etc/services - sync with NetBSD-8
[minix.git] / external / public-domain / sqlite / dist / sqlite3.c
blob7a635c4b6942efe3586617faeb48234f7325fccf
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.8.3.1. 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 sqlite3.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 ** This header file defines the interface that the SQLite library
41 ** presents to client programs. If a C-function, structure, datatype,
42 ** or constant definition does not appear in this file, then it is
43 ** not a published API of SQLite, is subject to change without
44 ** notice, and should not be referenced by programs that use SQLite.
46 ** Some of the definitions that are in this file are marked as
47 ** "experimental". Experimental interfaces are normally new
48 ** features recently added to SQLite. We do not anticipate changes
49 ** to experimental interfaces but reserve the right to make minor changes
50 ** if experience from use "in the wild" suggest such changes are prudent.
52 ** The official C-language API documentation for SQLite is derived
53 ** from comments in this file. This file is the authoritative source
54 ** on how SQLite interfaces are suppose to operate.
56 ** The name of this file under configuration management is "sqlite.h.in".
57 ** The makefile makes some minor changes to this file (such as inserting
58 ** the version number) and changes its name to "sqlite3.h" as
59 ** part of the build process.
61 #ifndef _SQLITE3_H_
62 #define _SQLITE3_H_
63 #include <stdarg.h> /* Needed for the definition of va_list */
66 ** Make sure we can call this stuff from C++.
68 #if 0
69 extern "C" {
70 #endif
74 ** Add the ability to override 'extern'
76 #ifndef SQLITE_EXTERN
77 # define SQLITE_EXTERN extern
78 #endif
80 #ifndef SQLITE_API
81 # define SQLITE_API
82 #endif
86 ** These no-op macros are used in front of interfaces to mark those
87 ** interfaces as either deprecated or experimental. New applications
88 ** should not use deprecated interfaces - they are support for backwards
89 ** compatibility only. Application writers should be aware that
90 ** experimental interfaces are subject to change in point releases.
92 ** These macros used to resolve to various kinds of compiler magic that
93 ** would generate warning messages when they were used. But that
94 ** compiler magic ended up generating such a flurry of bug reports
95 ** that we have taken it all out and gone back to using simple
96 ** noop macros.
98 #define SQLITE_DEPRECATED
99 #define SQLITE_EXPERIMENTAL
102 ** Ensure these symbols were not defined by some previous header file.
104 #ifdef SQLITE_VERSION
105 # undef SQLITE_VERSION
106 #endif
107 #ifdef SQLITE_VERSION_NUMBER
108 # undef SQLITE_VERSION_NUMBER
109 #endif
112 ** CAPI3REF: Compile-Time Library Version Numbers
114 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
115 ** evaluates to a string literal that is the SQLite version in the
116 ** format "X.Y.Z" where X is the major version number (always 3 for
117 ** SQLite3) and Y is the minor version number and Z is the release number.)^
118 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
119 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
120 ** numbers used in [SQLITE_VERSION].)^
121 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
122 ** be larger than the release from which it is derived. Either Y will
123 ** be held constant and Z will be incremented or else Y will be incremented
124 ** and Z will be reset to zero.
126 ** Since version 3.6.18, SQLite source code has been stored in the
127 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
128 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
129 ** a string which identifies a particular check-in of SQLite
130 ** within its configuration management system. ^The SQLITE_SOURCE_ID
131 ** string contains the date and time of the check-in (UTC) and an SHA1
132 ** hash of the entire source tree.
134 ** See also: [sqlite3_libversion()],
135 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
136 ** [sqlite_version()] and [sqlite_source_id()].
138 #define SQLITE_VERSION "3.8.3.1"
139 #define SQLITE_VERSION_NUMBER 3008003
140 #define SQLITE_SOURCE_ID "2014-02-11 14:52:19 ea3317a4803d71d88183b29f1d3086f46d68a00e"
143 ** CAPI3REF: Run-Time Library Version Numbers
144 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
146 ** These interfaces provide the same information as the [SQLITE_VERSION],
147 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
148 ** but are associated with the library instead of the header file. ^(Cautious
149 ** programmers might include assert() statements in their application to
150 ** verify that values returned by these interfaces match the macros in
151 ** the header, and thus insure that the application is
152 ** compiled with matching library and header files.
154 ** <blockquote><pre>
155 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
156 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
157 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
158 ** </pre></blockquote>)^
160 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
161 ** macro. ^The sqlite3_libversion() function returns a pointer to the
162 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
163 ** function is provided for use in DLLs since DLL users usually do not have
164 ** direct access to string constants within the DLL. ^The
165 ** sqlite3_libversion_number() function returns an integer equal to
166 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
167 ** a pointer to a string constant whose value is the same as the
168 ** [SQLITE_SOURCE_ID] C preprocessor macro.
170 ** See also: [sqlite_version()] and [sqlite_source_id()].
172 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
173 SQLITE_API const char *sqlite3_libversion(void);
174 SQLITE_API const char *sqlite3_sourceid(void);
175 SQLITE_API int sqlite3_libversion_number(void);
178 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
180 ** ^The sqlite3_compileoption_used() function returns 0 or 1
181 ** indicating whether the specified option was defined at
182 ** compile time. ^The SQLITE_ prefix may be omitted from the
183 ** option name passed to sqlite3_compileoption_used().
185 ** ^The sqlite3_compileoption_get() function allows iterating
186 ** over the list of options that were defined at compile time by
187 ** returning the N-th compile time option string. ^If N is out of range,
188 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
189 ** prefix is omitted from any strings returned by
190 ** sqlite3_compileoption_get().
192 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
193 ** and sqlite3_compileoption_get() may be omitted by specifying the
194 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
196 ** See also: SQL functions [sqlite_compileoption_used()] and
197 ** [sqlite_compileoption_get()] and the [compile_options pragma].
199 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
200 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
201 SQLITE_API const char *sqlite3_compileoption_get(int N);
202 #endif
205 ** CAPI3REF: Test To See If The Library Is Threadsafe
207 ** ^The sqlite3_threadsafe() function returns zero if and only if
208 ** SQLite was compiled with mutexing code omitted due to the
209 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
211 ** SQLite can be compiled with or without mutexes. When
212 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
213 ** are enabled and SQLite is threadsafe. When the
214 ** [SQLITE_THREADSAFE] macro is 0,
215 ** the mutexes are omitted. Without the mutexes, it is not safe
216 ** to use SQLite concurrently from more than one thread.
218 ** Enabling mutexes incurs a measurable performance penalty.
219 ** So if speed is of utmost importance, it makes sense to disable
220 ** the mutexes. But for maximum safety, mutexes should be enabled.
221 ** ^The default behavior is for mutexes to be enabled.
223 ** This interface can be used by an application to make sure that the
224 ** version of SQLite that it is linking against was compiled with
225 ** the desired setting of the [SQLITE_THREADSAFE] macro.
227 ** This interface only reports on the compile-time mutex setting
228 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
229 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
230 ** can be fully or partially disabled using a call to [sqlite3_config()]
231 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
232 ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
233 ** sqlite3_threadsafe() function shows only the compile-time setting of
234 ** thread safety, not any run-time changes to that setting made by
235 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
236 ** is unchanged by calls to sqlite3_config().)^
238 ** See the [threading mode] documentation for additional information.
240 SQLITE_API int sqlite3_threadsafe(void);
243 ** CAPI3REF: Database Connection Handle
244 ** KEYWORDS: {database connection} {database connections}
246 ** Each open SQLite database is represented by a pointer to an instance of
247 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
248 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
249 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
250 ** and [sqlite3_close_v2()] are its destructors. There are many other
251 ** interfaces (such as
252 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
253 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
254 ** sqlite3 object.
256 typedef struct sqlite3 sqlite3;
259 ** CAPI3REF: 64-Bit Integer Types
260 ** KEYWORDS: sqlite_int64 sqlite_uint64
262 ** Because there is no cross-platform way to specify 64-bit integer types
263 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
265 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
266 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
267 ** compatibility only.
269 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
270 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
271 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
272 ** between 0 and +18446744073709551615 inclusive.
274 #ifdef SQLITE_INT64_TYPE
275 typedef SQLITE_INT64_TYPE sqlite_int64;
276 typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
277 #elif defined(_MSC_VER) || defined(__BORLANDC__)
278 typedef __int64 sqlite_int64;
279 typedef unsigned __int64 sqlite_uint64;
280 #else
281 typedef long long int sqlite_int64;
282 typedef unsigned long long int sqlite_uint64;
283 #endif
284 typedef sqlite_int64 sqlite3_int64;
285 typedef sqlite_uint64 sqlite3_uint64;
288 ** If compiling for a processor that lacks floating point support,
289 ** substitute integer for floating-point.
291 #ifdef SQLITE_OMIT_FLOATING_POINT
292 # define double sqlite3_int64
293 #endif
296 ** CAPI3REF: Closing A Database Connection
298 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
299 ** for the [sqlite3] object.
300 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
301 ** the [sqlite3] object is successfully destroyed and all associated
302 ** resources are deallocated.
304 ** ^If the database connection is associated with unfinalized prepared
305 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
306 ** will leave the database connection open and return [SQLITE_BUSY].
307 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
308 ** and unfinished sqlite3_backups, then the database connection becomes
309 ** an unusable "zombie" which will automatically be deallocated when the
310 ** last prepared statement is finalized or the last sqlite3_backup is
311 ** finished. The sqlite3_close_v2() interface is intended for use with
312 ** host languages that are garbage collected, and where the order in which
313 ** destructors are called is arbitrary.
315 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
316 ** [sqlite3_blob_close | close] all [BLOB handles], and
317 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
318 ** with the [sqlite3] object prior to attempting to close the object. ^If
319 ** sqlite3_close_v2() is called on a [database connection] that still has
320 ** outstanding [prepared statements], [BLOB handles], and/or
321 ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
322 ** of resources is deferred until all [prepared statements], [BLOB handles],
323 ** and [sqlite3_backup] objects are also destroyed.
325 ** ^If an [sqlite3] object is destroyed while a transaction is open,
326 ** the transaction is automatically rolled back.
328 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
329 ** must be either a NULL
330 ** pointer or an [sqlite3] object pointer obtained
331 ** from [sqlite3_open()], [sqlite3_open16()], or
332 ** [sqlite3_open_v2()], and not previously closed.
333 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
334 ** argument is a harmless no-op.
336 SQLITE_API int sqlite3_close(sqlite3*);
337 SQLITE_API int sqlite3_close_v2(sqlite3*);
340 ** The type for a callback function.
341 ** This is legacy and deprecated. It is included for historical
342 ** compatibility and is not documented.
344 typedef int (*sqlite3_callback)(void*,int,char**, char**);
347 ** CAPI3REF: One-Step Query Execution Interface
349 ** The sqlite3_exec() interface is a convenience wrapper around
350 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
351 ** that allows an application to run multiple statements of SQL
352 ** without having to use a lot of C code.
354 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
355 ** semicolon-separate SQL statements passed into its 2nd argument,
356 ** in the context of the [database connection] passed in as its 1st
357 ** argument. ^If the callback function of the 3rd argument to
358 ** sqlite3_exec() is not NULL, then it is invoked for each result row
359 ** coming out of the evaluated SQL statements. ^The 4th argument to
360 ** sqlite3_exec() is relayed through to the 1st argument of each
361 ** callback invocation. ^If the callback pointer to sqlite3_exec()
362 ** is NULL, then no callback is ever invoked and result rows are
363 ** ignored.
365 ** ^If an error occurs while evaluating the SQL statements passed into
366 ** sqlite3_exec(), then execution of the current statement stops and
367 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
368 ** is not NULL then any error message is written into memory obtained
369 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
370 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
371 ** on error message strings returned through the 5th parameter of
372 ** of sqlite3_exec() after the error message string is no longer needed.
373 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
374 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
375 ** NULL before returning.
377 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
378 ** routine returns SQLITE_ABORT without invoking the callback again and
379 ** without running any subsequent SQL statements.
381 ** ^The 2nd argument to the sqlite3_exec() callback function is the
382 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
383 ** callback is an array of pointers to strings obtained as if from
384 ** [sqlite3_column_text()], one for each column. ^If an element of a
385 ** result row is NULL then the corresponding string pointer for the
386 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
387 ** sqlite3_exec() callback is an array of pointers to strings where each
388 ** entry represents the name of corresponding result column as obtained
389 ** from [sqlite3_column_name()].
391 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
392 ** to an empty string, or a pointer that contains only whitespace and/or
393 ** SQL comments, then no SQL statements are evaluated and the database
394 ** is not changed.
396 ** Restrictions:
398 ** <ul>
399 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
400 ** is a valid and open [database connection].
401 ** <li> The application must not close the [database connection] specified by
402 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
403 ** <li> The application must not modify the SQL statement text passed into
404 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
405 ** </ul>
407 SQLITE_API int sqlite3_exec(
408 sqlite3*, /* An open database */
409 const char *sql, /* SQL to be evaluated */
410 int (*callback)(void*,int,char**,char**), /* Callback function */
411 void *, /* 1st argument to callback */
412 char **errmsg /* Error msg written here */
416 ** CAPI3REF: Result Codes
417 ** KEYWORDS: SQLITE_OK {error code} {error codes}
418 ** KEYWORDS: {result code} {result codes}
420 ** Many SQLite functions return an integer result code from the set shown
421 ** here in order to indicate success or failure.
423 ** New error codes may be added in future versions of SQLite.
425 ** See also: [SQLITE_IOERR_READ | extended result codes],
426 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
428 #define SQLITE_OK 0 /* Successful result */
429 /* beginning-of-error-codes */
430 #define SQLITE_ERROR 1 /* SQL error or missing database */
431 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
432 #define SQLITE_PERM 3 /* Access permission denied */
433 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
434 #define SQLITE_BUSY 5 /* The database file is locked */
435 #define SQLITE_LOCKED 6 /* A table in the database is locked */
436 #define SQLITE_NOMEM 7 /* A malloc() failed */
437 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
438 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
439 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
440 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
441 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
442 #define SQLITE_FULL 13 /* Insertion failed because database is full */
443 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
444 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
445 #define SQLITE_EMPTY 16 /* Database is empty */
446 #define SQLITE_SCHEMA 17 /* The database schema changed */
447 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
448 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
449 #define SQLITE_MISMATCH 20 /* Data type mismatch */
450 #define SQLITE_MISUSE 21 /* Library used incorrectly */
451 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
452 #define SQLITE_AUTH 23 /* Authorization denied */
453 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
454 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
455 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
456 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
457 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
458 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
459 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
460 /* end-of-error-codes */
463 ** CAPI3REF: Extended Result Codes
464 ** KEYWORDS: {extended error code} {extended error codes}
465 ** KEYWORDS: {extended result code} {extended result codes}
467 ** In its default configuration, SQLite API routines return one of 26 integer
468 ** [SQLITE_OK | result codes]. However, experience has shown that many of
469 ** these result codes are too coarse-grained. They do not provide as
470 ** much information about problems as programmers might like. In an effort to
471 ** address this, newer versions of SQLite (version 3.3.8 and later) include
472 ** support for additional result codes that provide more detailed information
473 ** about errors. The extended result codes are enabled or disabled
474 ** on a per database connection basis using the
475 ** [sqlite3_extended_result_codes()] API.
477 ** Some of the available extended result codes are listed here.
478 ** One may expect the number of extended result codes will increase
479 ** over time. Software that uses extended result codes should expect
480 ** to see new result codes in future releases of SQLite.
482 ** The SQLITE_OK result code will never be extended. It will always
483 ** be exactly zero.
485 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
486 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
487 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
488 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
489 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
490 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
491 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
492 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
493 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
494 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
495 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
496 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
497 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
498 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
499 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
500 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
501 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
502 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
503 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
504 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
505 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
506 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
507 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
508 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
509 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
510 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
511 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
512 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
513 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
514 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
515 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
516 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
517 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
518 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
519 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
520 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
521 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
522 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
523 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
524 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
525 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
526 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
527 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
528 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
529 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
530 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
531 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
532 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
533 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
534 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
535 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
536 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
539 ** CAPI3REF: Flags For File Open Operations
541 ** These bit values are intended for use in the
542 ** 3rd parameter to the [sqlite3_open_v2()] interface and
543 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
545 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
546 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
547 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
548 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
549 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
550 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
551 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
552 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
553 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
554 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
555 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
556 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
557 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
558 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
559 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
560 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
561 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
562 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
563 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
564 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
566 /* Reserved: 0x00F00000 */
569 ** CAPI3REF: Device Characteristics
571 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
572 ** object returns an integer which is a vector of these
573 ** bit values expressing I/O characteristics of the mass storage
574 ** device that holds the file that the [sqlite3_io_methods]
575 ** refers to.
577 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
578 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
579 ** mean that writes of blocks that are nnn bytes in size and
580 ** are aligned to an address which is an integer multiple of
581 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
582 ** that when data is appended to a file, the data is appended
583 ** first then the size of the file is extended, never the other
584 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
585 ** information is written to disk in the same order as calls
586 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
587 ** after reboot following a crash or power loss, the only bytes in a
588 ** file that were written at the application level might have changed
589 ** and that adjacent bytes, even bytes within the same sector are
590 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
591 ** flag indicate that a file cannot be deleted when open.
593 #define SQLITE_IOCAP_ATOMIC 0x00000001
594 #define SQLITE_IOCAP_ATOMIC512 0x00000002
595 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
596 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
597 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
598 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
599 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
600 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
601 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
602 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
603 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
604 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
605 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
608 ** CAPI3REF: File Locking Levels
610 ** SQLite uses one of these integer values as the second
611 ** argument to calls it makes to the xLock() and xUnlock() methods
612 ** of an [sqlite3_io_methods] object.
614 #define SQLITE_LOCK_NONE 0
615 #define SQLITE_LOCK_SHARED 1
616 #define SQLITE_LOCK_RESERVED 2
617 #define SQLITE_LOCK_PENDING 3
618 #define SQLITE_LOCK_EXCLUSIVE 4
621 ** CAPI3REF: Synchronization Type Flags
623 ** When SQLite invokes the xSync() method of an
624 ** [sqlite3_io_methods] object it uses a combination of
625 ** these integer values as the second argument.
627 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
628 ** sync operation only needs to flush data to mass storage. Inode
629 ** information need not be flushed. If the lower four bits of the flag
630 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
631 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
632 ** to use Mac OS X style fullsync instead of fsync().
634 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
635 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
636 ** settings. The [synchronous pragma] determines when calls to the
637 ** xSync VFS method occur and applies uniformly across all platforms.
638 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
639 ** energetic or rigorous or forceful the sync operations are and
640 ** only make a difference on Mac OSX for the default SQLite code.
641 ** (Third-party VFS implementations might also make the distinction
642 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
643 ** operating systems natively supported by SQLite, only Mac OSX
644 ** cares about the difference.)
646 #define SQLITE_SYNC_NORMAL 0x00002
647 #define SQLITE_SYNC_FULL 0x00003
648 #define SQLITE_SYNC_DATAONLY 0x00010
651 ** CAPI3REF: OS Interface Open File Handle
653 ** An [sqlite3_file] object represents an open file in the
654 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
655 ** implementations will
656 ** want to subclass this object by appending additional fields
657 ** for their own use. The pMethods entry is a pointer to an
658 ** [sqlite3_io_methods] object that defines methods for performing
659 ** I/O operations on the open file.
661 typedef struct sqlite3_file sqlite3_file;
662 struct sqlite3_file {
663 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
667 ** CAPI3REF: OS Interface File Virtual Methods Object
669 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
670 ** [sqlite3_file] object (or, more commonly, a subclass of the
671 ** [sqlite3_file] object) with a pointer to an instance of this object.
672 ** This object defines the methods used to perform various operations
673 ** against the open file represented by the [sqlite3_file] object.
675 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
676 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
677 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
678 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
679 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
680 ** to NULL.
682 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
683 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
684 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
685 ** flag may be ORed in to indicate that only the data of the file
686 ** and not its inode needs to be synced.
688 ** The integer values to xLock() and xUnlock() are one of
689 ** <ul>
690 ** <li> [SQLITE_LOCK_NONE],
691 ** <li> [SQLITE_LOCK_SHARED],
692 ** <li> [SQLITE_LOCK_RESERVED],
693 ** <li> [SQLITE_LOCK_PENDING], or
694 ** <li> [SQLITE_LOCK_EXCLUSIVE].
695 ** </ul>
696 ** xLock() increases the lock. xUnlock() decreases the lock.
697 ** The xCheckReservedLock() method checks whether any database connection,
698 ** either in this process or in some other process, is holding a RESERVED,
699 ** PENDING, or EXCLUSIVE lock on the file. It returns true
700 ** if such a lock exists and false otherwise.
702 ** The xFileControl() method is a generic interface that allows custom
703 ** VFS implementations to directly control an open file using the
704 ** [sqlite3_file_control()] interface. The second "op" argument is an
705 ** integer opcode. The third argument is a generic pointer intended to
706 ** point to a structure that may contain arguments or space in which to
707 ** write return values. Potential uses for xFileControl() might be
708 ** functions to enable blocking locks with timeouts, to change the
709 ** locking strategy (for example to use dot-file locks), to inquire
710 ** about the status of a lock, or to break stale locks. The SQLite
711 ** core reserves all opcodes less than 100 for its own use.
712 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
713 ** Applications that define a custom xFileControl method should use opcodes
714 ** greater than 100 to avoid conflicts. VFS implementations should
715 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
716 ** recognize.
718 ** The xSectorSize() method returns the sector size of the
719 ** device that underlies the file. The sector size is the
720 ** minimum write that can be performed without disturbing
721 ** other bytes in the file. The xDeviceCharacteristics()
722 ** method returns a bit vector describing behaviors of the
723 ** underlying device:
725 ** <ul>
726 ** <li> [SQLITE_IOCAP_ATOMIC]
727 ** <li> [SQLITE_IOCAP_ATOMIC512]
728 ** <li> [SQLITE_IOCAP_ATOMIC1K]
729 ** <li> [SQLITE_IOCAP_ATOMIC2K]
730 ** <li> [SQLITE_IOCAP_ATOMIC4K]
731 ** <li> [SQLITE_IOCAP_ATOMIC8K]
732 ** <li> [SQLITE_IOCAP_ATOMIC16K]
733 ** <li> [SQLITE_IOCAP_ATOMIC32K]
734 ** <li> [SQLITE_IOCAP_ATOMIC64K]
735 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
736 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
737 ** </ul>
739 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
740 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
741 ** mean that writes of blocks that are nnn bytes in size and
742 ** are aligned to an address which is an integer multiple of
743 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
744 ** that when data is appended to a file, the data is appended
745 ** first then the size of the file is extended, never the other
746 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
747 ** information is written to disk in the same order as calls
748 ** to xWrite().
750 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
751 ** in the unread portions of the buffer with zeros. A VFS that
752 ** fails to zero-fill short reads might seem to work. However,
753 ** failure to zero-fill short reads will eventually lead to
754 ** database corruption.
756 typedef struct sqlite3_io_methods sqlite3_io_methods;
757 struct sqlite3_io_methods {
758 int iVersion;
759 int (*xClose)(sqlite3_file*);
760 int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
761 int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
762 int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
763 int (*xSync)(sqlite3_file*, int flags);
764 int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
765 int (*xLock)(sqlite3_file*, int);
766 int (*xUnlock)(sqlite3_file*, int);
767 int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
768 int (*xFileControl)(sqlite3_file*, int op, void *pArg);
769 int (*xSectorSize)(sqlite3_file*);
770 int (*xDeviceCharacteristics)(sqlite3_file*);
771 /* Methods above are valid for version 1 */
772 int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
773 int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
774 void (*xShmBarrier)(sqlite3_file*);
775 int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
776 /* Methods above are valid for version 2 */
777 int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
778 int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
779 /* Methods above are valid for version 3 */
780 /* Additional methods may be added in future releases */
784 ** CAPI3REF: Standard File Control Opcodes
786 ** These integer constants are opcodes for the xFileControl method
787 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
788 ** interface.
790 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
791 ** opcode causes the xFileControl method to write the current state of
792 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
793 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
794 ** into an integer that the pArg argument points to. This capability
795 ** is used during testing and only needs to be supported when SQLITE_TEST
796 ** is defined.
797 ** <ul>
798 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
799 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
800 ** layer a hint of how large the database file will grow to be during the
801 ** current transaction. This hint is not guaranteed to be accurate but it
802 ** is often close. The underlying VFS might choose to preallocate database
803 ** file space based on this hint in order to help writes to the database
804 ** file run faster.
806 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
807 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
808 ** extends and truncates the database file in chunks of a size specified
809 ** by the user. The fourth argument to [sqlite3_file_control()] should
810 ** point to an integer (type int) containing the new chunk-size to use
811 ** for the nominated database. Allocating database file space in large
812 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
813 ** improve performance on some systems.
815 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
816 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
817 ** to the [sqlite3_file] object associated with a particular database
818 ** connection. See the [sqlite3_file_control()] documentation for
819 ** additional information.
821 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
822 ** No longer in use.
824 ** <li>[[SQLITE_FCNTL_SYNC]]
825 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
826 ** sent to the VFS immediately before the xSync method is invoked on a
827 ** database file descriptor. Or, if the xSync method is not invoked
828 ** because the user has configured SQLite with
829 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
830 ** of the xSync method. In most cases, the pointer argument passed with
831 ** this file-control is NULL. However, if the database file is being synced
832 ** as part of a multi-database commit, the argument points to a nul-terminated
833 ** string containing the transactions master-journal file name. VFSes that
834 ** do not need this signal should silently ignore this opcode. Applications
835 ** should not call [sqlite3_file_control()] with this opcode as doing so may
836 ** disrupt the operation of the specialized VFSes that do require it.
838 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
839 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
840 ** and sent to the VFS after a transaction has been committed immediately
841 ** but before the database is unlocked. VFSes that do not need this signal
842 ** should silently ignore this opcode. Applications should not call
843 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
844 ** operation of the specialized VFSes that do require it.
846 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
847 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
848 ** retry counts and intervals for certain disk I/O operations for the
849 ** windows [VFS] in order to provide robustness in the presence of
850 ** anti-virus programs. By default, the windows VFS will retry file read,
851 ** file write, and file delete operations up to 10 times, with a delay
852 ** of 25 milliseconds before the first retry and with the delay increasing
853 ** by an additional 25 milliseconds with each subsequent retry. This
854 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
855 ** to be adjusted. The values are changed for all database connections
856 ** within the same process. The argument is a pointer to an array of two
857 ** integers where the first integer i the new retry count and the second
858 ** integer is the delay. If either integer is negative, then the setting
859 ** is not changed but instead the prior value of that setting is written
860 ** into the array entry, allowing the current retry settings to be
861 ** interrogated. The zDbName parameter is ignored.
863 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
864 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
865 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
866 ** write ahead log and shared memory files used for transaction control
867 ** are automatically deleted when the latest connection to the database
868 ** closes. Setting persistent WAL mode causes those files to persist after
869 ** close. Persisting the files is useful when other processes that do not
870 ** have write permission on the directory containing the database file want
871 ** to read the database file, as the WAL and shared memory files must exist
872 ** in order for the database to be readable. The fourth parameter to
873 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
874 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
875 ** WAL mode. If the integer is -1, then it is overwritten with the current
876 ** WAL persistence setting.
878 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
879 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
880 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
881 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
882 ** xDeviceCharacteristics methods. The fourth parameter to
883 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
884 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
885 ** mode. If the integer is -1, then it is overwritten with the current
886 ** zero-damage mode setting.
888 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
889 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
890 ** a write transaction to indicate that, unless it is rolled back for some
891 ** reason, the entire database file will be overwritten by the current
892 ** transaction. This is used by VACUUM operations.
894 ** <li>[[SQLITE_FCNTL_VFSNAME]]
895 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
896 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
897 ** final bottom-level VFS are written into memory obtained from
898 ** [sqlite3_malloc()] and the result is stored in the char* variable
899 ** that the fourth parameter of [sqlite3_file_control()] points to.
900 ** The caller is responsible for freeing the memory when done. As with
901 ** all file-control actions, there is no guarantee that this will actually
902 ** do anything. Callers should initialize the char* variable to a NULL
903 ** pointer in case this file-control is not implemented. This file-control
904 ** is intended for diagnostic use only.
906 ** <li>[[SQLITE_FCNTL_PRAGMA]]
907 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
908 ** file control is sent to the open [sqlite3_file] object corresponding
909 ** to the database file to which the pragma statement refers. ^The argument
910 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
911 ** pointers to strings (char**) in which the second element of the array
912 ** is the name of the pragma and the third element is the argument to the
913 ** pragma or NULL if the pragma has no argument. ^The handler for an
914 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
915 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
916 ** or the equivalent and that string will become the result of the pragma or
917 ** the error message if the pragma fails. ^If the
918 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
919 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
920 ** file control returns [SQLITE_OK], then the parser assumes that the
921 ** VFS has handled the PRAGMA itself and the parser generates a no-op
922 ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
923 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
924 ** that the VFS encountered an error while handling the [PRAGMA] and the
925 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
926 ** file control occurs at the beginning of pragma statement analysis and so
927 ** it is able to override built-in [PRAGMA] statements.
929 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
930 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
931 ** file-control may be invoked by SQLite on the database file handle
932 ** shortly after it is opened in order to provide a custom VFS with access
933 ** to the connections busy-handler callback. The argument is of type (void **)
934 ** - an array of two (void *) values. The first (void *) actually points
935 ** to a function of type (int (*)(void *)). In order to invoke the connections
936 ** busy-handler, this function should be invoked with the second (void *) in
937 ** the array as the only argument. If it returns non-zero, then the operation
938 ** should be retried. If it returns zero, the custom VFS should abandon the
939 ** current operation.
941 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
942 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
943 ** to have SQLite generate a
944 ** temporary filename using the same algorithm that is followed to generate
945 ** temporary filenames for TEMP tables and other internal uses. The
946 ** argument should be a char** which will be filled with the filename
947 ** written into memory obtained from [sqlite3_malloc()]. The caller should
948 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
950 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
951 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
952 ** maximum number of bytes that will be used for memory-mapped I/O.
953 ** The argument is a pointer to a value of type sqlite3_int64 that
954 ** is an advisory maximum number of bytes in the file to memory map. The
955 ** pointer is overwritten with the old value. The limit is not changed if
956 ** the value originally pointed to is negative, and so the current limit
957 ** can be queried by passing in a pointer to a negative number. This
958 ** file-control is used internally to implement [PRAGMA mmap_size].
960 ** <li>[[SQLITE_FCNTL_TRACE]]
961 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
962 ** to the VFS about what the higher layers of the SQLite stack are doing.
963 ** This file control is used by some VFS activity tracing [shims].
964 ** The argument is a zero-terminated string. Higher layers in the
965 ** SQLite stack may generate instances of this file control if
966 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
968 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
969 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
970 ** pointer to an integer and it writes a boolean into that integer depending
971 ** on whether or not the file has been renamed, moved, or deleted since it
972 ** was first opened.
974 ** </ul>
976 #define SQLITE_FCNTL_LOCKSTATE 1
977 #define SQLITE_GET_LOCKPROXYFILE 2
978 #define SQLITE_SET_LOCKPROXYFILE 3
979 #define SQLITE_LAST_ERRNO 4
980 #define SQLITE_FCNTL_SIZE_HINT 5
981 #define SQLITE_FCNTL_CHUNK_SIZE 6
982 #define SQLITE_FCNTL_FILE_POINTER 7
983 #define SQLITE_FCNTL_SYNC_OMITTED 8
984 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
985 #define SQLITE_FCNTL_PERSIST_WAL 10
986 #define SQLITE_FCNTL_OVERWRITE 11
987 #define SQLITE_FCNTL_VFSNAME 12
988 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
989 #define SQLITE_FCNTL_PRAGMA 14
990 #define SQLITE_FCNTL_BUSYHANDLER 15
991 #define SQLITE_FCNTL_TEMPFILENAME 16
992 #define SQLITE_FCNTL_MMAP_SIZE 18
993 #define SQLITE_FCNTL_TRACE 19
994 #define SQLITE_FCNTL_HAS_MOVED 20
995 #define SQLITE_FCNTL_SYNC 21
996 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
999 ** CAPI3REF: Mutex Handle
1001 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1002 ** abstract type for a mutex object. The SQLite core never looks
1003 ** at the internal representation of an [sqlite3_mutex]. It only
1004 ** deals with pointers to the [sqlite3_mutex] object.
1006 ** Mutexes are created using [sqlite3_mutex_alloc()].
1008 typedef struct sqlite3_mutex sqlite3_mutex;
1011 ** CAPI3REF: OS Interface Object
1013 ** An instance of the sqlite3_vfs object defines the interface between
1014 ** the SQLite core and the underlying operating system. The "vfs"
1015 ** in the name of the object stands for "virtual file system". See
1016 ** the [VFS | VFS documentation] for further information.
1018 ** The value of the iVersion field is initially 1 but may be larger in
1019 ** future versions of SQLite. Additional fields may be appended to this
1020 ** object when the iVersion value is increased. Note that the structure
1021 ** of the sqlite3_vfs object changes in the transaction between
1022 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1023 ** modified.
1025 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1026 ** structure used by this VFS. mxPathname is the maximum length of
1027 ** a pathname in this VFS.
1029 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1030 ** the pNext pointer. The [sqlite3_vfs_register()]
1031 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1032 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1033 ** searches the list. Neither the application code nor the VFS
1034 ** implementation should use the pNext pointer.
1036 ** The pNext field is the only field in the sqlite3_vfs
1037 ** structure that SQLite will ever modify. SQLite will only access
1038 ** or modify this field while holding a particular static mutex.
1039 ** The application should never modify anything within the sqlite3_vfs
1040 ** object once the object has been registered.
1042 ** The zName field holds the name of the VFS module. The name must
1043 ** be unique across all VFS modules.
1045 ** [[sqlite3_vfs.xOpen]]
1046 ** ^SQLite guarantees that the zFilename parameter to xOpen
1047 ** is either a NULL pointer or string obtained
1048 ** from xFullPathname() with an optional suffix added.
1049 ** ^If a suffix is added to the zFilename parameter, it will
1050 ** consist of a single "-" character followed by no more than
1051 ** 11 alphanumeric and/or "-" characters.
1052 ** ^SQLite further guarantees that
1053 ** the string will be valid and unchanged until xClose() is
1054 ** called. Because of the previous sentence,
1055 ** the [sqlite3_file] can safely store a pointer to the
1056 ** filename if it needs to remember the filename for some reason.
1057 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1058 ** must invent its own temporary name for the file. ^Whenever the
1059 ** xFilename parameter is NULL it will also be the case that the
1060 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1062 ** The flags argument to xOpen() includes all bits set in
1063 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1064 ** or [sqlite3_open16()] is used, then flags includes at least
1065 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1066 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1067 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1069 ** ^(SQLite will also add one of the following flags to the xOpen()
1070 ** call, depending on the object being opened:
1072 ** <ul>
1073 ** <li> [SQLITE_OPEN_MAIN_DB]
1074 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1075 ** <li> [SQLITE_OPEN_TEMP_DB]
1076 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1077 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1078 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1079 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1080 ** <li> [SQLITE_OPEN_WAL]
1081 ** </ul>)^
1083 ** The file I/O implementation can use the object type flags to
1084 ** change the way it deals with files. For example, an application
1085 ** that does not care about crash recovery or rollback might make
1086 ** the open of a journal file a no-op. Writes to this journal would
1087 ** also be no-ops, and any attempt to read the journal would return
1088 ** SQLITE_IOERR. Or the implementation might recognize that a database
1089 ** file will be doing page-aligned sector reads and writes in a random
1090 ** order and set up its I/O subsystem accordingly.
1092 ** SQLite might also add one of the following flags to the xOpen method:
1094 ** <ul>
1095 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1096 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1097 ** </ul>
1099 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1100 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1101 ** will be set for TEMP databases and their journals, transient
1102 ** databases, and subjournals.
1104 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1105 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1106 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1107 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1108 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1109 ** be created, and that it is an error if it already exists.
1110 ** It is <i>not</i> used to indicate the file should be opened
1111 ** for exclusive access.
1113 ** ^At least szOsFile bytes of memory are allocated by SQLite
1114 ** to hold the [sqlite3_file] structure passed as the third
1115 ** argument to xOpen. The xOpen method does not have to
1116 ** allocate the structure; it should just fill it in. Note that
1117 ** the xOpen method must set the sqlite3_file.pMethods to either
1118 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1119 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1120 ** element will be valid after xOpen returns regardless of the success
1121 ** or failure of the xOpen call.
1123 ** [[sqlite3_vfs.xAccess]]
1124 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1125 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1126 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1127 ** to test whether a file is at least readable. The file can be a
1128 ** directory.
1130 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1131 ** output buffer xFullPathname. The exact size of the output buffer
1132 ** is also passed as a parameter to both methods. If the output buffer
1133 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1134 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1135 ** to prevent this by setting mxPathname to a sufficiently large value.
1137 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1138 ** interfaces are not strictly a part of the filesystem, but they are
1139 ** included in the VFS structure for completeness.
1140 ** The xRandomness() function attempts to return nBytes bytes
1141 ** of good-quality randomness into zOut. The return value is
1142 ** the actual number of bytes of randomness obtained.
1143 ** The xSleep() method causes the calling thread to sleep for at
1144 ** least the number of microseconds given. ^The xCurrentTime()
1145 ** method returns a Julian Day Number for the current date and time as
1146 ** a floating point value.
1147 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1148 ** Day Number multiplied by 86400000 (the number of milliseconds in
1149 ** a 24-hour day).
1150 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1151 ** date and time if that method is available (if iVersion is 2 or
1152 ** greater and the function pointer is not NULL) and will fall back
1153 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1155 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1156 ** are not used by the SQLite core. These optional interfaces are provided
1157 ** by some VFSes to facilitate testing of the VFS code. By overriding
1158 ** system calls with functions under its control, a test program can
1159 ** simulate faults and error conditions that would otherwise be difficult
1160 ** or impossible to induce. The set of system calls that can be overridden
1161 ** varies from one VFS to another, and from one version of the same VFS to the
1162 ** next. Applications that use these interfaces must be prepared for any
1163 ** or all of these interfaces to be NULL or for their behavior to change
1164 ** from one release to the next. Applications must not attempt to access
1165 ** any of these methods if the iVersion of the VFS is less than 3.
1167 typedef struct sqlite3_vfs sqlite3_vfs;
1168 typedef void (*sqlite3_syscall_ptr)(void);
1169 struct sqlite3_vfs {
1170 int iVersion; /* Structure version number (currently 3) */
1171 int szOsFile; /* Size of subclassed sqlite3_file */
1172 int mxPathname; /* Maximum file pathname length */
1173 sqlite3_vfs *pNext; /* Next registered VFS */
1174 const char *zName; /* Name of this virtual file system */
1175 void *pAppData; /* Pointer to application-specific data */
1176 int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1177 int flags, int *pOutFlags);
1178 int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1179 int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1180 int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1181 void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1182 void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1183 void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1184 void (*xDlClose)(sqlite3_vfs*, void*);
1185 int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1186 int (*xSleep)(sqlite3_vfs*, int microseconds);
1187 int (*xCurrentTime)(sqlite3_vfs*, double*);
1188 int (*xGetLastError)(sqlite3_vfs*, int, char *);
1190 ** The methods above are in version 1 of the sqlite_vfs object
1191 ** definition. Those that follow are added in version 2 or later
1193 int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1195 ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1196 ** Those below are for version 3 and greater.
1198 int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1199 sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1200 const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1202 ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1203 ** New fields may be appended in figure versions. The iVersion
1204 ** value will increment whenever this happens.
1209 ** CAPI3REF: Flags for the xAccess VFS method
1211 ** These integer constants can be used as the third parameter to
1212 ** the xAccess method of an [sqlite3_vfs] object. They determine
1213 ** what kind of permissions the xAccess method is looking for.
1214 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1215 ** simply checks whether the file exists.
1216 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1217 ** checks whether the named directory is both readable and writable
1218 ** (in other words, if files can be added, removed, and renamed within
1219 ** the directory).
1220 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1221 ** [temp_store_directory pragma], though this could change in a future
1222 ** release of SQLite.
1223 ** With SQLITE_ACCESS_READ, the xAccess method
1224 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1225 ** currently unused, though it might be used in a future release of
1226 ** SQLite.
1228 #define SQLITE_ACCESS_EXISTS 0
1229 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1230 #define SQLITE_ACCESS_READ 2 /* Unused */
1233 ** CAPI3REF: Flags for the xShmLock VFS method
1235 ** These integer constants define the various locking operations
1236 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1237 ** following are the only legal combinations of flags to the
1238 ** xShmLock method:
1240 ** <ul>
1241 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1242 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1243 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1244 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1245 ** </ul>
1247 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1248 ** was given no the corresponding lock.
1250 ** The xShmLock method can transition between unlocked and SHARED or
1251 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1252 ** and EXCLUSIVE.
1254 #define SQLITE_SHM_UNLOCK 1
1255 #define SQLITE_SHM_LOCK 2
1256 #define SQLITE_SHM_SHARED 4
1257 #define SQLITE_SHM_EXCLUSIVE 8
1260 ** CAPI3REF: Maximum xShmLock index
1262 ** The xShmLock method on [sqlite3_io_methods] may use values
1263 ** between 0 and this upper bound as its "offset" argument.
1264 ** The SQLite core will never attempt to acquire or release a
1265 ** lock outside of this range
1267 #define SQLITE_SHM_NLOCK 8
1271 ** CAPI3REF: Initialize The SQLite Library
1273 ** ^The sqlite3_initialize() routine initializes the
1274 ** SQLite library. ^The sqlite3_shutdown() routine
1275 ** deallocates any resources that were allocated by sqlite3_initialize().
1276 ** These routines are designed to aid in process initialization and
1277 ** shutdown on embedded systems. Workstation applications using
1278 ** SQLite normally do not need to invoke either of these routines.
1280 ** A call to sqlite3_initialize() is an "effective" call if it is
1281 ** the first time sqlite3_initialize() is invoked during the lifetime of
1282 ** the process, or if it is the first time sqlite3_initialize() is invoked
1283 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1284 ** of sqlite3_initialize() does any initialization. All other calls
1285 ** are harmless no-ops.)^
1287 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1288 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1289 ** an effective call to sqlite3_shutdown() does any deinitialization.
1290 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1292 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1293 ** is not. The sqlite3_shutdown() interface must only be called from a
1294 ** single thread. All open [database connections] must be closed and all
1295 ** other SQLite resources must be deallocated prior to invoking
1296 ** sqlite3_shutdown().
1298 ** Among other things, ^sqlite3_initialize() will invoke
1299 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1300 ** will invoke sqlite3_os_end().
1302 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1303 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1304 ** the library (perhaps it is unable to allocate a needed resource such
1305 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1307 ** ^The sqlite3_initialize() routine is called internally by many other
1308 ** SQLite interfaces so that an application usually does not need to
1309 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1310 ** calls sqlite3_initialize() so the SQLite library will be automatically
1311 ** initialized when [sqlite3_open()] is called if it has not be initialized
1312 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1313 ** compile-time option, then the automatic calls to sqlite3_initialize()
1314 ** are omitted and the application must call sqlite3_initialize() directly
1315 ** prior to using any other SQLite interface. For maximum portability,
1316 ** it is recommended that applications always invoke sqlite3_initialize()
1317 ** directly prior to using any other SQLite interface. Future releases
1318 ** of SQLite may require this. In other words, the behavior exhibited
1319 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1320 ** default behavior in some future release of SQLite.
1322 ** The sqlite3_os_init() routine does operating-system specific
1323 ** initialization of the SQLite library. The sqlite3_os_end()
1324 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1325 ** performed by these routines include allocation or deallocation
1326 ** of static resources, initialization of global variables,
1327 ** setting up a default [sqlite3_vfs] module, or setting up
1328 ** a default configuration using [sqlite3_config()].
1330 ** The application should never invoke either sqlite3_os_init()
1331 ** or sqlite3_os_end() directly. The application should only invoke
1332 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1333 ** interface is called automatically by sqlite3_initialize() and
1334 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1335 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1336 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1337 ** When [custom builds | built for other platforms]
1338 ** (using the [SQLITE_OS_OTHER=1] compile-time
1339 ** option) the application must supply a suitable implementation for
1340 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1341 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1342 ** must return [SQLITE_OK] on success and some other [error code] upon
1343 ** failure.
1345 SQLITE_API int sqlite3_initialize(void);
1346 SQLITE_API int sqlite3_shutdown(void);
1347 SQLITE_API int sqlite3_os_init(void);
1348 SQLITE_API int sqlite3_os_end(void);
1351 ** CAPI3REF: Configuring The SQLite Library
1353 ** The sqlite3_config() interface is used to make global configuration
1354 ** changes to SQLite in order to tune SQLite to the specific needs of
1355 ** the application. The default configuration is recommended for most
1356 ** applications and so this routine is usually not necessary. It is
1357 ** provided to support rare applications with unusual needs.
1359 ** The sqlite3_config() interface is not threadsafe. The application
1360 ** must insure that no other SQLite interfaces are invoked by other
1361 ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
1362 ** may only be invoked prior to library initialization using
1363 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1364 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1365 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1366 ** Note, however, that ^sqlite3_config() can be called as part of the
1367 ** implementation of an application-defined [sqlite3_os_init()].
1369 ** The first argument to sqlite3_config() is an integer
1370 ** [configuration option] that determines
1371 ** what property of SQLite is to be configured. Subsequent arguments
1372 ** vary depending on the [configuration option]
1373 ** in the first argument.
1375 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1376 ** ^If the option is unknown or SQLite is unable to set the option
1377 ** then this routine returns a non-zero [error code].
1379 SQLITE_API int sqlite3_config(int, ...);
1382 ** CAPI3REF: Configure database connections
1384 ** The sqlite3_db_config() interface is used to make configuration
1385 ** changes to a [database connection]. The interface is similar to
1386 ** [sqlite3_config()] except that the changes apply to a single
1387 ** [database connection] (specified in the first argument).
1389 ** The second argument to sqlite3_db_config(D,V,...) is the
1390 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1391 ** that indicates what aspect of the [database connection] is being configured.
1392 ** Subsequent arguments vary depending on the configuration verb.
1394 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1395 ** the call is considered successful.
1397 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1400 ** CAPI3REF: Memory Allocation Routines
1402 ** An instance of this object defines the interface between SQLite
1403 ** and low-level memory allocation routines.
1405 ** This object is used in only one place in the SQLite interface.
1406 ** A pointer to an instance of this object is the argument to
1407 ** [sqlite3_config()] when the configuration option is
1408 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1409 ** By creating an instance of this object
1410 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1411 ** during configuration, an application can specify an alternative
1412 ** memory allocation subsystem for SQLite to use for all of its
1413 ** dynamic memory needs.
1415 ** Note that SQLite comes with several [built-in memory allocators]
1416 ** that are perfectly adequate for the overwhelming majority of applications
1417 ** and that this object is only useful to a tiny minority of applications
1418 ** with specialized memory allocation requirements. This object is
1419 ** also used during testing of SQLite in order to specify an alternative
1420 ** memory allocator that simulates memory out-of-memory conditions in
1421 ** order to verify that SQLite recovers gracefully from such
1422 ** conditions.
1424 ** The xMalloc, xRealloc, and xFree methods must work like the
1425 ** malloc(), realloc() and free() functions from the standard C library.
1426 ** ^SQLite guarantees that the second argument to
1427 ** xRealloc is always a value returned by a prior call to xRoundup.
1429 ** xSize should return the allocated size of a memory allocation
1430 ** previously obtained from xMalloc or xRealloc. The allocated size
1431 ** is always at least as big as the requested size but may be larger.
1433 ** The xRoundup method returns what would be the allocated size of
1434 ** a memory allocation given a particular requested size. Most memory
1435 ** allocators round up memory allocations at least to the next multiple
1436 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1437 ** Every memory allocation request coming in through [sqlite3_malloc()]
1438 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1439 ** that causes the corresponding memory allocation to fail.
1441 ** The xInit method initializes the memory allocator. For example,
1442 ** it might allocate any require mutexes or initialize internal data
1443 ** structures. The xShutdown method is invoked (indirectly) by
1444 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1445 ** by xInit. The pAppData pointer is used as the only parameter to
1446 ** xInit and xShutdown.
1448 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1449 ** the xInit method, so the xInit method need not be threadsafe. The
1450 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1451 ** not need to be threadsafe either. For all other methods, SQLite
1452 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1453 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1454 ** it is by default) and so the methods are automatically serialized.
1455 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1456 ** methods must be threadsafe or else make their own arrangements for
1457 ** serialization.
1459 ** SQLite will never invoke xInit() more than once without an intervening
1460 ** call to xShutdown().
1462 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1463 struct sqlite3_mem_methods {
1464 void *(*xMalloc)(int); /* Memory allocation function */
1465 void (*xFree)(void*); /* Free a prior allocation */
1466 void *(*xRealloc)(void*,int); /* Resize an allocation */
1467 int (*xSize)(void*); /* Return the size of an allocation */
1468 int (*xRoundup)(int); /* Round up request size to allocation size */
1469 int (*xInit)(void*); /* Initialize the memory allocator */
1470 void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1471 void *pAppData; /* Argument to xInit() and xShutdown() */
1475 ** CAPI3REF: Configuration Options
1476 ** KEYWORDS: {configuration option}
1478 ** These constants are the available integer configuration options that
1479 ** can be passed as the first argument to the [sqlite3_config()] interface.
1481 ** New configuration options may be added in future releases of SQLite.
1482 ** Existing configuration options might be discontinued. Applications
1483 ** should check the return code from [sqlite3_config()] to make sure that
1484 ** the call worked. The [sqlite3_config()] interface will return a
1485 ** non-zero [error code] if a discontinued or unsupported configuration option
1486 ** is invoked.
1488 ** <dl>
1489 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1490 ** <dd>There are no arguments to this option. ^This option sets the
1491 ** [threading mode] to Single-thread. In other words, it disables
1492 ** all mutexing and puts SQLite into a mode where it can only be used
1493 ** by a single thread. ^If SQLite is compiled with
1494 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1495 ** it is not possible to change the [threading mode] from its default
1496 ** value of Single-thread and so [sqlite3_config()] will return
1497 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1498 ** configuration option.</dd>
1500 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1501 ** <dd>There are no arguments to this option. ^This option sets the
1502 ** [threading mode] to Multi-thread. In other words, it disables
1503 ** mutexing on [database connection] and [prepared statement] objects.
1504 ** The application is responsible for serializing access to
1505 ** [database connections] and [prepared statements]. But other mutexes
1506 ** are enabled so that SQLite will be safe to use in a multi-threaded
1507 ** environment as long as no two threads attempt to use the same
1508 ** [database connection] at the same time. ^If SQLite is compiled with
1509 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1510 ** it is not possible to set the Multi-thread [threading mode] and
1511 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1512 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1514 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1515 ** <dd>There are no arguments to this option. ^This option sets the
1516 ** [threading mode] to Serialized. In other words, this option enables
1517 ** all mutexes including the recursive
1518 ** mutexes on [database connection] and [prepared statement] objects.
1519 ** In this mode (which is the default when SQLite is compiled with
1520 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1521 ** to [database connections] and [prepared statements] so that the
1522 ** application is free to use the same [database connection] or the
1523 ** same [prepared statement] in different threads at the same time.
1524 ** ^If SQLite is compiled with
1525 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1526 ** it is not possible to set the Serialized [threading mode] and
1527 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1528 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1530 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1531 ** <dd> ^(This option takes a single argument which is a pointer to an
1532 ** instance of the [sqlite3_mem_methods] structure. The argument specifies
1533 ** alternative low-level memory allocation routines to be used in place of
1534 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1535 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1536 ** before the [sqlite3_config()] call returns.</dd>
1538 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1539 ** <dd> ^(This option takes a single argument which is a pointer to an
1540 ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
1541 ** structure is filled with the currently defined memory allocation routines.)^
1542 ** This option can be used to overload the default memory allocation
1543 ** routines with a wrapper that simulations memory allocation failure or
1544 ** tracks memory usage, for example. </dd>
1546 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1547 ** <dd> ^This option takes single argument of type int, interpreted as a
1548 ** boolean, which enables or disables the collection of memory allocation
1549 ** statistics. ^(When memory allocation statistics are disabled, the
1550 ** following SQLite interfaces become non-operational:
1551 ** <ul>
1552 ** <li> [sqlite3_memory_used()]
1553 ** <li> [sqlite3_memory_highwater()]
1554 ** <li> [sqlite3_soft_heap_limit64()]
1555 ** <li> [sqlite3_status()]
1556 ** </ul>)^
1557 ** ^Memory allocation statistics are enabled by default unless SQLite is
1558 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1559 ** allocation statistics are disabled by default.
1560 ** </dd>
1562 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1563 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1564 ** scratch memory. There are three arguments: A pointer an 8-byte
1565 ** aligned memory buffer from which the scratch allocations will be
1566 ** drawn, the size of each scratch allocation (sz),
1567 ** and the maximum number of scratch allocations (N). The sz
1568 ** argument must be a multiple of 16.
1569 ** The first argument must be a pointer to an 8-byte aligned buffer
1570 ** of at least sz*N bytes of memory.
1571 ** ^SQLite will use no more than two scratch buffers per thread. So
1572 ** N should be set to twice the expected maximum number of threads.
1573 ** ^SQLite will never require a scratch buffer that is more than 6
1574 ** times the database page size. ^If SQLite needs needs additional
1575 ** scratch memory beyond what is provided by this configuration option, then
1576 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1578 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1579 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1580 ** the database page cache with the default page cache implementation.
1581 ** This configuration should not be used if an application-define page
1582 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1583 ** There are three arguments to this option: A pointer to 8-byte aligned
1584 ** memory, the size of each page buffer (sz), and the number of pages (N).
1585 ** The sz argument should be the size of the largest database page
1586 ** (a power of two between 512 and 32768) plus a little extra for each
1587 ** page header. ^The page header size is 20 to 40 bytes depending on
1588 ** the host architecture. ^It is harmless, apart from the wasted memory,
1589 ** to make sz a little too large. The first
1590 ** argument should point to an allocation of at least sz*N bytes of memory.
1591 ** ^SQLite will use the memory provided by the first argument to satisfy its
1592 ** memory needs for the first N pages that it adds to cache. ^If additional
1593 ** page cache memory is needed beyond what is provided by this option, then
1594 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1595 ** The pointer in the first argument must
1596 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1597 ** will be undefined.</dd>
1599 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1600 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1601 ** for all of its dynamic memory allocation needs beyond those provided
1602 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1603 ** There are three arguments: An 8-byte aligned pointer to the memory,
1604 ** the number of bytes in the memory buffer, and the minimum allocation size.
1605 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1606 ** to using its default memory allocator (the system malloc() implementation),
1607 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1608 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1609 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1610 ** allocator is engaged to handle all of SQLites memory allocation needs.
1611 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1612 ** boundary or subsequent behavior of SQLite will be undefined.
1613 ** The minimum allocation size is capped at 2**12. Reasonable values
1614 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1616 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1617 ** <dd> ^(This option takes a single argument which is a pointer to an
1618 ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
1619 ** alternative low-level mutex routines to be used in place
1620 ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
1621 ** content of the [sqlite3_mutex_methods] structure before the call to
1622 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1623 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1624 ** the entire mutexing subsystem is omitted from the build and hence calls to
1625 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1626 ** return [SQLITE_ERROR].</dd>
1628 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1629 ** <dd> ^(This option takes a single argument which is a pointer to an
1630 ** instance of the [sqlite3_mutex_methods] structure. The
1631 ** [sqlite3_mutex_methods]
1632 ** structure is filled with the currently defined mutex routines.)^
1633 ** This option can be used to overload the default mutex allocation
1634 ** routines with a wrapper used to track mutex usage for performance
1635 ** profiling or testing, for example. ^If SQLite is compiled with
1636 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1637 ** the entire mutexing subsystem is omitted from the build and hence calls to
1638 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1639 ** return [SQLITE_ERROR].</dd>
1641 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1642 ** <dd> ^(This option takes two arguments that determine the default
1643 ** memory allocation for the lookaside memory allocator on each
1644 ** [database connection]. The first argument is the
1645 ** size of each lookaside buffer slot and the second is the number of
1646 ** slots allocated to each database connection.)^ ^(This option sets the
1647 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1648 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1649 ** configuration on individual connections.)^ </dd>
1651 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1652 ** <dd> ^(This option takes a single argument which is a pointer to
1653 ** an [sqlite3_pcache_methods2] object. This object specifies the interface
1654 ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
1655 ** object and uses it for page cache memory allocations.</dd>
1657 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1658 ** <dd> ^(This option takes a single argument which is a pointer to an
1659 ** [sqlite3_pcache_methods2] object. SQLite copies of the current
1660 ** page cache implementation into that object.)^ </dd>
1662 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1663 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1664 ** global [error log].
1665 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1666 ** function with a call signature of void(*)(void*,int,const char*),
1667 ** and a pointer to void. ^If the function pointer is not NULL, it is
1668 ** invoked by [sqlite3_log()] to process each logging event. ^If the
1669 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1670 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1671 ** passed through as the first parameter to the application-defined logger
1672 ** function whenever that function is invoked. ^The second parameter to
1673 ** the logger function is a copy of the first parameter to the corresponding
1674 ** [sqlite3_log()] call and is intended to be a [result code] or an
1675 ** [extended result code]. ^The third parameter passed to the logger is
1676 ** log message after formatting via [sqlite3_snprintf()].
1677 ** The SQLite logging interface is not reentrant; the logger function
1678 ** supplied by the application must not invoke any SQLite interface.
1679 ** In a multi-threaded application, the application-defined logger
1680 ** function must be threadsafe. </dd>
1682 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1683 ** <dd>^(This option takes a single argument of type int. If non-zero, then
1684 ** URI handling is globally enabled. If the parameter is zero, then URI handling
1685 ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
1686 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
1687 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1688 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1689 ** connection is opened. ^If it is globally disabled, filenames are
1690 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1691 ** database connection is opened. ^(By default, URI handling is globally
1692 ** disabled. The default value may be changed by compiling with the
1693 ** [SQLITE_USE_URI] symbol defined.)^
1695 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1696 ** <dd>^This option takes a single integer argument which is interpreted as
1697 ** a boolean in order to enable or disable the use of covering indices for
1698 ** full table scans in the query optimizer. ^The default setting is determined
1699 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1700 ** if that compile-time option is omitted.
1701 ** The ability to disable the use of covering indices for full table scans
1702 ** is because some incorrectly coded legacy applications might malfunction
1703 ** when the optimization is enabled. Providing the ability to
1704 ** disable the optimization allows the older, buggy application code to work
1705 ** without change even with newer versions of SQLite.
1707 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1708 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1709 ** <dd> These options are obsolete and should not be used by new code.
1710 ** They are retained for backwards compatibility but are now no-ops.
1711 ** </dd>
1713 ** [[SQLITE_CONFIG_SQLLOG]]
1714 ** <dt>SQLITE_CONFIG_SQLLOG
1715 ** <dd>This option is only available if sqlite is compiled with the
1716 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1717 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1718 ** The second should be of type (void*). The callback is invoked by the library
1719 ** in three separate circumstances, identified by the value passed as the
1720 ** fourth parameter. If the fourth parameter is 0, then the database connection
1721 ** passed as the second argument has just been opened. The third argument
1722 ** points to a buffer containing the name of the main database file. If the
1723 ** fourth parameter is 1, then the SQL statement that the third parameter
1724 ** points to has just been executed. Or, if the fourth parameter is 2, then
1725 ** the connection being passed as the second parameter is being closed. The
1726 ** third parameter is passed NULL In this case. An example of using this
1727 ** configuration option can be seen in the "test_sqllog.c" source file in
1728 ** the canonical SQLite source tree.</dd>
1730 ** [[SQLITE_CONFIG_MMAP_SIZE]]
1731 ** <dt>SQLITE_CONFIG_MMAP_SIZE
1732 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1733 ** that are the default mmap size limit (the default setting for
1734 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1735 ** ^The default setting can be overridden by each database connection using
1736 ** either the [PRAGMA mmap_size] command, or by using the
1737 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
1738 ** cannot be changed at run-time. Nor may the maximum allowed mmap size
1739 ** exceed the compile-time maximum mmap size set by the
1740 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1741 ** ^If either argument to this option is negative, then that argument is
1742 ** changed to its compile-time default.
1744 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1745 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1746 ** <dd>^This option is only available if SQLite is compiled for Windows
1747 ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
1748 ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1749 ** that specifies the maximum size of the created heap.
1750 ** </dl>
1752 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
1753 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
1754 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
1755 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
1756 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
1757 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
1758 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
1759 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
1760 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
1761 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
1762 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
1763 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1764 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
1765 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
1766 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
1767 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
1768 #define SQLITE_CONFIG_URI 17 /* int */
1769 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
1770 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
1771 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
1772 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
1773 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
1774 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
1777 ** CAPI3REF: Database Connection Configuration Options
1779 ** These constants are the available integer configuration options that
1780 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1782 ** New configuration options may be added in future releases of SQLite.
1783 ** Existing configuration options might be discontinued. Applications
1784 ** should check the return code from [sqlite3_db_config()] to make sure that
1785 ** the call worked. ^The [sqlite3_db_config()] interface will return a
1786 ** non-zero [error code] if a discontinued or unsupported configuration option
1787 ** is invoked.
1789 ** <dl>
1790 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1791 ** <dd> ^This option takes three additional arguments that determine the
1792 ** [lookaside memory allocator] configuration for the [database connection].
1793 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1794 ** pointer to a memory buffer to use for lookaside memory.
1795 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1796 ** may be NULL in which case SQLite will allocate the
1797 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1798 ** size of each lookaside buffer slot. ^The third argument is the number of
1799 ** slots. The size of the buffer in the first argument must be greater than
1800 ** or equal to the product of the second and third arguments. The buffer
1801 ** must be aligned to an 8-byte boundary. ^If the second argument to
1802 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1803 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
1804 ** configuration for a database connection can only be changed when that
1805 ** connection is not currently using lookaside memory, or in other words
1806 ** when the "current value" returned by
1807 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
1808 ** Any attempt to change the lookaside memory configuration when lookaside
1809 ** memory is in use leaves the configuration unchanged and returns
1810 ** [SQLITE_BUSY].)^</dd>
1812 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
1813 ** <dd> ^This option is used to enable or disable the enforcement of
1814 ** [foreign key constraints]. There should be two additional arguments.
1815 ** The first argument is an integer which is 0 to disable FK enforcement,
1816 ** positive to enable FK enforcement or negative to leave FK enforcement
1817 ** unchanged. The second parameter is a pointer to an integer into which
1818 ** is written 0 or 1 to indicate whether FK enforcement is off or on
1819 ** following this call. The second parameter may be a NULL pointer, in
1820 ** which case the FK enforcement setting is not reported back. </dd>
1822 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
1823 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
1824 ** There should be two additional arguments.
1825 ** The first argument is an integer which is 0 to disable triggers,
1826 ** positive to enable triggers or negative to leave the setting unchanged.
1827 ** The second parameter is a pointer to an integer into which
1828 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
1829 ** following this call. The second parameter may be a NULL pointer, in
1830 ** which case the trigger setting is not reported back. </dd>
1832 ** </dl>
1834 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
1835 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
1836 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
1840 ** CAPI3REF: Enable Or Disable Extended Result Codes
1842 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1843 ** [extended result codes] feature of SQLite. ^The extended result
1844 ** codes are disabled by default for historical compatibility.
1846 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1849 ** CAPI3REF: Last Insert Rowid
1851 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
1852 ** has a unique 64-bit signed
1853 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1854 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1855 ** names are not also used by explicitly declared columns. ^If
1856 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1857 ** is another alias for the rowid.
1859 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
1860 ** most recent successful [INSERT] into a rowid table or [virtual table]
1861 ** on database connection D.
1862 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
1863 ** ^If no successful [INSERT]s into rowid tables
1864 ** have ever occurred on the database connection D,
1865 ** then sqlite3_last_insert_rowid(D) returns zero.
1867 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
1868 ** method, then this routine will return the [rowid] of the inserted
1869 ** row as long as the trigger or virtual table method is running.
1870 ** But once the trigger or virtual table method ends, the value returned
1871 ** by this routine reverts to what it was before the trigger or virtual
1872 ** table method began.)^
1874 ** ^An [INSERT] that fails due to a constraint violation is not a
1875 ** successful [INSERT] and does not change the value returned by this
1876 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1877 ** and INSERT OR ABORT make no changes to the return value of this
1878 ** routine when their insertion fails. ^(When INSERT OR REPLACE
1879 ** encounters a constraint violation, it does not fail. The
1880 ** INSERT continues to completion after deleting rows that caused
1881 ** the constraint problem so INSERT OR REPLACE will always change
1882 ** the return value of this interface.)^
1884 ** ^For the purposes of this routine, an [INSERT] is considered to
1885 ** be successful even if it is subsequently rolled back.
1887 ** This function is accessible to SQL statements via the
1888 ** [last_insert_rowid() SQL function].
1890 ** If a separate thread performs a new [INSERT] on the same
1891 ** database connection while the [sqlite3_last_insert_rowid()]
1892 ** function is running and thus changes the last insert [rowid],
1893 ** then the value returned by [sqlite3_last_insert_rowid()] is
1894 ** unpredictable and might not equal either the old or the new
1895 ** last insert [rowid].
1897 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1900 ** CAPI3REF: Count The Number Of Rows Modified
1902 ** ^This function returns the number of database rows that were changed
1903 ** or inserted or deleted by the most recently completed SQL statement
1904 ** on the [database connection] specified by the first parameter.
1905 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
1906 ** or [DELETE] statement are counted. Auxiliary changes caused by
1907 ** triggers or [foreign key actions] are not counted.)^ Use the
1908 ** [sqlite3_total_changes()] function to find the total number of changes
1909 ** including changes caused by triggers and foreign key actions.
1911 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
1912 ** are not counted. Only real table changes are counted.
1914 ** ^(A "row change" is a change to a single row of a single table
1915 ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
1916 ** are changed as side effects of [REPLACE] constraint resolution,
1917 ** rollback, ABORT processing, [DROP TABLE], or by any other
1918 ** mechanisms do not count as direct row changes.)^
1920 ** A "trigger context" is a scope of execution that begins and
1921 ** ends with the script of a [CREATE TRIGGER | trigger].
1922 ** Most SQL statements are
1923 ** evaluated outside of any trigger. This is the "top level"
1924 ** trigger context. If a trigger fires from the top level, a
1925 ** new trigger context is entered for the duration of that one
1926 ** trigger. Subtriggers create subcontexts for their duration.
1928 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1929 ** not create a new trigger context.
1931 ** ^This function returns the number of direct row changes in the
1932 ** most recent INSERT, UPDATE, or DELETE statement within the same
1933 ** trigger context.
1935 ** ^Thus, when called from the top level, this function returns the
1936 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1937 ** that also occurred at the top level. ^(Within the body of a trigger,
1938 ** the sqlite3_changes() interface can be called to find the number of
1939 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1940 ** statement within the body of the same trigger.
1941 ** However, the number returned does not include changes
1942 ** caused by subtriggers since those have their own context.)^
1944 ** See also the [sqlite3_total_changes()] interface, the
1945 ** [count_changes pragma], and the [changes() SQL function].
1947 ** If a separate thread makes changes on the same database connection
1948 ** while [sqlite3_changes()] is running then the value returned
1949 ** is unpredictable and not meaningful.
1951 SQLITE_API int sqlite3_changes(sqlite3*);
1954 ** CAPI3REF: Total Number Of Rows Modified
1956 ** ^This function returns the number of row changes caused by [INSERT],
1957 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1958 ** ^(The count returned by sqlite3_total_changes() includes all changes
1959 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
1960 ** [foreign key actions]. However,
1961 ** the count does not include changes used to implement [REPLACE] constraints,
1962 ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
1963 ** count does not include rows of views that fire an [INSTEAD OF trigger],
1964 ** though if the INSTEAD OF trigger makes changes of its own, those changes
1965 ** are counted.)^
1966 ** ^The sqlite3_total_changes() function counts the changes as soon as
1967 ** the statement that makes them is completed (when the statement handle
1968 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
1970 ** See also the [sqlite3_changes()] interface, the
1971 ** [count_changes pragma], and the [total_changes() SQL function].
1973 ** If a separate thread makes changes on the same database connection
1974 ** while [sqlite3_total_changes()] is running then the value
1975 ** returned is unpredictable and not meaningful.
1977 SQLITE_API int sqlite3_total_changes(sqlite3*);
1980 ** CAPI3REF: Interrupt A Long-Running Query
1982 ** ^This function causes any pending database operation to abort and
1983 ** return at its earliest opportunity. This routine is typically
1984 ** called in response to a user action such as pressing "Cancel"
1985 ** or Ctrl-C where the user wants a long query operation to halt
1986 ** immediately.
1988 ** ^It is safe to call this routine from a thread different from the
1989 ** thread that is currently running the database operation. But it
1990 ** is not safe to call this routine with a [database connection] that
1991 ** is closed or might close before sqlite3_interrupt() returns.
1993 ** ^If an SQL operation is very nearly finished at the time when
1994 ** sqlite3_interrupt() is called, then it might not have an opportunity
1995 ** to be interrupted and might continue to completion.
1997 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1998 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1999 ** that is inside an explicit transaction, then the entire transaction
2000 ** will be rolled back automatically.
2002 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2003 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2004 ** that are started after the sqlite3_interrupt() call and before the
2005 ** running statements reaches zero are interrupted as if they had been
2006 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2007 ** that are started after the running statement count reaches zero are
2008 ** not effected by the sqlite3_interrupt().
2009 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2010 ** SQL statements is a no-op and has no effect on SQL statements
2011 ** that are started after the sqlite3_interrupt() call returns.
2013 ** If the database connection closes while [sqlite3_interrupt()]
2014 ** is running then bad things will likely happen.
2016 SQLITE_API void sqlite3_interrupt(sqlite3*);
2019 ** CAPI3REF: Determine If An SQL Statement Is Complete
2021 ** These routines are useful during command-line input to determine if the
2022 ** currently entered text seems to form a complete SQL statement or
2023 ** if additional input is needed before sending the text into
2024 ** SQLite for parsing. ^These routines return 1 if the input string
2025 ** appears to be a complete SQL statement. ^A statement is judged to be
2026 ** complete if it ends with a semicolon token and is not a prefix of a
2027 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2028 ** string literals or quoted identifier names or comments are not
2029 ** independent tokens (they are part of the token in which they are
2030 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2031 ** and comments that follow the final semicolon are ignored.
2033 ** ^These routines return 0 if the statement is incomplete. ^If a
2034 ** memory allocation fails, then SQLITE_NOMEM is returned.
2036 ** ^These routines do not parse the SQL statements thus
2037 ** will not detect syntactically incorrect SQL.
2039 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2040 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2041 ** automatically by sqlite3_complete16(). If that initialization fails,
2042 ** then the return value from sqlite3_complete16() will be non-zero
2043 ** regardless of whether or not the input SQL is complete.)^
2045 ** The input to [sqlite3_complete()] must be a zero-terminated
2046 ** UTF-8 string.
2048 ** The input to [sqlite3_complete16()] must be a zero-terminated
2049 ** UTF-16 string in native byte order.
2051 SQLITE_API int sqlite3_complete(const char *sql);
2052 SQLITE_API int sqlite3_complete16(const void *sql);
2055 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2057 ** ^This routine sets a callback function that might be invoked whenever
2058 ** an attempt is made to open a database table that another thread
2059 ** or process has locked.
2061 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2062 ** is returned immediately upon encountering the lock. ^If the busy callback
2063 ** is not NULL, then the callback might be invoked with two arguments.
2065 ** ^The first argument to the busy handler is a copy of the void* pointer which
2066 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2067 ** the busy handler callback is the number of times that the busy handler has
2068 ** been invoked for this locking event. ^If the
2069 ** busy callback returns 0, then no additional attempts are made to
2070 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2071 ** ^If the callback returns non-zero, then another attempt
2072 ** is made to open the database for reading and the cycle repeats.
2074 ** The presence of a busy handler does not guarantee that it will be invoked
2075 ** when there is lock contention. ^If SQLite determines that invoking the busy
2076 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2077 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2078 ** Consider a scenario where one process is holding a read lock that
2079 ** it is trying to promote to a reserved lock and
2080 ** a second process is holding a reserved lock that it is trying
2081 ** to promote to an exclusive lock. The first process cannot proceed
2082 ** because it is blocked by the second and the second process cannot
2083 ** proceed because it is blocked by the first. If both processes
2084 ** invoke the busy handlers, neither will make any progress. Therefore,
2085 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2086 ** will induce the first process to release its read lock and allow
2087 ** the second process to proceed.
2089 ** ^The default busy callback is NULL.
2091 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2092 ** when SQLite is in the middle of a large transaction where all the
2093 ** changes will not fit into the in-memory cache. SQLite will
2094 ** already hold a RESERVED lock on the database file, but it needs
2095 ** to promote this lock to EXCLUSIVE so that it can spill cache
2096 ** pages into the database file without harm to concurrent
2097 ** readers. ^If it is unable to promote the lock, then the in-memory
2098 ** cache will be left in an inconsistent state and so the error
2099 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2100 ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
2101 ** forces an automatic rollback of the changes. See the
2102 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2103 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2104 ** this is important.
2106 ** ^(There can only be a single busy handler defined for each
2107 ** [database connection]. Setting a new busy handler clears any
2108 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2109 ** will also set or clear the busy handler.
2111 ** The busy callback should not take any actions which modify the
2112 ** database connection that invoked the busy handler. Any such actions
2113 ** result in undefined behavior.
2115 ** A busy handler must not close the database connection
2116 ** or [prepared statement] that invoked the busy handler.
2118 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2121 ** CAPI3REF: Set A Busy Timeout
2123 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2124 ** for a specified amount of time when a table is locked. ^The handler
2125 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2126 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2127 ** the handler returns 0 which causes [sqlite3_step()] to return
2128 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2130 ** ^Calling this routine with an argument less than or equal to zero
2131 ** turns off all busy handlers.
2133 ** ^(There can only be a single busy handler for a particular
2134 ** [database connection] any any given moment. If another busy handler
2135 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2136 ** this routine, that other busy handler is cleared.)^
2138 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2141 ** CAPI3REF: Convenience Routines For Running Queries
2143 ** This is a legacy interface that is preserved for backwards compatibility.
2144 ** Use of this interface is not recommended.
2146 ** Definition: A <b>result table</b> is memory data structure created by the
2147 ** [sqlite3_get_table()] interface. A result table records the
2148 ** complete query results from one or more queries.
2150 ** The table conceptually has a number of rows and columns. But
2151 ** these numbers are not part of the result table itself. These
2152 ** numbers are obtained separately. Let N be the number of rows
2153 ** and M be the number of columns.
2155 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2156 ** There are (N+1)*M elements in the array. The first M pointers point
2157 ** to zero-terminated strings that contain the names of the columns.
2158 ** The remaining entries all point to query results. NULL values result
2159 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2160 ** string representation as returned by [sqlite3_column_text()].
2162 ** A result table might consist of one or more memory allocations.
2163 ** It is not safe to pass a result table directly to [sqlite3_free()].
2164 ** A result table should be deallocated using [sqlite3_free_table()].
2166 ** ^(As an example of the result table format, suppose a query result
2167 ** is as follows:
2169 ** <blockquote><pre>
2170 ** Name | Age
2171 ** -----------------------
2172 ** Alice | 43
2173 ** Bob | 28
2174 ** Cindy | 21
2175 ** </pre></blockquote>
2177 ** There are two column (M==2) and three rows (N==3). Thus the
2178 ** result table has 8 entries. Suppose the result table is stored
2179 ** in an array names azResult. Then azResult holds this content:
2181 ** <blockquote><pre>
2182 ** azResult&#91;0] = "Name";
2183 ** azResult&#91;1] = "Age";
2184 ** azResult&#91;2] = "Alice";
2185 ** azResult&#91;3] = "43";
2186 ** azResult&#91;4] = "Bob";
2187 ** azResult&#91;5] = "28";
2188 ** azResult&#91;6] = "Cindy";
2189 ** azResult&#91;7] = "21";
2190 ** </pre></blockquote>)^
2192 ** ^The sqlite3_get_table() function evaluates one or more
2193 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2194 ** string of its 2nd parameter and returns a result table to the
2195 ** pointer given in its 3rd parameter.
2197 ** After the application has finished with the result from sqlite3_get_table(),
2198 ** it must pass the result table pointer to sqlite3_free_table() in order to
2199 ** release the memory that was malloced. Because of the way the
2200 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2201 ** function must not try to call [sqlite3_free()] directly. Only
2202 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2204 ** The sqlite3_get_table() interface is implemented as a wrapper around
2205 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2206 ** to any internal data structures of SQLite. It uses only the public
2207 ** interface defined here. As a consequence, errors that occur in the
2208 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2209 ** reflected in subsequent calls to [sqlite3_errcode()] or
2210 ** [sqlite3_errmsg()].
2212 SQLITE_API int sqlite3_get_table(
2213 sqlite3 *db, /* An open database */
2214 const char *zSql, /* SQL to be evaluated */
2215 char ***pazResult, /* Results of the query */
2216 int *pnRow, /* Number of result rows written here */
2217 int *pnColumn, /* Number of result columns written here */
2218 char **pzErrmsg /* Error msg written here */
2220 SQLITE_API void sqlite3_free_table(char **result);
2223 ** CAPI3REF: Formatted String Printing Functions
2225 ** These routines are work-alikes of the "printf()" family of functions
2226 ** from the standard C library.
2228 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2229 ** results into memory obtained from [sqlite3_malloc()].
2230 ** The strings returned by these two routines should be
2231 ** released by [sqlite3_free()]. ^Both routines return a
2232 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2233 ** memory to hold the resulting string.
2235 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2236 ** the standard C library. The result is written into the
2237 ** buffer supplied as the second parameter whose size is given by
2238 ** the first parameter. Note that the order of the
2239 ** first two parameters is reversed from snprintf().)^ This is an
2240 ** historical accident that cannot be fixed without breaking
2241 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2242 ** returns a pointer to its buffer instead of the number of
2243 ** characters actually written into the buffer.)^ We admit that
2244 ** the number of characters written would be a more useful return
2245 ** value but we cannot change the implementation of sqlite3_snprintf()
2246 ** now without breaking compatibility.
2248 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2249 ** guarantees that the buffer is always zero-terminated. ^The first
2250 ** parameter "n" is the total size of the buffer, including space for
2251 ** the zero terminator. So the longest string that can be completely
2252 ** written will be n-1 characters.
2254 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2256 ** These routines all implement some additional formatting
2257 ** options that are useful for constructing SQL statements.
2258 ** All of the usual printf() formatting options apply. In addition, there
2259 ** is are "%q", "%Q", and "%z" options.
2261 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2262 ** string from the argument list. But %q also doubles every '\'' character.
2263 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2264 ** character it escapes that character and allows it to be inserted into
2265 ** the string.
2267 ** For example, assume the string variable zText contains text as follows:
2269 ** <blockquote><pre>
2270 ** char *zText = "It's a happy day!";
2271 ** </pre></blockquote>
2273 ** One can use this text in an SQL statement as follows:
2275 ** <blockquote><pre>
2276 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2277 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2278 ** sqlite3_free(zSQL);
2279 ** </pre></blockquote>
2281 ** Because the %q format string is used, the '\'' character in zText
2282 ** is escaped and the SQL generated is as follows:
2284 ** <blockquote><pre>
2285 ** INSERT INTO table1 VALUES('It''s a happy day!')
2286 ** </pre></blockquote>
2288 ** This is correct. Had we used %s instead of %q, the generated SQL
2289 ** would have looked like this:
2291 ** <blockquote><pre>
2292 ** INSERT INTO table1 VALUES('It's a happy day!');
2293 ** </pre></blockquote>
2295 ** This second example is an SQL syntax error. As a general rule you should
2296 ** always use %q instead of %s when inserting text into a string literal.
2298 ** ^(The %Q option works like %q except it also adds single quotes around
2299 ** the outside of the total string. Additionally, if the parameter in the
2300 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2301 ** single quotes).)^ So, for example, one could say:
2303 ** <blockquote><pre>
2304 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2305 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2306 ** sqlite3_free(zSQL);
2307 ** </pre></blockquote>
2309 ** The code above will render a correct SQL statement in the zSQL
2310 ** variable even if the zText variable is a NULL pointer.
2312 ** ^(The "%z" formatting option works like "%s" but with the
2313 ** addition that after the string has been read and copied into
2314 ** the result, [sqlite3_free()] is called on the input string.)^
2316 SQLITE_API char *sqlite3_mprintf(const char*,...);
2317 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2318 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2319 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2322 ** CAPI3REF: Memory Allocation Subsystem
2324 ** The SQLite core uses these three routines for all of its own
2325 ** internal memory allocation needs. "Core" in the previous sentence
2326 ** does not include operating-system specific VFS implementation. The
2327 ** Windows VFS uses native malloc() and free() for some operations.
2329 ** ^The sqlite3_malloc() routine returns a pointer to a block
2330 ** of memory at least N bytes in length, where N is the parameter.
2331 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2332 ** memory, it returns a NULL pointer. ^If the parameter N to
2333 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2334 ** a NULL pointer.
2336 ** ^Calling sqlite3_free() with a pointer previously returned
2337 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2338 ** that it might be reused. ^The sqlite3_free() routine is
2339 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2340 ** to sqlite3_free() is harmless. After being freed, memory
2341 ** should neither be read nor written. Even reading previously freed
2342 ** memory might result in a segmentation fault or other severe error.
2343 ** Memory corruption, a segmentation fault, or other severe error
2344 ** might result if sqlite3_free() is called with a non-NULL pointer that
2345 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2347 ** ^(The sqlite3_realloc() interface attempts to resize a
2348 ** prior memory allocation to be at least N bytes, where N is the
2349 ** second parameter. The memory allocation to be resized is the first
2350 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2351 ** is a NULL pointer then its behavior is identical to calling
2352 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2353 ** ^If the second parameter to sqlite3_realloc() is zero or
2354 ** negative then the behavior is exactly the same as calling
2355 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2356 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2357 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2358 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2359 ** of the prior allocation are copied into the beginning of buffer returned
2360 ** by sqlite3_realloc() and the prior allocation is freed.
2361 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2362 ** is not freed.
2364 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2365 ** is always aligned to at least an 8 byte boundary, or to a
2366 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2367 ** option is used.
2369 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2370 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2371 ** implementation of these routines to be omitted. That capability
2372 ** is no longer provided. Only built-in memory allocators can be used.
2374 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2375 ** the system malloc() and free() directly when converting
2376 ** filenames between the UTF-8 encoding used by SQLite
2377 ** and whatever filename encoding is used by the particular Windows
2378 ** installation. Memory allocation errors were detected, but
2379 ** they were reported back as [SQLITE_CANTOPEN] or
2380 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2382 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2383 ** must be either NULL or else pointers obtained from a prior
2384 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2385 ** not yet been released.
2387 ** The application must not read or write any part of
2388 ** a block of memory after it has been released using
2389 ** [sqlite3_free()] or [sqlite3_realloc()].
2391 SQLITE_API void *sqlite3_malloc(int);
2392 SQLITE_API void *sqlite3_realloc(void*, int);
2393 SQLITE_API void sqlite3_free(void*);
2396 ** CAPI3REF: Memory Allocator Statistics
2398 ** SQLite provides these two interfaces for reporting on the status
2399 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2400 ** routines, which form the built-in memory allocation subsystem.
2402 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2403 ** of memory currently outstanding (malloced but not freed).
2404 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2405 ** value of [sqlite3_memory_used()] since the high-water mark
2406 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2407 ** [sqlite3_memory_highwater()] include any overhead
2408 ** added by SQLite in its implementation of [sqlite3_malloc()],
2409 ** but not overhead added by the any underlying system library
2410 ** routines that [sqlite3_malloc()] may call.
2412 ** ^The memory high-water mark is reset to the current value of
2413 ** [sqlite3_memory_used()] if and only if the parameter to
2414 ** [sqlite3_memory_highwater()] is true. ^The value returned
2415 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2416 ** prior to the reset.
2418 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2419 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2422 ** CAPI3REF: Pseudo-Random Number Generator
2424 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2425 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2426 ** already uses the largest possible [ROWID]. The PRNG is also used for
2427 ** the build-in random() and randomblob() SQL functions. This interface allows
2428 ** applications to access the same PRNG for other purposes.
2430 ** ^A call to this routine stores N bytes of randomness into buffer P.
2431 ** ^If N is less than one, then P can be a NULL pointer.
2433 ** ^If this routine has not been previously called or if the previous
2434 ** call had N less than one, then the PRNG is seeded using randomness
2435 ** obtained from the xRandomness method of the default [sqlite3_vfs] object.
2436 ** ^If the previous call to this routine had an N of 1 or more then
2437 ** the pseudo-randomness is generated
2438 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2439 ** method.
2441 SQLITE_API void sqlite3_randomness(int N, void *P);
2444 ** CAPI3REF: Compile-Time Authorization Callbacks
2446 ** ^This routine registers an authorizer callback with a particular
2447 ** [database connection], supplied in the first argument.
2448 ** ^The authorizer callback is invoked as SQL statements are being compiled
2449 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2450 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2451 ** points during the compilation process, as logic is being created
2452 ** to perform various actions, the authorizer callback is invoked to
2453 ** see if those actions are allowed. ^The authorizer callback should
2454 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2455 ** specific action but allow the SQL statement to continue to be
2456 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2457 ** rejected with an error. ^If the authorizer callback returns
2458 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2459 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2460 ** the authorizer will fail with an error message.
2462 ** When the callback returns [SQLITE_OK], that means the operation
2463 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2464 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2465 ** authorizer will fail with an error message explaining that
2466 ** access is denied.
2468 ** ^The first parameter to the authorizer callback is a copy of the third
2469 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2470 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2471 ** the particular action to be authorized. ^The third through sixth parameters
2472 ** to the callback are zero-terminated strings that contain additional
2473 ** details about the action to be authorized.
2475 ** ^If the action code is [SQLITE_READ]
2476 ** and the callback returns [SQLITE_IGNORE] then the
2477 ** [prepared statement] statement is constructed to substitute
2478 ** a NULL value in place of the table column that would have
2479 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2480 ** return can be used to deny an untrusted user access to individual
2481 ** columns of a table.
2482 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2483 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2484 ** [truncate optimization] is disabled and all rows are deleted individually.
2486 ** An authorizer is used when [sqlite3_prepare | preparing]
2487 ** SQL statements from an untrusted source, to ensure that the SQL statements
2488 ** do not try to access data they are not allowed to see, or that they do not
2489 ** try to execute malicious statements that damage the database. For
2490 ** example, an application may allow a user to enter arbitrary
2491 ** SQL queries for evaluation by a database. But the application does
2492 ** not want the user to be able to make arbitrary changes to the
2493 ** database. An authorizer could then be put in place while the
2494 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2495 ** disallows everything except [SELECT] statements.
2497 ** Applications that need to process SQL from untrusted sources
2498 ** might also consider lowering resource limits using [sqlite3_limit()]
2499 ** and limiting database size using the [max_page_count] [PRAGMA]
2500 ** in addition to using an authorizer.
2502 ** ^(Only a single authorizer can be in place on a database connection
2503 ** at a time. Each call to sqlite3_set_authorizer overrides the
2504 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2505 ** The authorizer is disabled by default.
2507 ** The authorizer callback must not do anything that will modify
2508 ** the database connection that invoked the authorizer callback.
2509 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2510 ** database connections for the meaning of "modify" in this paragraph.
2512 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2513 ** statement might be re-prepared during [sqlite3_step()] due to a
2514 ** schema change. Hence, the application should ensure that the
2515 ** correct authorizer callback remains in place during the [sqlite3_step()].
2517 ** ^Note that the authorizer callback is invoked only during
2518 ** [sqlite3_prepare()] or its variants. Authorization is not
2519 ** performed during statement evaluation in [sqlite3_step()], unless
2520 ** as stated in the previous paragraph, sqlite3_step() invokes
2521 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2523 SQLITE_API int sqlite3_set_authorizer(
2524 sqlite3*,
2525 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2526 void *pUserData
2530 ** CAPI3REF: Authorizer Return Codes
2532 ** The [sqlite3_set_authorizer | authorizer callback function] must
2533 ** return either [SQLITE_OK] or one of these two constants in order
2534 ** to signal SQLite whether or not the action is permitted. See the
2535 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2536 ** information.
2538 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2539 ** from the [sqlite3_vtab_on_conflict()] interface.
2541 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2542 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2545 ** CAPI3REF: Authorizer Action Codes
2547 ** The [sqlite3_set_authorizer()] interface registers a callback function
2548 ** that is invoked to authorize certain SQL statement actions. The
2549 ** second parameter to the callback is an integer code that specifies
2550 ** what action is being authorized. These are the integer action codes that
2551 ** the authorizer callback may be passed.
2553 ** These action code values signify what kind of operation is to be
2554 ** authorized. The 3rd and 4th parameters to the authorization
2555 ** callback function will be parameters or NULL depending on which of these
2556 ** codes is used as the second parameter. ^(The 5th parameter to the
2557 ** authorizer callback is the name of the database ("main", "temp",
2558 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2559 ** is the name of the inner-most trigger or view that is responsible for
2560 ** the access attempt or NULL if this access attempt is directly from
2561 ** top-level SQL code.
2563 /******************************************* 3rd ************ 4th ***********/
2564 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2565 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
2566 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
2567 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
2568 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
2569 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
2570 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
2571 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
2572 #define SQLITE_DELETE 9 /* Table Name NULL */
2573 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
2574 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
2575 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
2576 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
2577 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
2578 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
2579 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
2580 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
2581 #define SQLITE_INSERT 18 /* Table Name NULL */
2582 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
2583 #define SQLITE_READ 20 /* Table Name Column Name */
2584 #define SQLITE_SELECT 21 /* NULL NULL */
2585 #define SQLITE_TRANSACTION 22 /* Operation NULL */
2586 #define SQLITE_UPDATE 23 /* Table Name Column Name */
2587 #define SQLITE_ATTACH 24 /* Filename NULL */
2588 #define SQLITE_DETACH 25 /* Database Name NULL */
2589 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
2590 #define SQLITE_REINDEX 27 /* Index Name NULL */
2591 #define SQLITE_ANALYZE 28 /* Table Name NULL */
2592 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
2593 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
2594 #define SQLITE_FUNCTION 31 /* NULL Function Name */
2595 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
2596 #define SQLITE_COPY 0 /* No longer used */
2597 #define SQLITE_RECURSIVE 33 /* NULL NULL */
2600 ** CAPI3REF: Tracing And Profiling Functions
2602 ** These routines register callback functions that can be used for
2603 ** tracing and profiling the execution of SQL statements.
2605 ** ^The callback function registered by sqlite3_trace() is invoked at
2606 ** various times when an SQL statement is being run by [sqlite3_step()].
2607 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2608 ** SQL statement text as the statement first begins executing.
2609 ** ^(Additional sqlite3_trace() callbacks might occur
2610 ** as each triggered subprogram is entered. The callbacks for triggers
2611 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2613 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2614 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
2616 ** ^The callback function registered by sqlite3_profile() is invoked
2617 ** as each SQL statement finishes. ^The profile callback contains
2618 ** the original statement text and an estimate of wall-clock time
2619 ** of how long that statement took to run. ^The profile callback
2620 ** time is in units of nanoseconds, however the current implementation
2621 ** is only capable of millisecond resolution so the six least significant
2622 ** digits in the time are meaningless. Future versions of SQLite
2623 ** might provide greater resolution on the profiler callback. The
2624 ** sqlite3_profile() function is considered experimental and is
2625 ** subject to change in future versions of SQLite.
2627 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2628 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2629 void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2632 ** CAPI3REF: Query Progress Callbacks
2634 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2635 ** function X to be invoked periodically during long running calls to
2636 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2637 ** database connection D. An example use for this
2638 ** interface is to keep a GUI updated during a large query.
2640 ** ^The parameter P is passed through as the only parameter to the
2641 ** callback function X. ^The parameter N is the approximate number of
2642 ** [virtual machine instructions] that are evaluated between successive
2643 ** invocations of the callback X. ^If N is less than one then the progress
2644 ** handler is disabled.
2646 ** ^Only a single progress handler may be defined at one time per
2647 ** [database connection]; setting a new progress handler cancels the
2648 ** old one. ^Setting parameter X to NULL disables the progress handler.
2649 ** ^The progress handler is also disabled by setting N to a value less
2650 ** than 1.
2652 ** ^If the progress callback returns non-zero, the operation is
2653 ** interrupted. This feature can be used to implement a
2654 ** "Cancel" button on a GUI progress dialog box.
2656 ** The progress handler callback must not do anything that will modify
2657 ** the database connection that invoked the progress handler.
2658 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2659 ** database connections for the meaning of "modify" in this paragraph.
2662 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2665 ** CAPI3REF: Opening A New Database Connection
2667 ** ^These routines open an SQLite database file as specified by the
2668 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2669 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2670 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2671 ** returned in *ppDb, even if an error occurs. The only exception is that
2672 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2673 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2674 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2675 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
2676 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2677 ** an English language description of the error following a failure of any
2678 ** of the sqlite3_open() routines.
2680 ** ^The default encoding for the database will be UTF-8 if
2681 ** sqlite3_open() or sqlite3_open_v2() is called and
2682 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2684 ** Whether or not an error occurs when it is opened, resources
2685 ** associated with the [database connection] handle should be released by
2686 ** passing it to [sqlite3_close()] when it is no longer required.
2688 ** The sqlite3_open_v2() interface works like sqlite3_open()
2689 ** except that it accepts two additional parameters for additional control
2690 ** over the new database connection. ^(The flags parameter to
2691 ** sqlite3_open_v2() can take one of
2692 ** the following three values, optionally combined with the
2693 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2694 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2696 ** <dl>
2697 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2698 ** <dd>The database is opened in read-only mode. If the database does not
2699 ** already exist, an error is returned.</dd>)^
2701 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2702 ** <dd>The database is opened for reading and writing if possible, or reading
2703 ** only if the file is write protected by the operating system. In either
2704 ** case the database must already exist, otherwise an error is returned.</dd>)^
2706 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2707 ** <dd>The database is opened for reading and writing, and is created if
2708 ** it does not already exist. This is the behavior that is always used for
2709 ** sqlite3_open() and sqlite3_open16().</dd>)^
2710 ** </dl>
2712 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2713 ** combinations shown above optionally combined with other
2714 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2715 ** then the behavior is undefined.
2717 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2718 ** opens in the multi-thread [threading mode] as long as the single-thread
2719 ** mode has not been set at compile-time or start-time. ^If the
2720 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2721 ** in the serialized [threading mode] unless single-thread was
2722 ** previously selected at compile-time or start-time.
2723 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2724 ** eligible to use [shared cache mode], regardless of whether or not shared
2725 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
2726 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2727 ** participate in [shared cache mode] even if it is enabled.
2729 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2730 ** [sqlite3_vfs] object that defines the operating system interface that
2731 ** the new database connection should use. ^If the fourth parameter is
2732 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2734 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2735 ** is created for the connection. ^This in-memory database will vanish when
2736 ** the database connection is closed. Future versions of SQLite might
2737 ** make use of additional special filenames that begin with the ":" character.
2738 ** It is recommended that when a database filename actually does begin with
2739 ** a ":" character you should prefix the filename with a pathname such as
2740 ** "./" to avoid ambiguity.
2742 ** ^If the filename is an empty string, then a private, temporary
2743 ** on-disk database will be created. ^This private database will be
2744 ** automatically deleted as soon as the database connection is closed.
2746 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
2748 ** ^If [URI filename] interpretation is enabled, and the filename argument
2749 ** begins with "file:", then the filename is interpreted as a URI. ^URI
2750 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
2751 ** set in the fourth argument to sqlite3_open_v2(), or if it has
2752 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
2753 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
2754 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
2755 ** by default, but future releases of SQLite might enable URI filename
2756 ** interpretation by default. See "[URI filenames]" for additional
2757 ** information.
2759 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
2760 ** authority, then it must be either an empty string or the string
2761 ** "localhost". ^If the authority is not an empty string or "localhost", an
2762 ** error is returned to the caller. ^The fragment component of a URI, if
2763 ** present, is ignored.
2765 ** ^SQLite uses the path component of the URI as the name of the disk file
2766 ** which contains the database. ^If the path begins with a '/' character,
2767 ** then it is interpreted as an absolute path. ^If the path does not begin
2768 ** with a '/' (meaning that the authority section is omitted from the URI)
2769 ** then the path is interpreted as a relative path.
2770 ** ^On windows, the first component of an absolute path
2771 ** is a drive specification (e.g. "C:").
2773 ** [[core URI query parameters]]
2774 ** The query component of a URI may contain parameters that are interpreted
2775 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
2776 ** SQLite interprets the following three query parameters:
2778 ** <ul>
2779 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
2780 ** a VFS object that provides the operating system interface that should
2781 ** be used to access the database file on disk. ^If this option is set to
2782 ** an empty string the default VFS object is used. ^Specifying an unknown
2783 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
2784 ** present, then the VFS specified by the option takes precedence over
2785 ** the value passed as the fourth parameter to sqlite3_open_v2().
2787 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
2788 ** "rwc", or "memory". Attempting to set it to any other value is
2789 ** an error)^.
2790 ** ^If "ro" is specified, then the database is opened for read-only
2791 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
2792 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
2793 ** "rw", then the database is opened for read-write (but not create)
2794 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
2795 ** been set. ^Value "rwc" is equivalent to setting both
2796 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
2797 ** set to "memory" then a pure [in-memory database] that never reads
2798 ** or writes from disk is used. ^It is an error to specify a value for
2799 ** the mode parameter that is less restrictive than that specified by
2800 ** the flags passed in the third parameter to sqlite3_open_v2().
2802 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
2803 ** "private". ^Setting it to "shared" is equivalent to setting the
2804 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
2805 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
2806 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
2807 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
2808 ** a URI filename, its value overrides any behavior requested by setting
2809 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
2810 ** </ul>
2812 ** ^Specifying an unknown parameter in the query component of a URI is not an
2813 ** error. Future versions of SQLite might understand additional query
2814 ** parameters. See "[query parameters with special meaning to SQLite]" for
2815 ** additional information.
2817 ** [[URI filename examples]] <h3>URI filename examples</h3>
2819 ** <table border="1" align=center cellpadding=5>
2820 ** <tr><th> URI filenames <th> Results
2821 ** <tr><td> file:data.db <td>
2822 ** Open the file "data.db" in the current directory.
2823 ** <tr><td> file:/home/fred/data.db<br>
2824 ** file:///home/fred/data.db <br>
2825 ** file://localhost/home/fred/data.db <br> <td>
2826 ** Open the database file "/home/fred/data.db".
2827 ** <tr><td> file://darkstar/home/fred/data.db <td>
2828 ** An error. "darkstar" is not a recognized authority.
2829 ** <tr><td style="white-space:nowrap">
2830 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
2831 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
2832 ** C:. Note that the %20 escaping in this example is not strictly
2833 ** necessary - space characters can be used literally
2834 ** in URI filenames.
2835 ** <tr><td> file:data.db?mode=ro&cache=private <td>
2836 ** Open file "data.db" in the current directory for read-only access.
2837 ** Regardless of whether or not shared-cache mode is enabled by
2838 ** default, use a private cache.
2839 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
2840 ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
2841 ** <tr><td> file:data.db?mode=readonly <td>
2842 ** An error. "readonly" is not a valid option for the "mode" parameter.
2843 ** </table>
2845 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
2846 ** query components of a URI. A hexadecimal escape sequence consists of a
2847 ** percent sign - "%" - followed by exactly two hexadecimal digits
2848 ** specifying an octet value. ^Before the path or query components of a
2849 ** URI filename are interpreted, they are encoded using UTF-8 and all
2850 ** hexadecimal escape sequences replaced by a single byte containing the
2851 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
2852 ** the results are undefined.
2854 ** <b>Note to Windows users:</b> The encoding used for the filename argument
2855 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2856 ** codepage is currently defined. Filenames containing international
2857 ** characters must be converted to UTF-8 prior to passing them into
2858 ** sqlite3_open() or sqlite3_open_v2().
2860 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
2861 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
2862 ** features that require the use of temporary files may fail.
2864 ** See also: [sqlite3_temp_directory]
2866 SQLITE_API int sqlite3_open(
2867 const char *filename, /* Database filename (UTF-8) */
2868 sqlite3 **ppDb /* OUT: SQLite db handle */
2870 SQLITE_API int sqlite3_open16(
2871 const void *filename, /* Database filename (UTF-16) */
2872 sqlite3 **ppDb /* OUT: SQLite db handle */
2874 SQLITE_API int sqlite3_open_v2(
2875 const char *filename, /* Database filename (UTF-8) */
2876 sqlite3 **ppDb, /* OUT: SQLite db handle */
2877 int flags, /* Flags */
2878 const char *zVfs /* Name of VFS module to use */
2882 ** CAPI3REF: Obtain Values For URI Parameters
2884 ** These are utility routines, useful to VFS implementations, that check
2885 ** to see if a database file was a URI that contained a specific query
2886 ** parameter, and if so obtains the value of that query parameter.
2888 ** If F is the database filename pointer passed into the xOpen() method of
2889 ** a VFS implementation when the flags parameter to xOpen() has one or
2890 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
2891 ** P is the name of the query parameter, then
2892 ** sqlite3_uri_parameter(F,P) returns the value of the P
2893 ** parameter if it exists or a NULL pointer if P does not appear as a
2894 ** query parameter on F. If P is a query parameter of F
2895 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
2896 ** a pointer to an empty string.
2898 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
2899 ** parameter and returns true (1) or false (0) according to the value
2900 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
2901 ** value of query parameter P is one of "yes", "true", or "on" in any
2902 ** case or if the value begins with a non-zero number. The
2903 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
2904 ** query parameter P is one of "no", "false", or "off" in any case or
2905 ** if the value begins with a numeric zero. If P is not a query
2906 ** parameter on F or if the value of P is does not match any of the
2907 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
2909 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
2910 ** 64-bit signed integer and returns that integer, or D if P does not
2911 ** exist. If the value of P is something other than an integer, then
2912 ** zero is returned.
2914 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
2915 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
2916 ** is not a database file pathname pointer that SQLite passed into the xOpen
2917 ** VFS method, then the behavior of this routine is undefined and probably
2918 ** undesirable.
2920 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
2921 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
2922 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
2926 ** CAPI3REF: Error Codes And Messages
2928 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2929 ** [extended result code] for the most recent failed sqlite3_* API call
2930 ** associated with a [database connection]. If a prior API call failed
2931 ** but the most recent API call succeeded, the return value from
2932 ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
2933 ** interface is the same except that it always returns the
2934 ** [extended result code] even when extended result codes are
2935 ** disabled.
2937 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2938 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2939 ** ^(Memory to hold the error message string is managed internally.
2940 ** The application does not need to worry about freeing the result.
2941 ** However, the error string might be overwritten or deallocated by
2942 ** subsequent calls to other SQLite interface functions.)^
2944 ** ^The sqlite3_errstr() interface returns the English-language text
2945 ** that describes the [result code], as UTF-8.
2946 ** ^(Memory to hold the error message string is managed internally
2947 ** and must not be freed by the application)^.
2949 ** When the serialized [threading mode] is in use, it might be the
2950 ** case that a second error occurs on a separate thread in between
2951 ** the time of the first error and the call to these interfaces.
2952 ** When that happens, the second error will be reported since these
2953 ** interfaces always report the most recent result. To avoid
2954 ** this, each thread can obtain exclusive use of the [database connection] D
2955 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2956 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2957 ** all calls to the interfaces listed here are completed.
2959 ** If an interface fails with SQLITE_MISUSE, that means the interface
2960 ** was invoked incorrectly by the application. In that case, the
2961 ** error code and message may or may not be set.
2963 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2964 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2965 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2966 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2967 SQLITE_API const char *sqlite3_errstr(int);
2970 ** CAPI3REF: SQL Statement Object
2971 ** KEYWORDS: {prepared statement} {prepared statements}
2973 ** An instance of this object represents a single SQL statement.
2974 ** This object is variously known as a "prepared statement" or a
2975 ** "compiled SQL statement" or simply as a "statement".
2977 ** The life of a statement object goes something like this:
2979 ** <ol>
2980 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2981 ** function.
2982 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2983 ** interfaces.
2984 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2985 ** <li> Reset the statement using [sqlite3_reset()] then go back
2986 ** to step 2. Do this zero or more times.
2987 ** <li> Destroy the object using [sqlite3_finalize()].
2988 ** </ol>
2990 ** Refer to documentation on individual methods above for additional
2991 ** information.
2993 typedef struct sqlite3_stmt sqlite3_stmt;
2996 ** CAPI3REF: Run-time Limits
2998 ** ^(This interface allows the size of various constructs to be limited
2999 ** on a connection by connection basis. The first parameter is the
3000 ** [database connection] whose limit is to be set or queried. The
3001 ** second parameter is one of the [limit categories] that define a
3002 ** class of constructs to be size limited. The third parameter is the
3003 ** new limit for that construct.)^
3005 ** ^If the new limit is a negative number, the limit is unchanged.
3006 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3007 ** [limits | hard upper bound]
3008 ** set at compile-time by a C preprocessor macro called
3009 ** [limits | SQLITE_MAX_<i>NAME</i>].
3010 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3011 ** ^Attempts to increase a limit above its hard upper bound are
3012 ** silently truncated to the hard upper bound.
3014 ** ^Regardless of whether or not the limit was changed, the
3015 ** [sqlite3_limit()] interface returns the prior value of the limit.
3016 ** ^Hence, to find the current value of a limit without changing it,
3017 ** simply invoke this interface with the third parameter set to -1.
3019 ** Run-time limits are intended for use in applications that manage
3020 ** both their own internal database and also databases that are controlled
3021 ** by untrusted external sources. An example application might be a
3022 ** web browser that has its own databases for storing history and
3023 ** separate databases controlled by JavaScript applications downloaded
3024 ** off the Internet. The internal databases can be given the
3025 ** large, default limits. Databases managed by external sources can
3026 ** be given much smaller limits designed to prevent a denial of service
3027 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3028 ** interface to further control untrusted SQL. The size of the database
3029 ** created by an untrusted script can be contained using the
3030 ** [max_page_count] [PRAGMA].
3032 ** New run-time limit categories may be added in future releases.
3034 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3037 ** CAPI3REF: Run-Time Limit Categories
3038 ** KEYWORDS: {limit category} {*limit categories}
3040 ** These constants define various performance limits
3041 ** that can be lowered at run-time using [sqlite3_limit()].
3042 ** The synopsis of the meanings of the various limits is shown below.
3043 ** Additional information is available at [limits | Limits in SQLite].
3045 ** <dl>
3046 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3047 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3049 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3050 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3052 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3053 ** <dd>The maximum number of columns in a table definition or in the
3054 ** result set of a [SELECT] or the maximum number of columns in an index
3055 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3057 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3058 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3060 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3061 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3063 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3064 ** <dd>The maximum number of instructions in a virtual machine program
3065 ** used to implement an SQL statement. This limit is not currently
3066 ** enforced, though that might be added in some future release of
3067 ** SQLite.</dd>)^
3069 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3070 ** <dd>The maximum number of arguments on a function.</dd>)^
3072 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3073 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3075 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3076 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3077 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3078 ** [GLOB] operators.</dd>)^
3080 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3081 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3082 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3084 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3085 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3086 ** </dl>
3088 #define SQLITE_LIMIT_LENGTH 0
3089 #define SQLITE_LIMIT_SQL_LENGTH 1
3090 #define SQLITE_LIMIT_COLUMN 2
3091 #define SQLITE_LIMIT_EXPR_DEPTH 3
3092 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3093 #define SQLITE_LIMIT_VDBE_OP 5
3094 #define SQLITE_LIMIT_FUNCTION_ARG 6
3095 #define SQLITE_LIMIT_ATTACHED 7
3096 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3097 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3098 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3101 ** CAPI3REF: Compiling An SQL Statement
3102 ** KEYWORDS: {SQL statement compiler}
3104 ** To execute an SQL query, it must first be compiled into a byte-code
3105 ** program using one of these routines.
3107 ** The first argument, "db", is a [database connection] obtained from a
3108 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3109 ** [sqlite3_open16()]. The database connection must not have been closed.
3111 ** The second argument, "zSql", is the statement to be compiled, encoded
3112 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3113 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3114 ** use UTF-16.
3116 ** ^If the nByte argument is less than zero, then zSql is read up to the
3117 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3118 ** number of bytes read from zSql. ^When nByte is non-negative, the
3119 ** zSql string ends at either the first '\000' or '\u0000' character or
3120 ** the nByte-th byte, whichever comes first. If the caller knows
3121 ** that the supplied string is nul-terminated, then there is a small
3122 ** performance advantage to be gained by passing an nByte parameter that
3123 ** is equal to the number of bytes in the input string <i>including</i>
3124 ** the nul-terminator bytes as this saves SQLite from having to
3125 ** make a copy of the input string.
3127 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3128 ** past the end of the first SQL statement in zSql. These routines only
3129 ** compile the first statement in zSql, so *pzTail is left pointing to
3130 ** what remains uncompiled.
3132 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3133 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3134 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3135 ** string or a comment) then *ppStmt is set to NULL.
3136 ** The calling procedure is responsible for deleting the compiled
3137 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3138 ** ppStmt may not be NULL.
3140 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3141 ** otherwise an [error code] is returned.
3143 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3144 ** recommended for all new programs. The two older interfaces are retained
3145 ** for backwards compatibility, but their use is discouraged.
3146 ** ^In the "v2" interfaces, the prepared statement
3147 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3148 ** original SQL text. This causes the [sqlite3_step()] interface to
3149 ** behave differently in three ways:
3151 ** <ol>
3152 ** <li>
3153 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3154 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3155 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3156 ** retries will occur before sqlite3_step() gives up and returns an error.
3157 ** </li>
3159 ** <li>
3160 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3161 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3162 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3163 ** and the application would have to make a second call to [sqlite3_reset()]
3164 ** in order to find the underlying cause of the problem. With the "v2" prepare
3165 ** interfaces, the underlying reason for the error is returned immediately.
3166 ** </li>
3168 ** <li>
3169 ** ^If the specific value bound to [parameter | host parameter] in the
3170 ** WHERE clause might influence the choice of query plan for a statement,
3171 ** then the statement will be automatically recompiled, as if there had been
3172 ** a schema change, on the first [sqlite3_step()] call following any change
3173 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3174 ** ^The specific value of WHERE-clause [parameter] might influence the
3175 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3176 ** or [GLOB] operator or if the parameter is compared to an indexed column
3177 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3178 ** </li>
3179 ** </ol>
3181 SQLITE_API int sqlite3_prepare(
3182 sqlite3 *db, /* Database handle */
3183 const char *zSql, /* SQL statement, UTF-8 encoded */
3184 int nByte, /* Maximum length of zSql in bytes. */
3185 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3186 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3188 SQLITE_API int sqlite3_prepare_v2(
3189 sqlite3 *db, /* Database handle */
3190 const char *zSql, /* SQL statement, UTF-8 encoded */
3191 int nByte, /* Maximum length of zSql in bytes. */
3192 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3193 const char **pzTail /* OUT: Pointer to unused portion of zSql */
3195 SQLITE_API int sqlite3_prepare16(
3196 sqlite3 *db, /* Database handle */
3197 const void *zSql, /* SQL statement, UTF-16 encoded */
3198 int nByte, /* Maximum length of zSql in bytes. */
3199 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3200 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3202 SQLITE_API int sqlite3_prepare16_v2(
3203 sqlite3 *db, /* Database handle */
3204 const void *zSql, /* SQL statement, UTF-16 encoded */
3205 int nByte, /* Maximum length of zSql in bytes. */
3206 sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3207 const void **pzTail /* OUT: Pointer to unused portion of zSql */
3211 ** CAPI3REF: Retrieving Statement SQL
3213 ** ^This interface can be used to retrieve a saved copy of the original
3214 ** SQL text used to create a [prepared statement] if that statement was
3215 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3217 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3220 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3222 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3223 ** and only if the [prepared statement] X makes no direct changes to
3224 ** the content of the database file.
3226 ** Note that [application-defined SQL functions] or
3227 ** [virtual tables] might change the database indirectly as a side effect.
3228 ** ^(For example, if an application defines a function "eval()" that
3229 ** calls [sqlite3_exec()], then the following SQL statement would
3230 ** change the database file through side-effects:
3232 ** <blockquote><pre>
3233 ** SELECT eval('DELETE FROM t1') FROM t2;
3234 ** </pre></blockquote>
3236 ** But because the [SELECT] statement does not change the database file
3237 ** directly, sqlite3_stmt_readonly() would still return true.)^
3239 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3240 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3241 ** since the statements themselves do not actually modify the database but
3242 ** rather they control the timing of when other statements modify the
3243 ** database. ^The [ATTACH] and [DETACH] statements also cause
3244 ** sqlite3_stmt_readonly() to return true since, while those statements
3245 ** change the configuration of a database connection, they do not make
3246 ** changes to the content of the database files on disk.
3248 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3251 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3253 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3254 ** [prepared statement] S has been stepped at least once using
3255 ** [sqlite3_step(S)] but has not run to completion and/or has not
3256 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3257 ** interface returns false if S is a NULL pointer. If S is not a
3258 ** NULL pointer and is not a pointer to a valid [prepared statement]
3259 ** object, then the behavior is undefined and probably undesirable.
3261 ** This interface can be used in combination [sqlite3_next_stmt()]
3262 ** to locate all prepared statements associated with a database
3263 ** connection that are in need of being reset. This can be used,
3264 ** for example, in diagnostic routines to search for prepared
3265 ** statements that are holding a transaction open.
3267 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3270 ** CAPI3REF: Dynamically Typed Value Object
3271 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3273 ** SQLite uses the sqlite3_value object to represent all values
3274 ** that can be stored in a database table. SQLite uses dynamic typing
3275 ** for the values it stores. ^Values stored in sqlite3_value objects
3276 ** can be integers, floating point values, strings, BLOBs, or NULL.
3278 ** An sqlite3_value object may be either "protected" or "unprotected".
3279 ** Some interfaces require a protected sqlite3_value. Other interfaces
3280 ** will accept either a protected or an unprotected sqlite3_value.
3281 ** Every interface that accepts sqlite3_value arguments specifies
3282 ** whether or not it requires a protected sqlite3_value.
3284 ** The terms "protected" and "unprotected" refer to whether or not
3285 ** a mutex is held. An internal mutex is held for a protected
3286 ** sqlite3_value object but no mutex is held for an unprotected
3287 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3288 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3289 ** or if SQLite is run in one of reduced mutex modes
3290 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3291 ** then there is no distinction between protected and unprotected
3292 ** sqlite3_value objects and they can be used interchangeably. However,
3293 ** for maximum code portability it is recommended that applications
3294 ** still make the distinction between protected and unprotected
3295 ** sqlite3_value objects even when not strictly required.
3297 ** ^The sqlite3_value objects that are passed as parameters into the
3298 ** implementation of [application-defined SQL functions] are protected.
3299 ** ^The sqlite3_value object returned by
3300 ** [sqlite3_column_value()] is unprotected.
3301 ** Unprotected sqlite3_value objects may only be used with
3302 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3303 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3304 ** interfaces require protected sqlite3_value objects.
3306 typedef struct Mem sqlite3_value;
3309 ** CAPI3REF: SQL Function Context Object
3311 ** The context in which an SQL function executes is stored in an
3312 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3313 ** is always first parameter to [application-defined SQL functions].
3314 ** The application-defined SQL function implementation will pass this
3315 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3316 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3317 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3318 ** and/or [sqlite3_set_auxdata()].
3320 typedef struct sqlite3_context sqlite3_context;
3323 ** CAPI3REF: Binding Values To Prepared Statements
3324 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3325 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3327 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3328 ** literals may be replaced by a [parameter] that matches one of following
3329 ** templates:
3331 ** <ul>
3332 ** <li> ?
3333 ** <li> ?NNN
3334 ** <li> :VVV
3335 ** <li> @VVV
3336 ** <li> $VVV
3337 ** </ul>
3339 ** In the templates above, NNN represents an integer literal,
3340 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3341 ** parameters (also called "host parameter names" or "SQL parameters")
3342 ** can be set using the sqlite3_bind_*() routines defined here.
3344 ** ^The first argument to the sqlite3_bind_*() routines is always
3345 ** a pointer to the [sqlite3_stmt] object returned from
3346 ** [sqlite3_prepare_v2()] or its variants.
3348 ** ^The second argument is the index of the SQL parameter to be set.
3349 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3350 ** SQL parameter is used more than once, second and subsequent
3351 ** occurrences have the same index as the first occurrence.
3352 ** ^The index for named parameters can be looked up using the
3353 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3354 ** for "?NNN" parameters is the value of NNN.
3355 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3356 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3358 ** ^The third argument is the value to bind to the parameter.
3359 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3360 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3361 ** is ignored and the end result is the same as sqlite3_bind_null().
3363 ** ^(In those routines that have a fourth argument, its value is the
3364 ** number of bytes in the parameter. To be clear: the value is the
3365 ** number of <u>bytes</u> in the value, not the number of characters.)^
3366 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3367 ** is negative, then the length of the string is
3368 ** the number of bytes up to the first zero terminator.
3369 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3370 ** the behavior is undefined.
3371 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3372 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3373 ** where the NUL terminator would occur assuming the string were NUL
3374 ** terminated. If any NUL characters occur at byte offsets less than
3375 ** the value of the fourth parameter then the resulting string value will
3376 ** contain embedded NULs. The result of expressions involving strings
3377 ** with embedded NULs is undefined.
3379 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3380 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3381 ** string after SQLite has finished with it. ^The destructor is called
3382 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3383 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3384 ** ^If the fifth argument is
3385 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3386 ** information is in static, unmanaged space and does not need to be freed.
3387 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3388 ** SQLite makes its own private copy of the data immediately, before
3389 ** the sqlite3_bind_*() routine returns.
3391 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3392 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3393 ** (just an integer to hold its size) while it is being processed.
3394 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3395 ** content is later written using
3396 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3397 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3399 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3400 ** for the [prepared statement] or with a prepared statement for which
3401 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3402 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3403 ** routine is passed a [prepared statement] that has been finalized, the
3404 ** result is undefined and probably harmful.
3406 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3407 ** ^Unbound parameters are interpreted as NULL.
3409 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3410 ** [error code] if anything goes wrong.
3411 ** ^[SQLITE_RANGE] is returned if the parameter
3412 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3414 ** See also: [sqlite3_bind_parameter_count()],
3415 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3417 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3418 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3419 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3420 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3421 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3422 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3423 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3424 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3425 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3428 ** CAPI3REF: Number Of SQL Parameters
3430 ** ^This routine can be used to find the number of [SQL parameters]
3431 ** in a [prepared statement]. SQL parameters are tokens of the
3432 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3433 ** placeholders for values that are [sqlite3_bind_blob | bound]
3434 ** to the parameters at a later time.
3436 ** ^(This routine actually returns the index of the largest (rightmost)
3437 ** parameter. For all forms except ?NNN, this will correspond to the
3438 ** number of unique parameters. If parameters of the ?NNN form are used,
3439 ** there may be gaps in the list.)^
3441 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3442 ** [sqlite3_bind_parameter_name()], and
3443 ** [sqlite3_bind_parameter_index()].
3445 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3448 ** CAPI3REF: Name Of A Host Parameter
3450 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3451 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3452 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3453 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3454 ** respectively.
3455 ** In other words, the initial ":" or "$" or "@" or "?"
3456 ** is included as part of the name.)^
3457 ** ^Parameters of the form "?" without a following integer have no name
3458 ** and are referred to as "nameless" or "anonymous parameters".
3460 ** ^The first host parameter has an index of 1, not 0.
3462 ** ^If the value N is out of range or if the N-th parameter is
3463 ** nameless, then NULL is returned. ^The returned string is
3464 ** always in UTF-8 encoding even if the named parameter was
3465 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3466 ** [sqlite3_prepare16_v2()].
3468 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3469 ** [sqlite3_bind_parameter_count()], and
3470 ** [sqlite3_bind_parameter_index()].
3472 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3475 ** CAPI3REF: Index Of A Parameter With A Given Name
3477 ** ^Return the index of an SQL parameter given its name. ^The
3478 ** index value returned is suitable for use as the second
3479 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3480 ** is returned if no matching parameter is found. ^The parameter
3481 ** name must be given in UTF-8 even if the original statement
3482 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3484 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3485 ** [sqlite3_bind_parameter_count()], and
3486 ** [sqlite3_bind_parameter_index()].
3488 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3491 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3493 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3494 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3495 ** ^Use this routine to reset all host parameters to NULL.
3497 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3500 ** CAPI3REF: Number Of Columns In A Result Set
3502 ** ^Return the number of columns in the result set returned by the
3503 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3504 ** statement that does not return data (for example an [UPDATE]).
3506 ** See also: [sqlite3_data_count()]
3508 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3511 ** CAPI3REF: Column Names In A Result Set
3513 ** ^These routines return the name assigned to a particular column
3514 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3515 ** interface returns a pointer to a zero-terminated UTF-8 string
3516 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3517 ** UTF-16 string. ^The first parameter is the [prepared statement]
3518 ** that implements the [SELECT] statement. ^The second parameter is the
3519 ** column number. ^The leftmost column is number 0.
3521 ** ^The returned string pointer is valid until either the [prepared statement]
3522 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3523 ** reprepared by the first call to [sqlite3_step()] for a particular run
3524 ** or until the next call to
3525 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3527 ** ^If sqlite3_malloc() fails during the processing of either routine
3528 ** (for example during a conversion from UTF-8 to UTF-16) then a
3529 ** NULL pointer is returned.
3531 ** ^The name of a result column is the value of the "AS" clause for
3532 ** that column, if there is an AS clause. If there is no AS clause
3533 ** then the name of the column is unspecified and may change from
3534 ** one release of SQLite to the next.
3536 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3537 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3540 ** CAPI3REF: Source Of Data In A Query Result
3542 ** ^These routines provide a means to determine the database, table, and
3543 ** table column that is the origin of a particular result column in
3544 ** [SELECT] statement.
3545 ** ^The name of the database or table or column can be returned as
3546 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
3547 ** the database name, the _table_ routines return the table name, and
3548 ** the origin_ routines return the column name.
3549 ** ^The returned string is valid until the [prepared statement] is destroyed
3550 ** using [sqlite3_finalize()] or until the statement is automatically
3551 ** reprepared by the first call to [sqlite3_step()] for a particular run
3552 ** or until the same information is requested
3553 ** again in a different encoding.
3555 ** ^The names returned are the original un-aliased names of the
3556 ** database, table, and column.
3558 ** ^The first argument to these interfaces is a [prepared statement].
3559 ** ^These functions return information about the Nth result column returned by
3560 ** the statement, where N is the second function argument.
3561 ** ^The left-most column is column 0 for these routines.
3563 ** ^If the Nth column returned by the statement is an expression or
3564 ** subquery and is not a column value, then all of these functions return
3565 ** NULL. ^These routine might also return NULL if a memory allocation error
3566 ** occurs. ^Otherwise, they return the name of the attached database, table,
3567 ** or column that query result column was extracted from.
3569 ** ^As with all other SQLite APIs, those whose names end with "16" return
3570 ** UTF-16 encoded strings and the other functions return UTF-8.
3572 ** ^These APIs are only available if the library was compiled with the
3573 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3575 ** If two or more threads call one or more of these routines against the same
3576 ** prepared statement and column at the same time then the results are
3577 ** undefined.
3579 ** If two or more threads call one or more
3580 ** [sqlite3_column_database_name | column metadata interfaces]
3581 ** for the same [prepared statement] and result column
3582 ** at the same time then the results are undefined.
3584 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3585 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3586 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3587 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3588 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3589 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3592 ** CAPI3REF: Declared Datatype Of A Query Result
3594 ** ^(The first parameter is a [prepared statement].
3595 ** If this statement is a [SELECT] statement and the Nth column of the
3596 ** returned result set of that [SELECT] is a table column (not an
3597 ** expression or subquery) then the declared type of the table
3598 ** column is returned.)^ ^If the Nth column of the result set is an
3599 ** expression or subquery, then a NULL pointer is returned.
3600 ** ^The returned string is always UTF-8 encoded.
3602 ** ^(For example, given the database schema:
3604 ** CREATE TABLE t1(c1 VARIANT);
3606 ** and the following statement to be compiled:
3608 ** SELECT c1 + 1, c1 FROM t1;
3610 ** this routine would return the string "VARIANT" for the second result
3611 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3613 ** ^SQLite uses dynamic run-time typing. ^So just because a column
3614 ** is declared to contain a particular type does not mean that the
3615 ** data stored in that column is of the declared type. SQLite is
3616 ** strongly typed, but the typing is dynamic not static. ^Type
3617 ** is associated with individual values, not with the containers
3618 ** used to hold those values.
3620 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3621 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3624 ** CAPI3REF: Evaluate An SQL Statement
3626 ** After a [prepared statement] has been prepared using either
3627 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3628 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3629 ** must be called one or more times to evaluate the statement.
3631 ** The details of the behavior of the sqlite3_step() interface depend
3632 ** on whether the statement was prepared using the newer "v2" interface
3633 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3634 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
3635 ** new "v2" interface is recommended for new applications but the legacy
3636 ** interface will continue to be supported.
3638 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3639 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3640 ** ^With the "v2" interface, any of the other [result codes] or
3641 ** [extended result codes] might be returned as well.
3643 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3644 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
3645 ** or occurs outside of an explicit transaction, then you can retry the
3646 ** statement. If the statement is not a [COMMIT] and occurs within an
3647 ** explicit transaction then you should rollback the transaction before
3648 ** continuing.
3650 ** ^[SQLITE_DONE] means that the statement has finished executing
3651 ** successfully. sqlite3_step() should not be called again on this virtual
3652 ** machine without first calling [sqlite3_reset()] to reset the virtual
3653 ** machine back to its initial state.
3655 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3656 ** is returned each time a new row of data is ready for processing by the
3657 ** caller. The values may be accessed using the [column access functions].
3658 ** sqlite3_step() is called again to retrieve the next row of data.
3660 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3661 ** violation) has occurred. sqlite3_step() should not be called again on
3662 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3663 ** ^With the legacy interface, a more specific error code (for example,
3664 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3665 ** can be obtained by calling [sqlite3_reset()] on the
3666 ** [prepared statement]. ^In the "v2" interface,
3667 ** the more specific error code is returned directly by sqlite3_step().
3669 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3670 ** Perhaps it was called on a [prepared statement] that has
3671 ** already been [sqlite3_finalize | finalized] or on one that had
3672 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
3673 ** be the case that the same database connection is being used by two or
3674 ** more threads at the same moment in time.
3676 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3677 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3678 ** other than [SQLITE_ROW] before any subsequent invocation of
3679 ** sqlite3_step(). Failure to reset the prepared statement using
3680 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3681 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
3682 ** calling [sqlite3_reset()] automatically in this circumstance rather
3683 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
3684 ** break because any application that ever receives an SQLITE_MISUSE error
3685 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
3686 ** can be used to restore the legacy behavior.
3688 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3689 ** API always returns a generic error code, [SQLITE_ERROR], following any
3690 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
3691 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3692 ** specific [error codes] that better describes the error.
3693 ** We admit that this is a goofy design. The problem has been fixed
3694 ** with the "v2" interface. If you prepare all of your SQL statements
3695 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3696 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3697 ** then the more specific [error codes] are returned directly
3698 ** by sqlite3_step(). The use of the "v2" interface is recommended.
3700 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3703 ** CAPI3REF: Number of columns in a result set
3705 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3706 ** current row of the result set of [prepared statement] P.
3707 ** ^If prepared statement P does not have results ready to return
3708 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3709 ** interfaces) then sqlite3_data_count(P) returns 0.
3710 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3711 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
3712 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
3713 ** will return non-zero if previous call to [sqlite3_step](P) returned
3714 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
3715 ** where it always returns zero since each step of that multi-step
3716 ** pragma returns 0 columns of data.
3718 ** See also: [sqlite3_column_count()]
3720 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3723 ** CAPI3REF: Fundamental Datatypes
3724 ** KEYWORDS: SQLITE_TEXT
3726 ** ^(Every value in SQLite has one of five fundamental datatypes:
3728 ** <ul>
3729 ** <li> 64-bit signed integer
3730 ** <li> 64-bit IEEE floating point number
3731 ** <li> string
3732 ** <li> BLOB
3733 ** <li> NULL
3734 ** </ul>)^
3736 ** These constants are codes for each of those types.
3738 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3739 ** for a completely different meaning. Software that links against both
3740 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3741 ** SQLITE_TEXT.
3743 #define SQLITE_INTEGER 1
3744 #define SQLITE_FLOAT 2
3745 #define SQLITE_BLOB 4
3746 #define SQLITE_NULL 5
3747 #ifdef SQLITE_TEXT
3748 # undef SQLITE_TEXT
3749 #else
3750 # define SQLITE_TEXT 3
3751 #endif
3752 #define SQLITE3_TEXT 3
3755 ** CAPI3REF: Result Values From A Query
3756 ** KEYWORDS: {column access functions}
3758 ** These routines form the "result set" interface.
3760 ** ^These routines return information about a single column of the current
3761 ** result row of a query. ^In every case the first argument is a pointer
3762 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3763 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3764 ** and the second argument is the index of the column for which information
3765 ** should be returned. ^The leftmost column of the result set has the index 0.
3766 ** ^The number of columns in the result can be determined using
3767 ** [sqlite3_column_count()].
3769 ** If the SQL statement does not currently point to a valid row, or if the
3770 ** column index is out of range, the result is undefined.
3771 ** These routines may only be called when the most recent call to
3772 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3773 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3774 ** If any of these routines are called after [sqlite3_reset()] or
3775 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3776 ** something other than [SQLITE_ROW], the results are undefined.
3777 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3778 ** are called from a different thread while any of these routines
3779 ** are pending, then the results are undefined.
3781 ** ^The sqlite3_column_type() routine returns the
3782 ** [SQLITE_INTEGER | datatype code] for the initial data type
3783 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
3784 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
3785 ** returned by sqlite3_column_type() is only meaningful if no type
3786 ** conversions have occurred as described below. After a type conversion,
3787 ** the value returned by sqlite3_column_type() is undefined. Future
3788 ** versions of SQLite may change the behavior of sqlite3_column_type()
3789 ** following a type conversion.
3791 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3792 ** routine returns the number of bytes in that BLOB or string.
3793 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3794 ** the string to UTF-8 and then returns the number of bytes.
3795 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3796 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3797 ** the number of bytes in that string.
3798 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3800 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3801 ** routine returns the number of bytes in that BLOB or string.
3802 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3803 ** the string to UTF-16 and then returns the number of bytes.
3804 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3805 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3806 ** the number of bytes in that string.
3807 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3809 ** ^The values returned by [sqlite3_column_bytes()] and
3810 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
3811 ** of the string. ^For clarity: the values returned by
3812 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
3813 ** bytes in the string, not the number of characters.
3815 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3816 ** even empty strings, are always zero-terminated. ^The return
3817 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
3819 ** ^The object returned by [sqlite3_column_value()] is an
3820 ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
3821 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3822 ** If the [unprotected sqlite3_value] object returned by
3823 ** [sqlite3_column_value()] is used in any other way, including calls
3824 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3825 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3827 ** These routines attempt to convert the value where appropriate. ^For
3828 ** example, if the internal representation is FLOAT and a text result
3829 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3830 ** conversion automatically. ^(The following table details the conversions
3831 ** that are applied:
3833 ** <blockquote>
3834 ** <table border="1">
3835 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
3837 ** <tr><td> NULL <td> INTEGER <td> Result is 0
3838 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
3839 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
3840 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
3841 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
3842 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
3843 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
3844 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
3845 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
3846 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
3847 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
3848 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
3849 ** <tr><td> TEXT <td> BLOB <td> No change
3850 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
3851 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
3852 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
3853 ** </table>
3854 ** </blockquote>)^
3856 ** The table above makes reference to standard C library functions atoi()
3857 ** and atof(). SQLite does not really use these functions. It has its
3858 ** own equivalent internal routines. The atoi() and atof() names are
3859 ** used in the table for brevity and because they are familiar to most
3860 ** C programmers.
3862 ** Note that when type conversions occur, pointers returned by prior
3863 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3864 ** sqlite3_column_text16() may be invalidated.
3865 ** Type conversions and pointer invalidations might occur
3866 ** in the following cases:
3868 ** <ul>
3869 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3870 ** sqlite3_column_text16() is called. A zero-terminator might
3871 ** need to be added to the string.</li>
3872 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3873 ** sqlite3_column_text16() is called. The content must be converted
3874 ** to UTF-16.</li>
3875 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3876 ** sqlite3_column_text() is called. The content must be converted
3877 ** to UTF-8.</li>
3878 ** </ul>
3880 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3881 ** not invalidate a prior pointer, though of course the content of the buffer
3882 ** that the prior pointer references will have been modified. Other kinds
3883 ** of conversion are done in place when it is possible, but sometimes they
3884 ** are not possible and in those cases prior pointers are invalidated.
3886 ** The safest and easiest to remember policy is to invoke these routines
3887 ** in one of the following ways:
3889 ** <ul>
3890 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3891 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3892 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3893 ** </ul>
3895 ** In other words, you should call sqlite3_column_text(),
3896 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3897 ** into the desired format, then invoke sqlite3_column_bytes() or
3898 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
3899 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3900 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3901 ** with calls to sqlite3_column_bytes().
3903 ** ^The pointers returned are valid until a type conversion occurs as
3904 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3905 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
3906 ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
3907 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3908 ** [sqlite3_free()].
3910 ** ^(If a memory allocation error occurs during the evaluation of any
3911 ** of these routines, a default value is returned. The default value
3912 ** is either the integer 0, the floating point number 0.0, or a NULL
3913 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
3914 ** [SQLITE_NOMEM].)^
3916 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3917 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3918 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3919 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3920 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3921 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3922 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3923 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3924 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3925 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3928 ** CAPI3REF: Destroy A Prepared Statement Object
3930 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3931 ** ^If the most recent evaluation of the statement encountered no errors
3932 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
3933 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
3934 ** sqlite3_finalize(S) returns the appropriate [error code] or
3935 ** [extended error code].
3937 ** ^The sqlite3_finalize(S) routine can be called at any point during
3938 ** the life cycle of [prepared statement] S:
3939 ** before statement S is ever evaluated, after
3940 ** one or more calls to [sqlite3_reset()], or after any call
3941 ** to [sqlite3_step()] regardless of whether or not the statement has
3942 ** completed execution.
3944 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
3946 ** The application must finalize every [prepared statement] in order to avoid
3947 ** resource leaks. It is a grievous error for the application to try to use
3948 ** a prepared statement after it has been finalized. Any use of a prepared
3949 ** statement after it has been finalized can result in undefined and
3950 ** undesirable behavior such as segfaults and heap corruption.
3952 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3955 ** CAPI3REF: Reset A Prepared Statement Object
3957 ** The sqlite3_reset() function is called to reset a [prepared statement]
3958 ** object back to its initial state, ready to be re-executed.
3959 ** ^Any SQL statement variables that had values bound to them using
3960 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3961 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3963 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3964 ** back to the beginning of its program.
3966 ** ^If the most recent call to [sqlite3_step(S)] for the
3967 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3968 ** or if [sqlite3_step(S)] has never before been called on S,
3969 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3971 ** ^If the most recent call to [sqlite3_step(S)] for the
3972 ** [prepared statement] S indicated an error, then
3973 ** [sqlite3_reset(S)] returns an appropriate [error code].
3975 ** ^The [sqlite3_reset(S)] interface does not change the values
3976 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3978 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3981 ** CAPI3REF: Create Or Redefine SQL Functions
3982 ** KEYWORDS: {function creation routines}
3983 ** KEYWORDS: {application-defined SQL function}
3984 ** KEYWORDS: {application-defined SQL functions}
3986 ** ^These functions (collectively known as "function creation routines")
3987 ** are used to add SQL functions or aggregates or to redefine the behavior
3988 ** of existing SQL functions or aggregates. The only differences between
3989 ** these routines are the text encoding expected for
3990 ** the second parameter (the name of the function being created)
3991 ** and the presence or absence of a destructor callback for
3992 ** the application data pointer.
3994 ** ^The first parameter is the [database connection] to which the SQL
3995 ** function is to be added. ^If an application uses more than one database
3996 ** connection then application-defined SQL functions must be added
3997 ** to each database connection separately.
3999 ** ^The second parameter is the name of the SQL function to be created or
4000 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4001 ** representation, exclusive of the zero-terminator. ^Note that the name
4002 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4003 ** ^Any attempt to create a function with a longer name
4004 ** will result in [SQLITE_MISUSE] being returned.
4006 ** ^The third parameter (nArg)
4007 ** is the number of arguments that the SQL function or
4008 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4009 ** aggregate may take any number of arguments between 0 and the limit
4010 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4011 ** parameter is less than -1 or greater than 127 then the behavior is
4012 ** undefined.
4014 ** ^The fourth parameter, eTextRep, specifies what
4015 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4016 ** its parameters. The application should set this parameter to
4017 ** [SQLITE_UTF16LE] if the function implementation invokes
4018 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4019 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4020 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4021 ** otherwise. ^The same SQL function may be registered multiple times using
4022 ** different preferred text encodings, with different implementations for
4023 ** each encoding.
4024 ** ^When multiple implementations of the same function are available, SQLite
4025 ** will pick the one that involves the least amount of data conversion.
4027 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4028 ** to signal that the function will always return the same result given
4029 ** the same inputs within a single SQL statement. Most SQL functions are
4030 ** deterministic. The built-in [random()] SQL function is an example of a
4031 ** function that is not deterministic. The SQLite query planner is able to
4032 ** perform additional optimizations on deterministic functions, so use
4033 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4035 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4036 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4038 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4039 ** pointers to C-language functions that implement the SQL function or
4040 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4041 ** callback only; NULL pointers must be passed as the xStep and xFinal
4042 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4043 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4044 ** SQL function or aggregate, pass NULL pointers for all three function
4045 ** callbacks.
4047 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4048 ** then it is destructor for the application data pointer.
4049 ** The destructor is invoked when the function is deleted, either by being
4050 ** overloaded or when the database connection closes.)^
4051 ** ^The destructor is also invoked if the call to
4052 ** sqlite3_create_function_v2() fails.
4053 ** ^When the destructor callback of the tenth parameter is invoked, it
4054 ** is passed a single argument which is a copy of the application data
4055 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4057 ** ^It is permitted to register multiple implementations of the same
4058 ** functions with the same name but with either differing numbers of
4059 ** arguments or differing preferred text encodings. ^SQLite will use
4060 ** the implementation that most closely matches the way in which the
4061 ** SQL function is used. ^A function implementation with a non-negative
4062 ** nArg parameter is a better match than a function implementation with
4063 ** a negative nArg. ^A function where the preferred text encoding
4064 ** matches the database encoding is a better
4065 ** match than a function where the encoding is different.
4066 ** ^A function where the encoding difference is between UTF16le and UTF16be
4067 ** is a closer match than a function where the encoding difference is
4068 ** between UTF8 and UTF16.
4070 ** ^Built-in functions may be overloaded by new application-defined functions.
4072 ** ^An application-defined function is permitted to call other
4073 ** SQLite interfaces. However, such calls must not
4074 ** close the database connection nor finalize or reset the prepared
4075 ** statement in which the function is running.
4077 SQLITE_API int sqlite3_create_function(
4078 sqlite3 *db,
4079 const char *zFunctionName,
4080 int nArg,
4081 int eTextRep,
4082 void *pApp,
4083 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4084 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4085 void (*xFinal)(sqlite3_context*)
4087 SQLITE_API int sqlite3_create_function16(
4088 sqlite3 *db,
4089 const void *zFunctionName,
4090 int nArg,
4091 int eTextRep,
4092 void *pApp,
4093 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4094 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4095 void (*xFinal)(sqlite3_context*)
4097 SQLITE_API int sqlite3_create_function_v2(
4098 sqlite3 *db,
4099 const char *zFunctionName,
4100 int nArg,
4101 int eTextRep,
4102 void *pApp,
4103 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4104 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4105 void (*xFinal)(sqlite3_context*),
4106 void(*xDestroy)(void*)
4110 ** CAPI3REF: Text Encodings
4112 ** These constant define integer codes that represent the various
4113 ** text encodings supported by SQLite.
4115 #define SQLITE_UTF8 1
4116 #define SQLITE_UTF16LE 2
4117 #define SQLITE_UTF16BE 3
4118 #define SQLITE_UTF16 4 /* Use native byte order */
4119 #define SQLITE_ANY 5 /* Deprecated */
4120 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4123 ** CAPI3REF: Function Flags
4125 ** These constants may be ORed together with the
4126 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4127 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4128 ** [sqlite3_create_function_v2()].
4130 #define SQLITE_DETERMINISTIC 0x800
4133 ** CAPI3REF: Deprecated Functions
4134 ** DEPRECATED
4136 ** These functions are [deprecated]. In order to maintain
4137 ** backwards compatibility with older code, these functions continue
4138 ** to be supported. However, new applications should avoid
4139 ** the use of these functions. To help encourage people to avoid
4140 ** using these functions, we are not going to tell you what they do.
4142 #ifndef SQLITE_OMIT_DEPRECATED
4143 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4144 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4145 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4146 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4147 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4148 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4149 void*,sqlite3_int64);
4150 #endif
4153 ** CAPI3REF: Obtaining SQL Function Parameter Values
4155 ** The C-language implementation of SQL functions and aggregates uses
4156 ** this set of interface routines to access the parameter values on
4157 ** the function or aggregate.
4159 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4160 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4161 ** define callbacks that implement the SQL functions and aggregates.
4162 ** The 3rd parameter to these callbacks is an array of pointers to
4163 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4164 ** each parameter to the SQL function. These routines are used to
4165 ** extract values from the [sqlite3_value] objects.
4167 ** These routines work only with [protected sqlite3_value] objects.
4168 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4169 ** object results in undefined behavior.
4171 ** ^These routines work just like the corresponding [column access functions]
4172 ** except that these routines take a single [protected sqlite3_value] object
4173 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4175 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4176 ** in the native byte-order of the host machine. ^The
4177 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4178 ** extract UTF-16 strings as big-endian and little-endian respectively.
4180 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4181 ** numeric affinity to the value. This means that an attempt is
4182 ** made to convert the value to an integer or floating point. If
4183 ** such a conversion is possible without loss of information (in other
4184 ** words, if the value is a string that looks like a number)
4185 ** then the conversion is performed. Otherwise no conversion occurs.
4186 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4188 ** Please pay particular attention to the fact that the pointer returned
4189 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4190 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4191 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4192 ** or [sqlite3_value_text16()].
4194 ** These routines must be called from the same thread as
4195 ** the SQL function that supplied the [sqlite3_value*] parameters.
4197 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4198 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4199 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4200 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4201 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4202 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4203 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4204 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4205 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4206 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4207 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4208 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4211 ** CAPI3REF: Obtain Aggregate Function Context
4213 ** Implementations of aggregate SQL functions use this
4214 ** routine to allocate memory for storing their state.
4216 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4217 ** for a particular aggregate function, SQLite
4218 ** allocates N of memory, zeroes out that memory, and returns a pointer
4219 ** to the new memory. ^On second and subsequent calls to
4220 ** sqlite3_aggregate_context() for the same aggregate function instance,
4221 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4222 ** called once for each invocation of the xStep callback and then one
4223 ** last time when the xFinal callback is invoked. ^(When no rows match
4224 ** an aggregate query, the xStep() callback of the aggregate function
4225 ** implementation is never called and xFinal() is called exactly once.
4226 ** In those cases, sqlite3_aggregate_context() might be called for the
4227 ** first time from within xFinal().)^
4229 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4230 ** when first called if N is less than or equal to zero or if a memory
4231 ** allocate error occurs.
4233 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4234 ** determined by the N parameter on first successful call. Changing the
4235 ** value of N in subsequent call to sqlite3_aggregate_context() within
4236 ** the same aggregate function instance will not resize the memory
4237 ** allocation.)^ Within the xFinal callback, it is customary to set
4238 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4239 ** pointless memory allocations occur.
4241 ** ^SQLite automatically frees the memory allocated by
4242 ** sqlite3_aggregate_context() when the aggregate query concludes.
4244 ** The first parameter must be a copy of the
4245 ** [sqlite3_context | SQL function context] that is the first parameter
4246 ** to the xStep or xFinal callback routine that implements the aggregate
4247 ** function.
4249 ** This routine must be called from the same thread in which
4250 ** the aggregate SQL function is running.
4252 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4255 ** CAPI3REF: User Data For Functions
4257 ** ^The sqlite3_user_data() interface returns a copy of
4258 ** the pointer that was the pUserData parameter (the 5th parameter)
4259 ** of the [sqlite3_create_function()]
4260 ** and [sqlite3_create_function16()] routines that originally
4261 ** registered the application defined function.
4263 ** This routine must be called from the same thread in which
4264 ** the application-defined function is running.
4266 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4269 ** CAPI3REF: Database Connection For Functions
4271 ** ^The sqlite3_context_db_handle() interface returns a copy of
4272 ** the pointer to the [database connection] (the 1st parameter)
4273 ** of the [sqlite3_create_function()]
4274 ** and [sqlite3_create_function16()] routines that originally
4275 ** registered the application defined function.
4277 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4280 ** CAPI3REF: Function Auxiliary Data
4282 ** These functions may be used by (non-aggregate) SQL functions to
4283 ** associate metadata with argument values. If the same value is passed to
4284 ** multiple invocations of the same SQL function during query execution, under
4285 ** some circumstances the associated metadata may be preserved. An example
4286 ** of where this might be useful is in a regular-expression matching
4287 ** function. The compiled version of the regular expression can be stored as
4288 ** metadata associated with the pattern string.
4289 ** Then as long as the pattern string remains the same,
4290 ** the compiled regular expression can be reused on multiple
4291 ** invocations of the same function.
4293 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4294 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4295 ** value to the application-defined function. ^If there is no metadata
4296 ** associated with the function argument, this sqlite3_get_auxdata() interface
4297 ** returns a NULL pointer.
4299 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4300 ** argument of the application-defined function. ^Subsequent
4301 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4302 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4303 ** NULL if the metadata has been discarded.
4304 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4305 ** SQLite will invoke the destructor function X with parameter P exactly
4306 ** once, when the metadata is discarded.
4307 ** SQLite is free to discard the metadata at any time, including: <ul>
4308 ** <li> when the corresponding function parameter changes, or
4309 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4310 ** SQL statement, or
4311 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4312 ** <li> during the original sqlite3_set_auxdata() call when a memory
4313 ** allocation error occurs. </ul>)^
4315 ** Note the last bullet in particular. The destructor X in
4316 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4317 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4318 ** should be called near the end of the function implementation and the
4319 ** function implementation should not make any use of P after
4320 ** sqlite3_set_auxdata() has been called.
4322 ** ^(In practice, metadata is preserved between function calls for
4323 ** function parameters that are compile-time constants, including literal
4324 ** values and [parameters] and expressions composed from the same.)^
4326 ** These routines must be called from the same thread in which
4327 ** the SQL function is running.
4329 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4330 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4334 ** CAPI3REF: Constants Defining Special Destructor Behavior
4336 ** These are special values for the destructor that is passed in as the
4337 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4338 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4339 ** and will never change. It does not need to be destroyed. ^The
4340 ** SQLITE_TRANSIENT value means that the content will likely change in
4341 ** the near future and that SQLite should make its own private copy of
4342 ** the content before returning.
4344 ** The typedef is necessary to work around problems in certain
4345 ** C++ compilers.
4347 typedef void (*sqlite3_destructor_type)(void*);
4348 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4349 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4352 ** CAPI3REF: Setting The Result Of An SQL Function
4354 ** These routines are used by the xFunc or xFinal callbacks that
4355 ** implement SQL functions and aggregates. See
4356 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4357 ** for additional information.
4359 ** These functions work very much like the [parameter binding] family of
4360 ** functions used to bind values to host parameters in prepared statements.
4361 ** Refer to the [SQL parameter] documentation for additional information.
4363 ** ^The sqlite3_result_blob() interface sets the result from
4364 ** an application-defined function to be the BLOB whose content is pointed
4365 ** to by the second parameter and which is N bytes long where N is the
4366 ** third parameter.
4368 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4369 ** the application-defined function to be a BLOB containing all zero
4370 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4372 ** ^The sqlite3_result_double() interface sets the result from
4373 ** an application-defined function to be a floating point value specified
4374 ** by its 2nd argument.
4376 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4377 ** cause the implemented SQL function to throw an exception.
4378 ** ^SQLite uses the string pointed to by the
4379 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4380 ** as the text of an error message. ^SQLite interprets the error
4381 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4382 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4383 ** byte order. ^If the third parameter to sqlite3_result_error()
4384 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4385 ** message all text up through the first zero character.
4386 ** ^If the third parameter to sqlite3_result_error() or
4387 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4388 ** bytes (not characters) from the 2nd parameter as the error message.
4389 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4390 ** routines make a private copy of the error message text before
4391 ** they return. Hence, the calling function can deallocate or
4392 ** modify the text after they return without harm.
4393 ** ^The sqlite3_result_error_code() function changes the error code
4394 ** returned by SQLite as a result of an error in a function. ^By default,
4395 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4396 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4398 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4399 ** error indicating that a string or BLOB is too long to represent.
4401 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4402 ** error indicating that a memory allocation failed.
4404 ** ^The sqlite3_result_int() interface sets the return value
4405 ** of the application-defined function to be the 32-bit signed integer
4406 ** value given in the 2nd argument.
4407 ** ^The sqlite3_result_int64() interface sets the return value
4408 ** of the application-defined function to be the 64-bit signed integer
4409 ** value given in the 2nd argument.
4411 ** ^The sqlite3_result_null() interface sets the return value
4412 ** of the application-defined function to be NULL.
4414 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4415 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4416 ** set the return value of the application-defined function to be
4417 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4418 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4419 ** ^SQLite takes the text result from the application from
4420 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4421 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4422 ** is negative, then SQLite takes result text from the 2nd parameter
4423 ** through the first zero character.
4424 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4425 ** is non-negative, then as many bytes (not characters) of the text
4426 ** pointed to by the 2nd parameter are taken as the application-defined
4427 ** function result. If the 3rd parameter is non-negative, then it
4428 ** must be the byte offset into the string where the NUL terminator would
4429 ** appear if the string where NUL terminated. If any NUL characters occur
4430 ** in the string at a byte offset that is less than the value of the 3rd
4431 ** parameter, then the resulting string will contain embedded NULs and the
4432 ** result of expressions operating on strings with embedded NULs is undefined.
4433 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4434 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4435 ** function as the destructor on the text or BLOB result when it has
4436 ** finished using that result.
4437 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4438 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4439 ** assumes that the text or BLOB result is in constant space and does not
4440 ** copy the content of the parameter nor call a destructor on the content
4441 ** when it has finished using that result.
4442 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4443 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4444 ** then SQLite makes a copy of the result into space obtained from
4445 ** from [sqlite3_malloc()] before it returns.
4447 ** ^The sqlite3_result_value() interface sets the result of
4448 ** the application-defined function to be a copy the
4449 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4450 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4451 ** so that the [sqlite3_value] specified in the parameter may change or
4452 ** be deallocated after sqlite3_result_value() returns without harm.
4453 ** ^A [protected sqlite3_value] object may always be used where an
4454 ** [unprotected sqlite3_value] object is required, so either
4455 ** kind of [sqlite3_value] object can be used with this interface.
4457 ** If these routines are called from within the different thread
4458 ** than the one containing the application-defined function that received
4459 ** the [sqlite3_context] pointer, the results are undefined.
4461 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4462 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4463 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4464 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4465 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4466 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4467 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4468 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4469 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4470 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4471 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4472 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4473 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4474 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4475 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4476 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4479 ** CAPI3REF: Define New Collating Sequences
4481 ** ^These functions add, remove, or modify a [collation] associated
4482 ** with the [database connection] specified as the first argument.
4484 ** ^The name of the collation is a UTF-8 string
4485 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4486 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4487 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4488 ** considered to be the same name.
4490 ** ^(The third argument (eTextRep) must be one of the constants:
4491 ** <ul>
4492 ** <li> [SQLITE_UTF8],
4493 ** <li> [SQLITE_UTF16LE],
4494 ** <li> [SQLITE_UTF16BE],
4495 ** <li> [SQLITE_UTF16], or
4496 ** <li> [SQLITE_UTF16_ALIGNED].
4497 ** </ul>)^
4498 ** ^The eTextRep argument determines the encoding of strings passed
4499 ** to the collating function callback, xCallback.
4500 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4501 ** force strings to be UTF16 with native byte order.
4502 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4503 ** on an even byte address.
4505 ** ^The fourth argument, pArg, is an application data pointer that is passed
4506 ** through as the first argument to the collating function callback.
4508 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4509 ** ^Multiple collating functions can be registered using the same name but
4510 ** with different eTextRep parameters and SQLite will use whichever
4511 ** function requires the least amount of data transformation.
4512 ** ^If the xCallback argument is NULL then the collating function is
4513 ** deleted. ^When all collating functions having the same name are deleted,
4514 ** that collation is no longer usable.
4516 ** ^The collating function callback is invoked with a copy of the pArg
4517 ** application data pointer and with two strings in the encoding specified
4518 ** by the eTextRep argument. The collating function must return an
4519 ** integer that is negative, zero, or positive
4520 ** if the first string is less than, equal to, or greater than the second,
4521 ** respectively. A collating function must always return the same answer
4522 ** given the same inputs. If two or more collating functions are registered
4523 ** to the same collation name (using different eTextRep values) then all
4524 ** must give an equivalent answer when invoked with equivalent strings.
4525 ** The collating function must obey the following properties for all
4526 ** strings A, B, and C:
4528 ** <ol>
4529 ** <li> If A==B then B==A.
4530 ** <li> If A==B and B==C then A==C.
4531 ** <li> If A&lt;B THEN B&gt;A.
4532 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4533 ** </ol>
4535 ** If a collating function fails any of the above constraints and that
4536 ** collating function is registered and used, then the behavior of SQLite
4537 ** is undefined.
4539 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4540 ** with the addition that the xDestroy callback is invoked on pArg when
4541 ** the collating function is deleted.
4542 ** ^Collating functions are deleted when they are overridden by later
4543 ** calls to the collation creation functions or when the
4544 ** [database connection] is closed using [sqlite3_close()].
4546 ** ^The xDestroy callback is <u>not</u> called if the
4547 ** sqlite3_create_collation_v2() function fails. Applications that invoke
4548 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4549 ** check the return code and dispose of the application data pointer
4550 ** themselves rather than expecting SQLite to deal with it for them.
4551 ** This is different from every other SQLite interface. The inconsistency
4552 ** is unfortunate but cannot be changed without breaking backwards
4553 ** compatibility.
4555 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4557 SQLITE_API int sqlite3_create_collation(
4558 sqlite3*,
4559 const char *zName,
4560 int eTextRep,
4561 void *pArg,
4562 int(*xCompare)(void*,int,const void*,int,const void*)
4564 SQLITE_API int sqlite3_create_collation_v2(
4565 sqlite3*,
4566 const char *zName,
4567 int eTextRep,
4568 void *pArg,
4569 int(*xCompare)(void*,int,const void*,int,const void*),
4570 void(*xDestroy)(void*)
4572 SQLITE_API int sqlite3_create_collation16(
4573 sqlite3*,
4574 const void *zName,
4575 int eTextRep,
4576 void *pArg,
4577 int(*xCompare)(void*,int,const void*,int,const void*)
4581 ** CAPI3REF: Collation Needed Callbacks
4583 ** ^To avoid having to register all collation sequences before a database
4584 ** can be used, a single callback function may be registered with the
4585 ** [database connection] to be invoked whenever an undefined collation
4586 ** sequence is required.
4588 ** ^If the function is registered using the sqlite3_collation_needed() API,
4589 ** then it is passed the names of undefined collation sequences as strings
4590 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4591 ** the names are passed as UTF-16 in machine native byte order.
4592 ** ^A call to either function replaces the existing collation-needed callback.
4594 ** ^(When the callback is invoked, the first argument passed is a copy
4595 ** of the second argument to sqlite3_collation_needed() or
4596 ** sqlite3_collation_needed16(). The second argument is the database
4597 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4598 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4599 ** sequence function required. The fourth parameter is the name of the
4600 ** required collation sequence.)^
4602 ** The callback function should register the desired collation using
4603 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4604 ** [sqlite3_create_collation_v2()].
4606 SQLITE_API int sqlite3_collation_needed(
4607 sqlite3*,
4608 void*,
4609 void(*)(void*,sqlite3*,int eTextRep,const char*)
4611 SQLITE_API int sqlite3_collation_needed16(
4612 sqlite3*,
4613 void*,
4614 void(*)(void*,sqlite3*,int eTextRep,const void*)
4617 #ifdef SQLITE_HAS_CODEC
4619 ** Specify the key for an encrypted database. This routine should be
4620 ** called right after sqlite3_open().
4622 ** The code to implement this API is not available in the public release
4623 ** of SQLite.
4625 SQLITE_API int sqlite3_key(
4626 sqlite3 *db, /* Database to be rekeyed */
4627 const void *pKey, int nKey /* The key */
4629 SQLITE_API int sqlite3_key_v2(
4630 sqlite3 *db, /* Database to be rekeyed */
4631 const char *zDbName, /* Name of the database */
4632 const void *pKey, int nKey /* The key */
4636 ** Change the key on an open database. If the current database is not
4637 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
4638 ** database is decrypted.
4640 ** The code to implement this API is not available in the public release
4641 ** of SQLite.
4643 SQLITE_API int sqlite3_rekey(
4644 sqlite3 *db, /* Database to be rekeyed */
4645 const void *pKey, int nKey /* The new key */
4647 SQLITE_API int sqlite3_rekey_v2(
4648 sqlite3 *db, /* Database to be rekeyed */
4649 const char *zDbName, /* Name of the database */
4650 const void *pKey, int nKey /* The new key */
4654 ** Specify the activation key for a SEE database. Unless
4655 ** activated, none of the SEE routines will work.
4657 SQLITE_API void sqlite3_activate_see(
4658 const char *zPassPhrase /* Activation phrase */
4660 #endif
4662 #ifdef SQLITE_ENABLE_CEROD
4664 ** Specify the activation key for a CEROD database. Unless
4665 ** activated, none of the CEROD routines will work.
4667 SQLITE_API void sqlite3_activate_cerod(
4668 const char *zPassPhrase /* Activation phrase */
4670 #endif
4673 ** CAPI3REF: Suspend Execution For A Short Time
4675 ** The sqlite3_sleep() function causes the current thread to suspend execution
4676 ** for at least a number of milliseconds specified in its parameter.
4678 ** If the operating system does not support sleep requests with
4679 ** millisecond time resolution, then the time will be rounded up to
4680 ** the nearest second. The number of milliseconds of sleep actually
4681 ** requested from the operating system is returned.
4683 ** ^SQLite implements this interface by calling the xSleep()
4684 ** method of the default [sqlite3_vfs] object. If the xSleep() method
4685 ** of the default VFS is not implemented correctly, or not implemented at
4686 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4687 ** in the previous paragraphs.
4689 SQLITE_API int sqlite3_sleep(int);
4692 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4694 ** ^(If this global variable is made to point to a string which is
4695 ** the name of a folder (a.k.a. directory), then all temporary files
4696 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4697 ** will be placed in that directory.)^ ^If this variable
4698 ** is a NULL pointer, then SQLite performs a search for an appropriate
4699 ** temporary file directory.
4701 ** It is not safe to read or modify this variable in more than one
4702 ** thread at a time. It is not safe to read or modify this variable
4703 ** if a [database connection] is being used at the same time in a separate
4704 ** thread.
4705 ** It is intended that this variable be set once
4706 ** as part of process initialization and before any SQLite interface
4707 ** routines have been called and that this variable remain unchanged
4708 ** thereafter.
4710 ** ^The [temp_store_directory pragma] may modify this variable and cause
4711 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
4712 ** the [temp_store_directory pragma] always assumes that any string
4713 ** that this variable points to is held in memory obtained from
4714 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4715 ** using [sqlite3_free].
4716 ** Hence, if this variable is modified directly, either it should be
4717 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4718 ** or else the use of the [temp_store_directory pragma] should be avoided.
4720 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
4721 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
4722 ** features that require the use of temporary files may fail. Here is an
4723 ** example of how to do this using C++ with the Windows Runtime:
4725 ** <blockquote><pre>
4726 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
4727 ** &nbsp; TemporaryFolder->Path->Data();
4728 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
4729 ** memset(zPathBuf, 0, sizeof(zPathBuf));
4730 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
4731 ** &nbsp; NULL, NULL);
4732 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
4733 ** </pre></blockquote>
4735 SQLITE_API char *sqlite3_temp_directory;
4738 ** CAPI3REF: Name Of The Folder Holding Database Files
4740 ** ^(If this global variable is made to point to a string which is
4741 ** the name of a folder (a.k.a. directory), then all database files
4742 ** specified with a relative pathname and created or accessed by
4743 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
4744 ** to be relative to that directory.)^ ^If this variable is a NULL
4745 ** pointer, then SQLite assumes that all database files specified
4746 ** with a relative pathname are relative to the current directory
4747 ** for the process. Only the windows VFS makes use of this global
4748 ** variable; it is ignored by the unix VFS.
4750 ** Changing the value of this variable while a database connection is
4751 ** open can result in a corrupt database.
4753 ** It is not safe to read or modify this variable in more than one
4754 ** thread at a time. It is not safe to read or modify this variable
4755 ** if a [database connection] is being used at the same time in a separate
4756 ** thread.
4757 ** It is intended that this variable be set once
4758 ** as part of process initialization and before any SQLite interface
4759 ** routines have been called and that this variable remain unchanged
4760 ** thereafter.
4762 ** ^The [data_store_directory pragma] may modify this variable and cause
4763 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
4764 ** the [data_store_directory pragma] always assumes that any string
4765 ** that this variable points to is held in memory obtained from
4766 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4767 ** using [sqlite3_free].
4768 ** Hence, if this variable is modified directly, either it should be
4769 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4770 ** or else the use of the [data_store_directory pragma] should be avoided.
4772 SQLITE_API char *sqlite3_data_directory;
4775 ** CAPI3REF: Test For Auto-Commit Mode
4776 ** KEYWORDS: {autocommit mode}
4778 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4779 ** zero if the given database connection is or is not in autocommit mode,
4780 ** respectively. ^Autocommit mode is on by default.
4781 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4782 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4784 ** If certain kinds of errors occur on a statement within a multi-statement
4785 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4786 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4787 ** transaction might be rolled back automatically. The only way to
4788 ** find out whether SQLite automatically rolled back the transaction after
4789 ** an error is to use this function.
4791 ** If another thread changes the autocommit status of the database
4792 ** connection while this routine is running, then the return value
4793 ** is undefined.
4795 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4798 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4800 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4801 ** to which a [prepared statement] belongs. ^The [database connection]
4802 ** returned by sqlite3_db_handle is the same [database connection]
4803 ** that was the first argument
4804 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4805 ** create the statement in the first place.
4807 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4810 ** CAPI3REF: Return The Filename For A Database Connection
4812 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
4813 ** associated with database N of connection D. ^The main database file
4814 ** has the name "main". If there is no attached database N on the database
4815 ** connection D, or if database N is a temporary or in-memory database, then
4816 ** a NULL pointer is returned.
4818 ** ^The filename returned by this function is the output of the
4819 ** xFullPathname method of the [VFS]. ^In other words, the filename
4820 ** will be an absolute pathname, even if the filename used
4821 ** to open the database originally was a URI or relative pathname.
4823 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
4826 ** CAPI3REF: Determine if a database is read-only
4828 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
4829 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
4830 ** the name of a database on connection D.
4832 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
4835 ** CAPI3REF: Find the next prepared statement
4837 ** ^This interface returns a pointer to the next [prepared statement] after
4838 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
4839 ** then this interface returns a pointer to the first prepared statement
4840 ** associated with the database connection pDb. ^If no prepared statement
4841 ** satisfies the conditions of this routine, it returns NULL.
4843 ** The [database connection] pointer D in a call to
4844 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4845 ** connection and in particular must not be a NULL pointer.
4847 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4850 ** CAPI3REF: Commit And Rollback Notification Callbacks
4852 ** ^The sqlite3_commit_hook() interface registers a callback
4853 ** function to be invoked whenever a transaction is [COMMIT | committed].
4854 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4855 ** for the same database connection is overridden.
4856 ** ^The sqlite3_rollback_hook() interface registers a callback
4857 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4858 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4859 ** for the same database connection is overridden.
4860 ** ^The pArg argument is passed through to the callback.
4861 ** ^If the callback on a commit hook function returns non-zero,
4862 ** then the commit is converted into a rollback.
4864 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4865 ** return the P argument from the previous call of the same function
4866 ** on the same [database connection] D, or NULL for
4867 ** the first call for each function on D.
4869 ** The commit and rollback hook callbacks are not reentrant.
4870 ** The callback implementation must not do anything that will modify
4871 ** the database connection that invoked the callback. Any actions
4872 ** to modify the database connection must be deferred until after the
4873 ** completion of the [sqlite3_step()] call that triggered the commit
4874 ** or rollback hook in the first place.
4875 ** Note that running any other SQL statements, including SELECT statements,
4876 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
4877 ** the database connections for the meaning of "modify" in this paragraph.
4879 ** ^Registering a NULL function disables the callback.
4881 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4882 ** operation is allowed to continue normally. ^If the commit hook
4883 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4884 ** ^The rollback hook is invoked on a rollback that results from a commit
4885 ** hook returning non-zero, just as it would be with any other rollback.
4887 ** ^For the purposes of this API, a transaction is said to have been
4888 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4889 ** an error or constraint causes an implicit rollback to occur.
4890 ** ^The rollback callback is not invoked if a transaction is
4891 ** automatically rolled back because the database connection is closed.
4893 ** See also the [sqlite3_update_hook()] interface.
4895 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4896 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4899 ** CAPI3REF: Data Change Notification Callbacks
4901 ** ^The sqlite3_update_hook() interface registers a callback function
4902 ** with the [database connection] identified by the first argument
4903 ** to be invoked whenever a row is updated, inserted or deleted in
4904 ** a rowid table.
4905 ** ^Any callback set by a previous call to this function
4906 ** for the same database connection is overridden.
4908 ** ^The second argument is a pointer to the function to invoke when a
4909 ** row is updated, inserted or deleted in a rowid table.
4910 ** ^The first argument to the callback is a copy of the third argument
4911 ** to sqlite3_update_hook().
4912 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4913 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4914 ** to be invoked.
4915 ** ^The third and fourth arguments to the callback contain pointers to the
4916 ** database and table name containing the affected row.
4917 ** ^The final callback parameter is the [rowid] of the row.
4918 ** ^In the case of an update, this is the [rowid] after the update takes place.
4920 ** ^(The update hook is not invoked when internal system tables are
4921 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4922 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
4924 ** ^In the current implementation, the update hook
4925 ** is not invoked when duplication rows are deleted because of an
4926 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
4927 ** invoked when rows are deleted using the [truncate optimization].
4928 ** The exceptions defined in this paragraph might change in a future
4929 ** release of SQLite.
4931 ** The update hook implementation must not do anything that will modify
4932 ** the database connection that invoked the update hook. Any actions
4933 ** to modify the database connection must be deferred until after the
4934 ** completion of the [sqlite3_step()] call that triggered the update hook.
4935 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4936 ** database connections for the meaning of "modify" in this paragraph.
4938 ** ^The sqlite3_update_hook(D,C,P) function
4939 ** returns the P argument from the previous call
4940 ** on the same [database connection] D, or NULL for
4941 ** the first call on D.
4943 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4944 ** interfaces.
4946 SQLITE_API void *sqlite3_update_hook(
4947 sqlite3*,
4948 void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4949 void*
4953 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4955 ** ^(This routine enables or disables the sharing of the database cache
4956 ** and schema data structures between [database connection | connections]
4957 ** to the same database. Sharing is enabled if the argument is true
4958 ** and disabled if the argument is false.)^
4960 ** ^Cache sharing is enabled and disabled for an entire process.
4961 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4962 ** sharing was enabled or disabled for each thread separately.
4964 ** ^(The cache sharing mode set by this interface effects all subsequent
4965 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4966 ** Existing database connections continue use the sharing mode
4967 ** that was in effect at the time they were opened.)^
4969 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4970 ** successfully. An [error code] is returned otherwise.)^
4972 ** ^Shared cache is disabled by default. But this might change in
4973 ** future releases of SQLite. Applications that care about shared
4974 ** cache setting should set it explicitly.
4976 ** This interface is threadsafe on processors where writing a
4977 ** 32-bit integer is atomic.
4979 ** See Also: [SQLite Shared-Cache Mode]
4981 SQLITE_API int sqlite3_enable_shared_cache(int);
4984 ** CAPI3REF: Attempt To Free Heap Memory
4986 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4987 ** of heap memory by deallocating non-essential memory allocations
4988 ** held by the database library. Memory used to cache database
4989 ** pages to improve performance is an example of non-essential memory.
4990 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4991 ** which might be more or less than the amount requested.
4992 ** ^The sqlite3_release_memory() routine is a no-op returning zero
4993 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
4995 ** See also: [sqlite3_db_release_memory()]
4997 SQLITE_API int sqlite3_release_memory(int);
5000 ** CAPI3REF: Free Memory Used By A Database Connection
5002 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5003 ** memory as possible from database connection D. Unlike the
5004 ** [sqlite3_release_memory()] interface, this interface is in effect even
5005 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5006 ** omitted.
5008 ** See also: [sqlite3_release_memory()]
5010 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5013 ** CAPI3REF: Impose A Limit On Heap Size
5015 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5016 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5017 ** ^SQLite strives to keep heap memory utilization below the soft heap
5018 ** limit by reducing the number of pages held in the page cache
5019 ** as heap memory usages approaches the limit.
5020 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5021 ** below the limit, it will exceed the limit rather than generate
5022 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5023 ** is advisory only.
5025 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5026 ** the soft heap limit prior to the call, or negative in the case of an
5027 ** error. ^If the argument N is negative
5028 ** then no change is made to the soft heap limit. Hence, the current
5029 ** size of the soft heap limit can be determined by invoking
5030 ** sqlite3_soft_heap_limit64() with a negative argument.
5032 ** ^If the argument N is zero then the soft heap limit is disabled.
5034 ** ^(The soft heap limit is not enforced in the current implementation
5035 ** if one or more of following conditions are true:
5037 ** <ul>
5038 ** <li> The soft heap limit is set to zero.
5039 ** <li> Memory accounting is disabled using a combination of the
5040 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5041 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5042 ** <li> An alternative page cache implementation is specified using
5043 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5044 ** <li> The page cache allocates from its own memory pool supplied
5045 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5046 ** from the heap.
5047 ** </ul>)^
5049 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5050 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5051 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5052 ** the soft heap limit is enforced on every memory allocation. Without
5053 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5054 ** when memory is allocated by the page cache. Testing suggests that because
5055 ** the page cache is the predominate memory user in SQLite, most
5056 ** applications will achieve adequate soft heap limit enforcement without
5057 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5059 ** The circumstances under which SQLite will enforce the soft heap limit may
5060 ** changes in future releases of SQLite.
5062 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5065 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5066 ** DEPRECATED
5068 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5069 ** interface. This routine is provided for historical compatibility
5070 ** only. All new applications should use the
5071 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5073 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5077 ** CAPI3REF: Extract Metadata About A Column Of A Table
5079 ** ^This routine returns metadata about a specific column of a specific
5080 ** database table accessible using the [database connection] handle
5081 ** passed as the first function argument.
5083 ** ^The column is identified by the second, third and fourth parameters to
5084 ** this function. ^The second parameter is either the name of the database
5085 ** (i.e. "main", "temp", or an attached database) containing the specified
5086 ** table or NULL. ^If it is NULL, then all attached databases are searched
5087 ** for the table using the same algorithm used by the database engine to
5088 ** resolve unqualified table references.
5090 ** ^The third and fourth parameters to this function are the table and column
5091 ** name of the desired column, respectively. Neither of these parameters
5092 ** may be NULL.
5094 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5095 ** and subsequent parameters to this function. ^Any of these arguments may be
5096 ** NULL, in which case the corresponding element of metadata is omitted.
5098 ** ^(<blockquote>
5099 ** <table border="1">
5100 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5102 ** <tr><td> 5th <td> const char* <td> Data type
5103 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5104 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5105 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5106 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5107 ** </table>
5108 ** </blockquote>)^
5110 ** ^The memory pointed to by the character pointers returned for the
5111 ** declaration type and collation sequence is valid only until the next
5112 ** call to any SQLite API function.
5114 ** ^If the specified table is actually a view, an [error code] is returned.
5116 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5117 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5118 ** parameters are set for the explicitly declared column. ^(If there is no
5119 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5120 ** parameters are set as follows:
5122 ** <pre>
5123 ** data type: "INTEGER"
5124 ** collation sequence: "BINARY"
5125 ** not null: 0
5126 ** primary key: 1
5127 ** auto increment: 0
5128 ** </pre>)^
5130 ** ^(This function may load one or more schemas from database files. If an
5131 ** error occurs during this process, or if the requested table or column
5132 ** cannot be found, an [error code] is returned and an error message left
5133 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5135 ** ^This API is only available if the library was compiled with the
5136 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5138 SQLITE_API int sqlite3_table_column_metadata(
5139 sqlite3 *db, /* Connection handle */
5140 const char *zDbName, /* Database name or NULL */
5141 const char *zTableName, /* Table name */
5142 const char *zColumnName, /* Column name */
5143 char const **pzDataType, /* OUTPUT: Declared data type */
5144 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5145 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5146 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5147 int *pAutoinc /* OUTPUT: True if column is auto-increment */
5151 ** CAPI3REF: Load An Extension
5153 ** ^This interface loads an SQLite extension library from the named file.
5155 ** ^The sqlite3_load_extension() interface attempts to load an
5156 ** [SQLite extension] library contained in the file zFile. If
5157 ** the file cannot be loaded directly, attempts are made to load
5158 ** with various operating-system specific extensions added.
5159 ** So for example, if "samplelib" cannot be loaded, then names like
5160 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5161 ** be tried also.
5163 ** ^The entry point is zProc.
5164 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5165 ** entry point name on its own. It first tries "sqlite3_extension_init".
5166 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5167 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5168 ** characters in the filename from the last "/" to the first following
5169 ** "." and omitting any initial "lib".)^
5170 ** ^The sqlite3_load_extension() interface returns
5171 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5172 ** ^If an error occurs and pzErrMsg is not 0, then the
5173 ** [sqlite3_load_extension()] interface shall attempt to
5174 ** fill *pzErrMsg with error message text stored in memory
5175 ** obtained from [sqlite3_malloc()]. The calling function
5176 ** should free this memory by calling [sqlite3_free()].
5178 ** ^Extension loading must be enabled using
5179 ** [sqlite3_enable_load_extension()] prior to calling this API,
5180 ** otherwise an error will be returned.
5182 ** See also the [load_extension() SQL function].
5184 SQLITE_API int sqlite3_load_extension(
5185 sqlite3 *db, /* Load the extension into this database connection */
5186 const char *zFile, /* Name of the shared library containing extension */
5187 const char *zProc, /* Entry point. Derived from zFile if 0 */
5188 char **pzErrMsg /* Put error message here if not 0 */
5192 ** CAPI3REF: Enable Or Disable Extension Loading
5194 ** ^So as not to open security holes in older applications that are
5195 ** unprepared to deal with [extension loading], and as a means of disabling
5196 ** [extension loading] while evaluating user-entered SQL, the following API
5197 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5199 ** ^Extension loading is off by default.
5200 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5201 ** to turn extension loading on and call it with onoff==0 to turn
5202 ** it back off again.
5204 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5207 ** CAPI3REF: Automatically Load Statically Linked Extensions
5209 ** ^This interface causes the xEntryPoint() function to be invoked for
5210 ** each new [database connection] that is created. The idea here is that
5211 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5212 ** that is to be automatically loaded into all new database connections.
5214 ** ^(Even though the function prototype shows that xEntryPoint() takes
5215 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5216 ** arguments and expects and integer result as if the signature of the
5217 ** entry point where as follows:
5219 ** <blockquote><pre>
5220 ** &nbsp; int xEntryPoint(
5221 ** &nbsp; sqlite3 *db,
5222 ** &nbsp; const char **pzErrMsg,
5223 ** &nbsp; const struct sqlite3_api_routines *pThunk
5224 ** &nbsp; );
5225 ** </pre></blockquote>)^
5227 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5228 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5229 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5230 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5231 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5232 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5233 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5235 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5236 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5237 ** will be called more than once for each database connection that is opened.
5239 ** See also: [sqlite3_reset_auto_extension()]
5240 ** and [sqlite3_cancel_auto_extension()]
5242 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5245 ** CAPI3REF: Cancel Automatic Extension Loading
5247 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5248 ** initialization routine X that was registered using a prior call to
5249 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
5250 ** routine returns 1 if initialization routine X was successfully
5251 ** unregistered and it returns 0 if X was not on the list of initialization
5252 ** routines.
5254 SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5257 ** CAPI3REF: Reset Automatic Extension Loading
5259 ** ^This interface disables all automatic extensions previously
5260 ** registered using [sqlite3_auto_extension()].
5262 SQLITE_API void sqlite3_reset_auto_extension(void);
5265 ** The interface to the virtual-table mechanism is currently considered
5266 ** to be experimental. The interface might change in incompatible ways.
5267 ** If this is a problem for you, do not use the interface at this time.
5269 ** When the virtual-table mechanism stabilizes, we will declare the
5270 ** interface fixed, support it indefinitely, and remove this comment.
5274 ** Structures used by the virtual table interface
5276 typedef struct sqlite3_vtab sqlite3_vtab;
5277 typedef struct sqlite3_index_info sqlite3_index_info;
5278 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5279 typedef struct sqlite3_module sqlite3_module;
5282 ** CAPI3REF: Virtual Table Object
5283 ** KEYWORDS: sqlite3_module {virtual table module}
5285 ** This structure, sometimes called a "virtual table module",
5286 ** defines the implementation of a [virtual tables].
5287 ** This structure consists mostly of methods for the module.
5289 ** ^A virtual table module is created by filling in a persistent
5290 ** instance of this structure and passing a pointer to that instance
5291 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5292 ** ^The registration remains valid until it is replaced by a different
5293 ** module or until the [database connection] closes. The content
5294 ** of this structure must not change while it is registered with
5295 ** any database connection.
5297 struct sqlite3_module {
5298 int iVersion;
5299 int (*xCreate)(sqlite3*, void *pAux,
5300 int argc, const char *const*argv,
5301 sqlite3_vtab **ppVTab, char**);
5302 int (*xConnect)(sqlite3*, void *pAux,
5303 int argc, const char *const*argv,
5304 sqlite3_vtab **ppVTab, char**);
5305 int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5306 int (*xDisconnect)(sqlite3_vtab *pVTab);
5307 int (*xDestroy)(sqlite3_vtab *pVTab);
5308 int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5309 int (*xClose)(sqlite3_vtab_cursor*);
5310 int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5311 int argc, sqlite3_value **argv);
5312 int (*xNext)(sqlite3_vtab_cursor*);
5313 int (*xEof)(sqlite3_vtab_cursor*);
5314 int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5315 int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5316 int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5317 int (*xBegin)(sqlite3_vtab *pVTab);
5318 int (*xSync)(sqlite3_vtab *pVTab);
5319 int (*xCommit)(sqlite3_vtab *pVTab);
5320 int (*xRollback)(sqlite3_vtab *pVTab);
5321 int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5322 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5323 void **ppArg);
5324 int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5325 /* The methods above are in version 1 of the sqlite_module object. Those
5326 ** below are for version 2 and greater. */
5327 int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5328 int (*xRelease)(sqlite3_vtab *pVTab, int);
5329 int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5333 ** CAPI3REF: Virtual Table Indexing Information
5334 ** KEYWORDS: sqlite3_index_info
5336 ** The sqlite3_index_info structure and its substructures is used as part
5337 ** of the [virtual table] interface to
5338 ** pass information into and receive the reply from the [xBestIndex]
5339 ** method of a [virtual table module]. The fields under **Inputs** are the
5340 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5341 ** results into the **Outputs** fields.
5343 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5345 ** <blockquote>column OP expr</blockquote>
5347 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5348 ** stored in aConstraint[].op using one of the
5349 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5350 ** ^(The index of the column is stored in
5351 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5352 ** expr on the right-hand side can be evaluated (and thus the constraint
5353 ** is usable) and false if it cannot.)^
5355 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5356 ** and makes other simplifications to the WHERE clause in an attempt to
5357 ** get as many WHERE clause terms into the form shown above as possible.
5358 ** ^The aConstraint[] array only reports WHERE clause terms that are
5359 ** relevant to the particular virtual table being queried.
5361 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5362 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5364 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5365 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5366 ** the right-hand side of the corresponding aConstraint[] is evaluated
5367 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5368 ** is true, then the constraint is assumed to be fully handled by the
5369 ** virtual table and is not checked again by SQLite.)^
5371 ** ^The idxNum and idxPtr values are recorded and passed into the
5372 ** [xFilter] method.
5373 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5374 ** needToFreeIdxPtr is true.
5376 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5377 ** the correct order to satisfy the ORDER BY clause so that no separate
5378 ** sorting step is required.
5380 ** ^The estimatedCost value is an estimate of the cost of a particular
5381 ** strategy. A cost of N indicates that the cost of the strategy is similar
5382 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
5383 ** indicates that the expense of the operation is similar to that of a
5384 ** binary search on a unique indexed field of an SQLite table with N rows.
5386 ** ^The estimatedRows value is an estimate of the number of rows that
5387 ** will be returned by the strategy.
5389 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5390 ** structure for SQLite version 3.8.2. If a virtual table extension is
5391 ** used with an SQLite version earlier than 3.8.2, the results of attempting
5392 ** to read or write the estimatedRows field are undefined (but are likely
5393 ** to included crashing the application). The estimatedRows field should
5394 ** therefore only be used if [sqlite3_libversion_number()] returns a
5395 ** value greater than or equal to 3008002.
5397 struct sqlite3_index_info {
5398 /* Inputs */
5399 int nConstraint; /* Number of entries in aConstraint */
5400 struct sqlite3_index_constraint {
5401 int iColumn; /* Column on left-hand side of constraint */
5402 unsigned char op; /* Constraint operator */
5403 unsigned char usable; /* True if this constraint is usable */
5404 int iTermOffset; /* Used internally - xBestIndex should ignore */
5405 } *aConstraint; /* Table of WHERE clause constraints */
5406 int nOrderBy; /* Number of terms in the ORDER BY clause */
5407 struct sqlite3_index_orderby {
5408 int iColumn; /* Column number */
5409 unsigned char desc; /* True for DESC. False for ASC. */
5410 } *aOrderBy; /* The ORDER BY clause */
5411 /* Outputs */
5412 struct sqlite3_index_constraint_usage {
5413 int argvIndex; /* if >0, constraint is part of argv to xFilter */
5414 unsigned char omit; /* Do not code a test for this constraint */
5415 } *aConstraintUsage;
5416 int idxNum; /* Number used to identify the index */
5417 char *idxStr; /* String, possibly obtained from sqlite3_malloc */
5418 int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
5419 int orderByConsumed; /* True if output is already ordered */
5420 double estimatedCost; /* Estimated cost of using this index */
5421 /* Fields below are only available in SQLite 3.8.2 and later */
5422 sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
5426 ** CAPI3REF: Virtual Table Constraint Operator Codes
5428 ** These macros defined the allowed values for the
5429 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
5430 ** an operator that is part of a constraint term in the wHERE clause of
5431 ** a query that uses a [virtual table].
5433 #define SQLITE_INDEX_CONSTRAINT_EQ 2
5434 #define SQLITE_INDEX_CONSTRAINT_GT 4
5435 #define SQLITE_INDEX_CONSTRAINT_LE 8
5436 #define SQLITE_INDEX_CONSTRAINT_LT 16
5437 #define SQLITE_INDEX_CONSTRAINT_GE 32
5438 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5441 ** CAPI3REF: Register A Virtual Table Implementation
5443 ** ^These routines are used to register a new [virtual table module] name.
5444 ** ^Module names must be registered before
5445 ** creating a new [virtual table] using the module and before using a
5446 ** preexisting [virtual table] for the module.
5448 ** ^The module name is registered on the [database connection] specified
5449 ** by the first parameter. ^The name of the module is given by the
5450 ** second parameter. ^The third parameter is a pointer to
5451 ** the implementation of the [virtual table module]. ^The fourth
5452 ** parameter is an arbitrary client data pointer that is passed through
5453 ** into the [xCreate] and [xConnect] methods of the virtual table module
5454 ** when a new virtual table is be being created or reinitialized.
5456 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5457 ** is a pointer to a destructor for the pClientData. ^SQLite will
5458 ** invoke the destructor function (if it is not NULL) when SQLite
5459 ** no longer needs the pClientData pointer. ^The destructor will also
5460 ** be invoked if the call to sqlite3_create_module_v2() fails.
5461 ** ^The sqlite3_create_module()
5462 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5463 ** destructor.
5465 SQLITE_API int sqlite3_create_module(
5466 sqlite3 *db, /* SQLite connection to register module with */
5467 const char *zName, /* Name of the module */
5468 const sqlite3_module *p, /* Methods for the module */
5469 void *pClientData /* Client data for xCreate/xConnect */
5471 SQLITE_API int sqlite3_create_module_v2(
5472 sqlite3 *db, /* SQLite connection to register module with */
5473 const char *zName, /* Name of the module */
5474 const sqlite3_module *p, /* Methods for the module */
5475 void *pClientData, /* Client data for xCreate/xConnect */
5476 void(*xDestroy)(void*) /* Module destructor function */
5480 ** CAPI3REF: Virtual Table Instance Object
5481 ** KEYWORDS: sqlite3_vtab
5483 ** Every [virtual table module] implementation uses a subclass
5484 ** of this object to describe a particular instance
5485 ** of the [virtual table]. Each subclass will
5486 ** be tailored to the specific needs of the module implementation.
5487 ** The purpose of this superclass is to define certain fields that are
5488 ** common to all module implementations.
5490 ** ^Virtual tables methods can set an error message by assigning a
5491 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
5492 ** take care that any prior string is freed by a call to [sqlite3_free()]
5493 ** prior to assigning a new string to zErrMsg. ^After the error message
5494 ** is delivered up to the client application, the string will be automatically
5495 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5497 struct sqlite3_vtab {
5498 const sqlite3_module *pModule; /* The module for this virtual table */
5499 int nRef; /* NO LONGER USED */
5500 char *zErrMsg; /* Error message from sqlite3_mprintf() */
5501 /* Virtual table implementations will typically add additional fields */
5505 ** CAPI3REF: Virtual Table Cursor Object
5506 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5508 ** Every [virtual table module] implementation uses a subclass of the
5509 ** following structure to describe cursors that point into the
5510 ** [virtual table] and are used
5511 ** to loop through the virtual table. Cursors are created using the
5512 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5513 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
5514 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5515 ** of the module. Each module implementation will define
5516 ** the content of a cursor structure to suit its own needs.
5518 ** This superclass exists in order to define fields of the cursor that
5519 ** are common to all implementations.
5521 struct sqlite3_vtab_cursor {
5522 sqlite3_vtab *pVtab; /* Virtual table of this cursor */
5523 /* Virtual table implementations will typically add additional fields */
5527 ** CAPI3REF: Declare The Schema Of A Virtual Table
5529 ** ^The [xCreate] and [xConnect] methods of a
5530 ** [virtual table module] call this interface
5531 ** to declare the format (the names and datatypes of the columns) of
5532 ** the virtual tables they implement.
5534 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5537 ** CAPI3REF: Overload A Function For A Virtual Table
5539 ** ^(Virtual tables can provide alternative implementations of functions
5540 ** using the [xFindFunction] method of the [virtual table module].
5541 ** But global versions of those functions
5542 ** must exist in order to be overloaded.)^
5544 ** ^(This API makes sure a global version of a function with a particular
5545 ** name and number of parameters exists. If no such function exists
5546 ** before this API is called, a new function is created.)^ ^The implementation
5547 ** of the new function always causes an exception to be thrown. So
5548 ** the new function is not good for anything by itself. Its only
5549 ** purpose is to be a placeholder function that can be overloaded
5550 ** by a [virtual table].
5552 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5555 ** The interface to the virtual-table mechanism defined above (back up
5556 ** to a comment remarkably similar to this one) is currently considered
5557 ** to be experimental. The interface might change in incompatible ways.
5558 ** If this is a problem for you, do not use the interface at this time.
5560 ** When the virtual-table mechanism stabilizes, we will declare the
5561 ** interface fixed, support it indefinitely, and remove this comment.
5565 ** CAPI3REF: A Handle To An Open BLOB
5566 ** KEYWORDS: {BLOB handle} {BLOB handles}
5568 ** An instance of this object represents an open BLOB on which
5569 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5570 ** ^Objects of this type are created by [sqlite3_blob_open()]
5571 ** and destroyed by [sqlite3_blob_close()].
5572 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5573 ** can be used to read or write small subsections of the BLOB.
5574 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5576 typedef struct sqlite3_blob sqlite3_blob;
5579 ** CAPI3REF: Open A BLOB For Incremental I/O
5581 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5582 ** in row iRow, column zColumn, table zTable in database zDb;
5583 ** in other words, the same BLOB that would be selected by:
5585 ** <pre>
5586 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5587 ** </pre>)^
5589 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5590 ** and write access. ^If it is zero, the BLOB is opened for read access.
5591 ** ^It is not possible to open a column that is part of an index or primary
5592 ** key for writing. ^If [foreign key constraints] are enabled, it is
5593 ** not possible to open a column that is part of a [child key] for writing.
5595 ** ^Note that the database name is not the filename that contains
5596 ** the database but rather the symbolic name of the database that
5597 ** appears after the AS keyword when the database is connected using [ATTACH].
5598 ** ^For the main database file, the database name is "main".
5599 ** ^For TEMP tables, the database name is "temp".
5601 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5602 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5603 ** to be a null pointer.)^
5604 ** ^This function sets the [database connection] error code and message
5605 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5606 ** functions. ^Note that the *ppBlob variable is always initialized in a
5607 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5608 ** regardless of the success or failure of this routine.
5610 ** ^(If the row that a BLOB handle points to is modified by an
5611 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5612 ** then the BLOB handle is marked as "expired".
5613 ** This is true if any column of the row is changed, even a column
5614 ** other than the one the BLOB handle is open on.)^
5615 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5616 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5617 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5618 ** rolled back by the expiration of the BLOB. Such changes will eventually
5619 ** commit if the transaction continues to completion.)^
5621 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5622 ** the opened blob. ^The size of a blob may not be changed by this
5623 ** interface. Use the [UPDATE] SQL command to change the size of a
5624 ** blob.
5626 ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
5627 ** table. Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
5629 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5630 ** and the built-in [zeroblob] SQL function can be used, if desired,
5631 ** to create an empty, zero-filled blob in which to read or write using
5632 ** this interface.
5634 ** To avoid a resource leak, every open [BLOB handle] should eventually
5635 ** be released by a call to [sqlite3_blob_close()].
5637 SQLITE_API int sqlite3_blob_open(
5638 sqlite3*,
5639 const char *zDb,
5640 const char *zTable,
5641 const char *zColumn,
5642 sqlite3_int64 iRow,
5643 int flags,
5644 sqlite3_blob **ppBlob
5648 ** CAPI3REF: Move a BLOB Handle to a New Row
5650 ** ^This function is used to move an existing blob handle so that it points
5651 ** to a different row of the same database table. ^The new row is identified
5652 ** by the rowid value passed as the second argument. Only the row can be
5653 ** changed. ^The database, table and column on which the blob handle is open
5654 ** remain the same. Moving an existing blob handle to a new row can be
5655 ** faster than closing the existing handle and opening a new one.
5657 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5658 ** it must exist and there must be either a blob or text value stored in
5659 ** the nominated column.)^ ^If the new row is not present in the table, or if
5660 ** it does not contain a blob or text value, or if another error occurs, an
5661 ** SQLite error code is returned and the blob handle is considered aborted.
5662 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5663 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5664 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5665 ** always returns zero.
5667 ** ^This function sets the database handle error code and message.
5669 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5672 ** CAPI3REF: Close A BLOB Handle
5674 ** ^Closes an open [BLOB handle].
5676 ** ^Closing a BLOB shall cause the current transaction to commit
5677 ** if there are no other BLOBs, no pending prepared statements, and the
5678 ** database connection is in [autocommit mode].
5679 ** ^If any writes were made to the BLOB, they might be held in cache
5680 ** until the close operation if they will fit.
5682 ** ^(Closing the BLOB often forces the changes
5683 ** out to disk and so if any I/O errors occur, they will likely occur
5684 ** at the time when the BLOB is closed. Any errors that occur during
5685 ** closing are reported as a non-zero return value.)^
5687 ** ^(The BLOB is closed unconditionally. Even if this routine returns
5688 ** an error code, the BLOB is still closed.)^
5690 ** ^Calling this routine with a null pointer (such as would be returned
5691 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5693 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5696 ** CAPI3REF: Return The Size Of An Open BLOB
5698 ** ^Returns the size in bytes of the BLOB accessible via the
5699 ** successfully opened [BLOB handle] in its only argument. ^The
5700 ** incremental blob I/O routines can only read or overwriting existing
5701 ** blob content; they cannot change the size of a blob.
5703 ** This routine only works on a [BLOB handle] which has been created
5704 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5705 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5706 ** to this routine results in undefined and probably undesirable behavior.
5708 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5711 ** CAPI3REF: Read Data From A BLOB Incrementally
5713 ** ^(This function is used to read data from an open [BLOB handle] into a
5714 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5715 ** from the open BLOB, starting at offset iOffset.)^
5717 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5718 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
5719 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5720 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5721 ** can be determined using the [sqlite3_blob_bytes()] interface.
5723 ** ^An attempt to read from an expired [BLOB handle] fails with an
5724 ** error code of [SQLITE_ABORT].
5726 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5727 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5729 ** This routine only works on a [BLOB handle] which has been created
5730 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5731 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5732 ** to this routine results in undefined and probably undesirable behavior.
5734 ** See also: [sqlite3_blob_write()].
5736 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5739 ** CAPI3REF: Write Data Into A BLOB Incrementally
5741 ** ^This function is used to write data into an open [BLOB handle] from a
5742 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5743 ** into the open BLOB, starting at offset iOffset.
5745 ** ^If the [BLOB handle] passed as the first argument was not opened for
5746 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5747 ** this function returns [SQLITE_READONLY].
5749 ** ^This function may only modify the contents of the BLOB; it is
5750 ** not possible to increase the size of a BLOB using this API.
5751 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5752 ** [SQLITE_ERROR] is returned and no data is written. ^If N is
5753 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5754 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5755 ** can be determined using the [sqlite3_blob_bytes()] interface.
5757 ** ^An attempt to write to an expired [BLOB handle] fails with an
5758 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
5759 ** before the [BLOB handle] expired are not rolled back by the
5760 ** expiration of the handle, though of course those changes might
5761 ** have been overwritten by the statement that expired the BLOB handle
5762 ** or by other independent statements.
5764 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5765 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5767 ** This routine only works on a [BLOB handle] which has been created
5768 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5769 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
5770 ** to this routine results in undefined and probably undesirable behavior.
5772 ** See also: [sqlite3_blob_read()].
5774 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5777 ** CAPI3REF: Virtual File System Objects
5779 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5780 ** that SQLite uses to interact
5781 ** with the underlying operating system. Most SQLite builds come with a
5782 ** single default VFS that is appropriate for the host computer.
5783 ** New VFSes can be registered and existing VFSes can be unregistered.
5784 ** The following interfaces are provided.
5786 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5787 ** ^Names are case sensitive.
5788 ** ^Names are zero-terminated UTF-8 strings.
5789 ** ^If there is no match, a NULL pointer is returned.
5790 ** ^If zVfsName is NULL then the default VFS is returned.
5792 ** ^New VFSes are registered with sqlite3_vfs_register().
5793 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5794 ** ^The same VFS can be registered multiple times without injury.
5795 ** ^To make an existing VFS into the default VFS, register it again
5796 ** with the makeDflt flag set. If two different VFSes with the
5797 ** same name are registered, the behavior is undefined. If a
5798 ** VFS is registered with a name that is NULL or an empty string,
5799 ** then the behavior is undefined.
5801 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5802 ** ^(If the default VFS is unregistered, another VFS is chosen as
5803 ** the default. The choice for the new VFS is arbitrary.)^
5805 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5806 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5807 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5810 ** CAPI3REF: Mutexes
5812 ** The SQLite core uses these routines for thread
5813 ** synchronization. Though they are intended for internal
5814 ** use by SQLite, code that links against SQLite is
5815 ** permitted to use any of these routines.
5817 ** The SQLite source code contains multiple implementations
5818 ** of these mutex routines. An appropriate implementation
5819 ** is selected automatically at compile-time. ^(The following
5820 ** implementations are available in the SQLite core:
5822 ** <ul>
5823 ** <li> SQLITE_MUTEX_PTHREADS
5824 ** <li> SQLITE_MUTEX_W32
5825 ** <li> SQLITE_MUTEX_NOOP
5826 ** </ul>)^
5828 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5829 ** that does no real locking and is appropriate for use in
5830 ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
5831 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
5832 ** and Windows.
5834 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5835 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5836 ** implementation is included with the library. In this case the
5837 ** application must supply a custom mutex implementation using the
5838 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5839 ** before calling sqlite3_initialize() or any other public sqlite3_
5840 ** function that calls sqlite3_initialize().)^
5842 ** ^The sqlite3_mutex_alloc() routine allocates a new
5843 ** mutex and returns a pointer to it. ^If it returns NULL
5844 ** that means that a mutex could not be allocated. ^SQLite
5845 ** will unwind its stack and return an error. ^(The argument
5846 ** to sqlite3_mutex_alloc() is one of these integer constants:
5848 ** <ul>
5849 ** <li> SQLITE_MUTEX_FAST
5850 ** <li> SQLITE_MUTEX_RECURSIVE
5851 ** <li> SQLITE_MUTEX_STATIC_MASTER
5852 ** <li> SQLITE_MUTEX_STATIC_MEM
5853 ** <li> SQLITE_MUTEX_STATIC_MEM2
5854 ** <li> SQLITE_MUTEX_STATIC_PRNG
5855 ** <li> SQLITE_MUTEX_STATIC_LRU
5856 ** <li> SQLITE_MUTEX_STATIC_LRU2
5857 ** </ul>)^
5859 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5860 ** cause sqlite3_mutex_alloc() to create
5861 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5862 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5863 ** The mutex implementation does not need to make a distinction
5864 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5865 ** not want to. ^SQLite will only request a recursive mutex in
5866 ** cases where it really needs one. ^If a faster non-recursive mutex
5867 ** implementation is available on the host platform, the mutex subsystem
5868 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5870 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5871 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5872 ** a pointer to a static preexisting mutex. ^Six static mutexes are
5873 ** used by the current version of SQLite. Future versions of SQLite
5874 ** may add additional static mutexes. Static mutexes are for internal
5875 ** use by SQLite only. Applications that use SQLite mutexes should
5876 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5877 ** SQLITE_MUTEX_RECURSIVE.
5879 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5880 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5881 ** returns a different mutex on every call. ^But for the static
5882 ** mutex types, the same mutex is returned on every call that has
5883 ** the same type number.
5885 ** ^The sqlite3_mutex_free() routine deallocates a previously
5886 ** allocated dynamic mutex. ^SQLite is careful to deallocate every
5887 ** dynamic mutex that it allocates. The dynamic mutexes must not be in
5888 ** use when they are deallocated. Attempting to deallocate a static
5889 ** mutex results in undefined behavior. ^SQLite never deallocates
5890 ** a static mutex.
5892 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5893 ** to enter a mutex. ^If another thread is already within the mutex,
5894 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5895 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5896 ** upon successful entry. ^(Mutexes created using
5897 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5898 ** In such cases the,
5899 ** mutex must be exited an equal number of times before another thread
5900 ** can enter.)^ ^(If the same thread tries to enter any other
5901 ** kind of mutex more than once, the behavior is undefined.
5902 ** SQLite will never exhibit
5903 ** such behavior in its own use of mutexes.)^
5905 ** ^(Some systems (for example, Windows 95) do not support the operation
5906 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
5907 ** will always return SQLITE_BUSY. The SQLite core only ever uses
5908 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5910 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5911 ** previously entered by the same thread. ^(The behavior
5912 ** is undefined if the mutex is not currently entered by the
5913 ** calling thread or is not currently allocated. SQLite will
5914 ** never do either.)^
5916 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5917 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5918 ** behave as no-ops.
5920 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5922 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5923 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5924 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5925 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5926 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5929 ** CAPI3REF: Mutex Methods Object
5931 ** An instance of this structure defines the low-level routines
5932 ** used to allocate and use mutexes.
5934 ** Usually, the default mutex implementations provided by SQLite are
5935 ** sufficient, however the user has the option of substituting a custom
5936 ** implementation for specialized deployments or systems for which SQLite
5937 ** does not provide a suitable implementation. In this case, the user
5938 ** creates and populates an instance of this structure to pass
5939 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5940 ** Additionally, an instance of this structure can be used as an
5941 ** output variable when querying the system for the current mutex
5942 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5944 ** ^The xMutexInit method defined by this structure is invoked as
5945 ** part of system initialization by the sqlite3_initialize() function.
5946 ** ^The xMutexInit routine is called by SQLite exactly once for each
5947 ** effective call to [sqlite3_initialize()].
5949 ** ^The xMutexEnd method defined by this structure is invoked as
5950 ** part of system shutdown by the sqlite3_shutdown() function. The
5951 ** implementation of this method is expected to release all outstanding
5952 ** resources obtained by the mutex methods implementation, especially
5953 ** those obtained by the xMutexInit method. ^The xMutexEnd()
5954 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5956 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5957 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5958 ** xMutexNotheld) implement the following interfaces (respectively):
5960 ** <ul>
5961 ** <li> [sqlite3_mutex_alloc()] </li>
5962 ** <li> [sqlite3_mutex_free()] </li>
5963 ** <li> [sqlite3_mutex_enter()] </li>
5964 ** <li> [sqlite3_mutex_try()] </li>
5965 ** <li> [sqlite3_mutex_leave()] </li>
5966 ** <li> [sqlite3_mutex_held()] </li>
5967 ** <li> [sqlite3_mutex_notheld()] </li>
5968 ** </ul>)^
5970 ** The only difference is that the public sqlite3_XXX functions enumerated
5971 ** above silently ignore any invocations that pass a NULL pointer instead
5972 ** of a valid mutex handle. The implementations of the methods defined
5973 ** by this structure are not required to handle this case, the results
5974 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5975 ** (i.e. it is acceptable to provide an implementation that segfaults if
5976 ** it is passed a NULL pointer).
5978 ** The xMutexInit() method must be threadsafe. ^It must be harmless to
5979 ** invoke xMutexInit() multiple times within the same process and without
5980 ** intervening calls to xMutexEnd(). Second and subsequent calls to
5981 ** xMutexInit() must be no-ops.
5983 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5984 ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
5985 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
5986 ** memory allocation for a fast or recursive mutex.
5988 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5989 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5990 ** If xMutexInit fails in any way, it is expected to clean up after itself
5991 ** prior to returning.
5993 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5994 struct sqlite3_mutex_methods {
5995 int (*xMutexInit)(void);
5996 int (*xMutexEnd)(void);
5997 sqlite3_mutex *(*xMutexAlloc)(int);
5998 void (*xMutexFree)(sqlite3_mutex *);
5999 void (*xMutexEnter)(sqlite3_mutex *);
6000 int (*xMutexTry)(sqlite3_mutex *);
6001 void (*xMutexLeave)(sqlite3_mutex *);
6002 int (*xMutexHeld)(sqlite3_mutex *);
6003 int (*xMutexNotheld)(sqlite3_mutex *);
6007 ** CAPI3REF: Mutex Verification Routines
6009 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6010 ** are intended for use inside assert() statements. ^The SQLite core
6011 ** never uses these routines except inside an assert() and applications
6012 ** are advised to follow the lead of the core. ^The SQLite core only
6013 ** provides implementations for these routines when it is compiled
6014 ** with the SQLITE_DEBUG flag. ^External mutex implementations
6015 ** are only required to provide these routines if SQLITE_DEBUG is
6016 ** defined and if NDEBUG is not defined.
6018 ** ^These routines should return true if the mutex in their argument
6019 ** is held or not held, respectively, by the calling thread.
6021 ** ^The implementation is not required to provide versions of these
6022 ** routines that actually work. If the implementation does not provide working
6023 ** versions of these routines, it should at least provide stubs that always
6024 ** return true so that one does not get spurious assertion failures.
6026 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6027 ** the routine should return 1. This seems counter-intuitive since
6028 ** clearly the mutex cannot be held if it does not exist. But
6029 ** the reason the mutex does not exist is because the build is not
6030 ** using mutexes. And we do not want the assert() containing the
6031 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6032 ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
6033 ** interface should also return 1 when given a NULL pointer.
6035 #ifndef NDEBUG
6036 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6037 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6038 #endif
6041 ** CAPI3REF: Mutex Types
6043 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6044 ** which is one of these integer constants.
6046 ** The set of static mutexes may change from one SQLite release to the
6047 ** next. Applications that override the built-in mutex logic must be
6048 ** prepared to accommodate additional static mutexes.
6050 #define SQLITE_MUTEX_FAST 0
6051 #define SQLITE_MUTEX_RECURSIVE 1
6052 #define SQLITE_MUTEX_STATIC_MASTER 2
6053 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6054 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6055 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6056 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6057 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6058 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6059 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6062 ** CAPI3REF: Retrieve the mutex for a database connection
6064 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6065 ** serializes access to the [database connection] given in the argument
6066 ** when the [threading mode] is Serialized.
6067 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6068 ** routine returns a NULL pointer.
6070 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6073 ** CAPI3REF: Low-Level Control Of Database Files
6075 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6076 ** xFileControl method for the [sqlite3_io_methods] object associated
6077 ** with a particular database identified by the second argument. ^The
6078 ** name of the database is "main" for the main database or "temp" for the
6079 ** TEMP database, or the name that appears after the AS keyword for
6080 ** databases that are added using the [ATTACH] SQL command.
6081 ** ^A NULL pointer can be used in place of "main" to refer to the
6082 ** main database file.
6083 ** ^The third and fourth parameters to this routine
6084 ** are passed directly through to the second and third parameters of
6085 ** the xFileControl method. ^The return value of the xFileControl
6086 ** method becomes the return value of this routine.
6088 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6089 ** a pointer to the underlying [sqlite3_file] object to be written into
6090 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6091 ** case is a short-circuit path which does not actually invoke the
6092 ** underlying sqlite3_io_methods.xFileControl method.
6094 ** ^If the second parameter (zDbName) does not match the name of any
6095 ** open database file, then SQLITE_ERROR is returned. ^This error
6096 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6097 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6098 ** also return SQLITE_ERROR. There is no way to distinguish between
6099 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6100 ** xFileControl method.
6102 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6104 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6107 ** CAPI3REF: Testing Interface
6109 ** ^The sqlite3_test_control() interface is used to read out internal
6110 ** state of SQLite and to inject faults into SQLite for testing
6111 ** purposes. ^The first parameter is an operation code that determines
6112 ** the number, meaning, and operation of all subsequent parameters.
6114 ** This interface is not for use by applications. It exists solely
6115 ** for verifying the correct operation of the SQLite library. Depending
6116 ** on how the SQLite library is compiled, this interface might not exist.
6118 ** The details of the operation codes, their meanings, the parameters
6119 ** they take, and what they do are all subject to change without notice.
6120 ** Unlike most of the SQLite API, this function is not guaranteed to
6121 ** operate consistently from one release to the next.
6123 SQLITE_API int sqlite3_test_control(int op, ...);
6126 ** CAPI3REF: Testing Interface Operation Codes
6128 ** These constants are the valid operation code parameters used
6129 ** as the first argument to [sqlite3_test_control()].
6131 ** These parameters and their meanings are subject to change
6132 ** without notice. These values are for testing purposes only.
6133 ** Applications should not use any of these parameters or the
6134 ** [sqlite3_test_control()] interface.
6136 #define SQLITE_TESTCTRL_FIRST 5
6137 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6138 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6139 #define SQLITE_TESTCTRL_PRNG_RESET 7
6140 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6141 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6142 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6143 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6144 #define SQLITE_TESTCTRL_ASSERT 12
6145 #define SQLITE_TESTCTRL_ALWAYS 13
6146 #define SQLITE_TESTCTRL_RESERVE 14
6147 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6148 #define SQLITE_TESTCTRL_ISKEYWORD 16
6149 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6150 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6151 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
6152 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
6153 #define SQLITE_TESTCTRL_LAST 20
6156 ** CAPI3REF: SQLite Runtime Status
6158 ** ^This interface is used to retrieve runtime status information
6159 ** about the performance of SQLite, and optionally to reset various
6160 ** highwater marks. ^The first argument is an integer code for
6161 ** the specific parameter to measure. ^(Recognized integer codes
6162 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6163 ** ^The current value of the parameter is returned into *pCurrent.
6164 ** ^The highest recorded value is returned in *pHighwater. ^If the
6165 ** resetFlag is true, then the highest record value is reset after
6166 ** *pHighwater is written. ^(Some parameters do not record the highest
6167 ** value. For those parameters
6168 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6169 ** ^(Other parameters record only the highwater mark and not the current
6170 ** value. For these latter parameters nothing is written into *pCurrent.)^
6172 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6173 ** non-zero [error code] on failure.
6175 ** This routine is threadsafe but is not atomic. This routine can be
6176 ** called while other threads are running the same or different SQLite
6177 ** interfaces. However the values returned in *pCurrent and
6178 ** *pHighwater reflect the status of SQLite at different points in time
6179 ** and it is possible that another thread might change the parameter
6180 ** in between the times when *pCurrent and *pHighwater are written.
6182 ** See also: [sqlite3_db_status()]
6184 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6188 ** CAPI3REF: Status Parameters
6189 ** KEYWORDS: {status parameters}
6191 ** These integer constants designate various run-time status parameters
6192 ** that can be returned by [sqlite3_status()].
6194 ** <dl>
6195 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6196 ** <dd>This parameter is the current amount of memory checked out
6197 ** using [sqlite3_malloc()], either directly or indirectly. The
6198 ** figure includes calls made to [sqlite3_malloc()] by the application
6199 ** and internal memory usage by the SQLite library. Scratch memory
6200 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6201 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6202 ** this parameter. The amount returned is the sum of the allocation
6203 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6205 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6206 ** <dd>This parameter records the largest memory allocation request
6207 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6208 ** internal equivalents). Only the value returned in the
6209 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6210 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6212 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6213 ** <dd>This parameter records the number of separate memory allocations
6214 ** currently checked out.</dd>)^
6216 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6217 ** <dd>This parameter returns the number of pages used out of the
6218 ** [pagecache memory allocator] that was configured using
6219 ** [SQLITE_CONFIG_PAGECACHE]. The
6220 ** value returned is in pages, not in bytes.</dd>)^
6222 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6223 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6224 ** <dd>This parameter returns the number of bytes of page cache
6225 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6226 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6227 ** returned value includes allocations that overflowed because they
6228 ** where too large (they were larger than the "sz" parameter to
6229 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6230 ** no space was left in the page cache.</dd>)^
6232 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6233 ** <dd>This parameter records the largest memory allocation request
6234 ** handed to [pagecache memory allocator]. Only the value returned in the
6235 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6236 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6238 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6239 ** <dd>This parameter returns the number of allocations used out of the
6240 ** [scratch memory allocator] configured using
6241 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6242 ** in bytes. Since a single thread may only have one scratch allocation
6243 ** outstanding at time, this parameter also reports the number of threads
6244 ** using scratch memory at the same time.</dd>)^
6246 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6247 ** <dd>This parameter returns the number of bytes of scratch memory
6248 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6249 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6250 ** returned include overflows because the requested allocation was too
6251 ** larger (that is, because the requested allocation was larger than the
6252 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6253 ** slots were available.
6254 ** </dd>)^
6256 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6257 ** <dd>This parameter records the largest memory allocation request
6258 ** handed to [scratch memory allocator]. Only the value returned in the
6259 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6260 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6262 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6263 ** <dd>This parameter records the deepest parser stack. It is only
6264 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6265 ** </dl>
6267 ** New status parameters may be added from time to time.
6269 #define SQLITE_STATUS_MEMORY_USED 0
6270 #define SQLITE_STATUS_PAGECACHE_USED 1
6271 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6272 #define SQLITE_STATUS_SCRATCH_USED 3
6273 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6274 #define SQLITE_STATUS_MALLOC_SIZE 5
6275 #define SQLITE_STATUS_PARSER_STACK 6
6276 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6277 #define SQLITE_STATUS_SCRATCH_SIZE 8
6278 #define SQLITE_STATUS_MALLOC_COUNT 9
6281 ** CAPI3REF: Database Connection Status
6283 ** ^This interface is used to retrieve runtime status information
6284 ** about a single [database connection]. ^The first argument is the
6285 ** database connection object to be interrogated. ^The second argument
6286 ** is an integer constant, taken from the set of
6287 ** [SQLITE_DBSTATUS options], that
6288 ** determines the parameter to interrogate. The set of
6289 ** [SQLITE_DBSTATUS options] is likely
6290 ** to grow in future releases of SQLite.
6292 ** ^The current value of the requested parameter is written into *pCur
6293 ** and the highest instantaneous value is written into *pHiwtr. ^If
6294 ** the resetFlg is true, then the highest instantaneous value is
6295 ** reset back down to the current value.
6297 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6298 ** non-zero [error code] on failure.
6300 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6302 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6305 ** CAPI3REF: Status Parameters for database connections
6306 ** KEYWORDS: {SQLITE_DBSTATUS options}
6308 ** These constants are the available integer "verbs" that can be passed as
6309 ** the second argument to the [sqlite3_db_status()] interface.
6311 ** New verbs may be added in future releases of SQLite. Existing verbs
6312 ** might be discontinued. Applications should check the return code from
6313 ** [sqlite3_db_status()] to make sure that the call worked.
6314 ** The [sqlite3_db_status()] interface will return a non-zero error code
6315 ** if a discontinued or unsupported verb is invoked.
6317 ** <dl>
6318 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6319 ** <dd>This parameter returns the number of lookaside memory slots currently
6320 ** checked out.</dd>)^
6322 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6323 ** <dd>This parameter returns the number malloc attempts that were
6324 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6325 ** the current value is always zero.)^
6327 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6328 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6329 ** <dd>This parameter returns the number malloc attempts that might have
6330 ** been satisfied using lookaside memory but failed due to the amount of
6331 ** memory requested being larger than the lookaside slot size.
6332 ** Only the high-water value is meaningful;
6333 ** the current value is always zero.)^
6335 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6336 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6337 ** <dd>This parameter returns the number malloc attempts that might have
6338 ** been satisfied using lookaside memory but failed due to all lookaside
6339 ** memory already being in use.
6340 ** Only the high-water value is meaningful;
6341 ** the current value is always zero.)^
6343 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6344 ** <dd>This parameter returns the approximate number of of bytes of heap
6345 ** memory used by all pager caches associated with the database connection.)^
6346 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6348 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6349 ** <dd>This parameter returns the approximate number of of bytes of heap
6350 ** memory used to store the schema for all databases associated
6351 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6352 ** ^The full amount of memory used by the schemas is reported, even if the
6353 ** schema memory is shared with other database connections due to
6354 ** [shared cache mode] being enabled.
6355 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6357 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6358 ** <dd>This parameter returns the approximate number of of bytes of heap
6359 ** and lookaside memory used by all prepared statements associated with
6360 ** the database connection.)^
6361 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6362 ** </dd>
6364 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6365 ** <dd>This parameter returns the number of pager cache hits that have
6366 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6367 ** is always 0.
6368 ** </dd>
6370 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6371 ** <dd>This parameter returns the number of pager cache misses that have
6372 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6373 ** is always 0.
6374 ** </dd>
6376 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6377 ** <dd>This parameter returns the number of dirty cache entries that have
6378 ** been written to disk. Specifically, the number of pages written to the
6379 ** wal file in wal mode databases, or the number of pages written to the
6380 ** database file in rollback mode databases. Any pages written as part of
6381 ** transaction rollback or database recovery operations are not included.
6382 ** If an IO or other error occurs while writing a page to disk, the effect
6383 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6384 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6385 ** </dd>
6387 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6388 ** <dd>This parameter returns zero for the current value if and only if
6389 ** all foreign key constraints (deferred or immediate) have been
6390 ** resolved.)^ ^The highwater mark is always 0.
6391 ** </dd>
6392 ** </dl>
6394 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
6395 #define SQLITE_DBSTATUS_CACHE_USED 1
6396 #define SQLITE_DBSTATUS_SCHEMA_USED 2
6397 #define SQLITE_DBSTATUS_STMT_USED 3
6398 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
6399 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
6400 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
6401 #define SQLITE_DBSTATUS_CACHE_HIT 7
6402 #define SQLITE_DBSTATUS_CACHE_MISS 8
6403 #define SQLITE_DBSTATUS_CACHE_WRITE 9
6404 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
6405 #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
6409 ** CAPI3REF: Prepared Statement Status
6411 ** ^(Each prepared statement maintains various
6412 ** [SQLITE_STMTSTATUS counters] that measure the number
6413 ** of times it has performed specific operations.)^ These counters can
6414 ** be used to monitor the performance characteristics of the prepared
6415 ** statements. For example, if the number of table steps greatly exceeds
6416 ** the number of table searches or result rows, that would tend to indicate
6417 ** that the prepared statement is using a full table scan rather than
6418 ** an index.
6420 ** ^(This interface is used to retrieve and reset counter values from
6421 ** a [prepared statement]. The first argument is the prepared statement
6422 ** object to be interrogated. The second argument
6423 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6424 ** to be interrogated.)^
6425 ** ^The current value of the requested counter is returned.
6426 ** ^If the resetFlg is true, then the counter is reset to zero after this
6427 ** interface call returns.
6429 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6431 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6434 ** CAPI3REF: Status Parameters for prepared statements
6435 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6437 ** These preprocessor macros define integer codes that name counter
6438 ** values associated with the [sqlite3_stmt_status()] interface.
6439 ** The meanings of the various counters are as follows:
6441 ** <dl>
6442 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6443 ** <dd>^This is the number of times that SQLite has stepped forward in
6444 ** a table as part of a full table scan. Large numbers for this counter
6445 ** may indicate opportunities for performance improvement through
6446 ** careful use of indices.</dd>
6448 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6449 ** <dd>^This is the number of sort operations that have occurred.
6450 ** A non-zero value in this counter may indicate an opportunity to
6451 ** improvement performance through careful use of indices.</dd>
6453 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6454 ** <dd>^This is the number of rows inserted into transient indices that
6455 ** were created automatically in order to help joins run faster.
6456 ** A non-zero value in this counter may indicate an opportunity to
6457 ** improvement performance by adding permanent indices that do not
6458 ** need to be reinitialized each time the statement is run.</dd>
6460 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6461 ** <dd>^This is the number of virtual machine operations executed
6462 ** by the prepared statement if that number is less than or equal
6463 ** to 2147483647. The number of virtual machine operations can be
6464 ** used as a proxy for the total work done by the prepared statement.
6465 ** If the number of virtual machine operations exceeds 2147483647
6466 ** then the value returned by this statement status code is undefined.
6467 ** </dd>
6468 ** </dl>
6470 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
6471 #define SQLITE_STMTSTATUS_SORT 2
6472 #define SQLITE_STMTSTATUS_AUTOINDEX 3
6473 #define SQLITE_STMTSTATUS_VM_STEP 4
6476 ** CAPI3REF: Custom Page Cache Object
6478 ** The sqlite3_pcache type is opaque. It is implemented by
6479 ** the pluggable module. The SQLite core has no knowledge of
6480 ** its size or internal structure and never deals with the
6481 ** sqlite3_pcache object except by holding and passing pointers
6482 ** to the object.
6484 ** See [sqlite3_pcache_methods2] for additional information.
6486 typedef struct sqlite3_pcache sqlite3_pcache;
6489 ** CAPI3REF: Custom Page Cache Object
6491 ** The sqlite3_pcache_page object represents a single page in the
6492 ** page cache. The page cache will allocate instances of this
6493 ** object. Various methods of the page cache use pointers to instances
6494 ** of this object as parameters or as their return value.
6496 ** See [sqlite3_pcache_methods2] for additional information.
6498 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6499 struct sqlite3_pcache_page {
6500 void *pBuf; /* The content of the page */
6501 void *pExtra; /* Extra information associated with the page */
6505 ** CAPI3REF: Application Defined Page Cache.
6506 ** KEYWORDS: {page cache}
6508 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6509 ** register an alternative page cache implementation by passing in an
6510 ** instance of the sqlite3_pcache_methods2 structure.)^
6511 ** In many applications, most of the heap memory allocated by
6512 ** SQLite is used for the page cache.
6513 ** By implementing a
6514 ** custom page cache using this API, an application can better control
6515 ** the amount of memory consumed by SQLite, the way in which
6516 ** that memory is allocated and released, and the policies used to
6517 ** determine exactly which parts of a database file are cached and for
6518 ** how long.
6520 ** The alternative page cache mechanism is an
6521 ** extreme measure that is only needed by the most demanding applications.
6522 ** The built-in page cache is recommended for most uses.
6524 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6525 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
6526 ** the application may discard the parameter after the call to
6527 ** [sqlite3_config()] returns.)^
6529 ** [[the xInit() page cache method]]
6530 ** ^(The xInit() method is called once for each effective
6531 ** call to [sqlite3_initialize()])^
6532 ** (usually only once during the lifetime of the process). ^(The xInit()
6533 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6534 ** The intent of the xInit() method is to set up global data structures
6535 ** required by the custom page cache implementation.
6536 ** ^(If the xInit() method is NULL, then the
6537 ** built-in default page cache is used instead of the application defined
6538 ** page cache.)^
6540 ** [[the xShutdown() page cache method]]
6541 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6542 ** It can be used to clean up
6543 ** any outstanding resources before process shutdown, if required.
6544 ** ^The xShutdown() method may be NULL.
6546 ** ^SQLite automatically serializes calls to the xInit method,
6547 ** so the xInit method need not be threadsafe. ^The
6548 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6549 ** not need to be threadsafe either. All other methods must be threadsafe
6550 ** in multithreaded applications.
6552 ** ^SQLite will never invoke xInit() more than once without an intervening
6553 ** call to xShutdown().
6555 ** [[the xCreate() page cache methods]]
6556 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6557 ** SQLite will typically create one cache instance for each open database file,
6558 ** though this is not guaranteed. ^The
6559 ** first parameter, szPage, is the size in bytes of the pages that must
6560 ** be allocated by the cache. ^szPage will always a power of two. ^The
6561 ** second parameter szExtra is a number of bytes of extra storage
6562 ** associated with each page cache entry. ^The szExtra parameter will
6563 ** a number less than 250. SQLite will use the
6564 ** extra szExtra bytes on each page to store metadata about the underlying
6565 ** database page on disk. The value passed into szExtra depends
6566 ** on the SQLite version, the target platform, and how SQLite was compiled.
6567 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6568 ** created will be used to cache database pages of a file stored on disk, or
6569 ** false if it is used for an in-memory database. The cache implementation
6570 ** does not have to do anything special based with the value of bPurgeable;
6571 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
6572 ** never invoke xUnpin() except to deliberately delete a page.
6573 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6574 ** false will always have the "discard" flag set to true.
6575 ** ^Hence, a cache created with bPurgeable false will
6576 ** never contain any unpinned pages.
6578 ** [[the xCachesize() page cache method]]
6579 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6580 ** suggested maximum cache-size (number of pages stored by) the cache
6581 ** instance passed as the first argument. This is the value configured using
6582 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
6583 ** parameter, the implementation is not required to do anything with this
6584 ** value; it is advisory only.
6586 ** [[the xPagecount() page cache methods]]
6587 ** The xPagecount() method must return the number of pages currently
6588 ** stored in the cache, both pinned and unpinned.
6590 ** [[the xFetch() page cache methods]]
6591 ** The xFetch() method locates a page in the cache and returns a pointer to
6592 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6593 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6594 ** pointer to a buffer of szPage bytes used to store the content of a
6595 ** single database page. The pExtra element of sqlite3_pcache_page will be
6596 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6597 ** for each entry in the page cache.
6599 ** The page to be fetched is determined by the key. ^The minimum key value
6600 ** is 1. After it has been retrieved using xFetch, the page is considered
6601 ** to be "pinned".
6603 ** If the requested page is already in the page cache, then the page cache
6604 ** implementation must return a pointer to the page buffer with its content
6605 ** intact. If the requested page is not already in the cache, then the
6606 ** cache implementation should use the value of the createFlag
6607 ** parameter to help it determined what action to take:
6609 ** <table border=1 width=85% align=center>
6610 ** <tr><th> createFlag <th> Behavior when page is not already in cache
6611 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
6612 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6613 ** Otherwise return NULL.
6614 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
6615 ** NULL if allocating a new page is effectively impossible.
6616 ** </table>
6618 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
6619 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6620 ** failed.)^ In between the to xFetch() calls, SQLite may
6621 ** attempt to unpin one or more cache pages by spilling the content of
6622 ** pinned pages to disk and synching the operating system disk cache.
6624 ** [[the xUnpin() page cache method]]
6625 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6626 ** as its second argument. If the third parameter, discard, is non-zero,
6627 ** then the page must be evicted from the cache.
6628 ** ^If the discard parameter is
6629 ** zero, then the page may be discarded or retained at the discretion of
6630 ** page cache implementation. ^The page cache implementation
6631 ** may choose to evict unpinned pages at any time.
6633 ** The cache must not perform any reference counting. A single
6634 ** call to xUnpin() unpins the page regardless of the number of prior calls
6635 ** to xFetch().
6637 ** [[the xRekey() page cache methods]]
6638 ** The xRekey() method is used to change the key value associated with the
6639 ** page passed as the second argument. If the cache
6640 ** previously contains an entry associated with newKey, it must be
6641 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6642 ** to be pinned.
6644 ** When SQLite calls the xTruncate() method, the cache must discard all
6645 ** existing cache entries with page numbers (keys) greater than or equal
6646 ** to the value of the iLimit parameter passed to xTruncate(). If any
6647 ** of these pages are pinned, they are implicitly unpinned, meaning that
6648 ** they can be safely discarded.
6650 ** [[the xDestroy() page cache method]]
6651 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6652 ** All resources associated with the specified cache should be freed. ^After
6653 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6654 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6655 ** functions.
6657 ** [[the xShrink() page cache method]]
6658 ** ^SQLite invokes the xShrink() method when it wants the page cache to
6659 ** free up as much of heap memory as possible. The page cache implementation
6660 ** is not obligated to free any memory, but well-behaved implementations should
6661 ** do their best.
6663 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6664 struct sqlite3_pcache_methods2 {
6665 int iVersion;
6666 void *pArg;
6667 int (*xInit)(void*);
6668 void (*xShutdown)(void*);
6669 sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6670 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6671 int (*xPagecount)(sqlite3_pcache*);
6672 sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6673 void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6674 void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
6675 unsigned oldKey, unsigned newKey);
6676 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6677 void (*xDestroy)(sqlite3_pcache*);
6678 void (*xShrink)(sqlite3_pcache*);
6682 ** This is the obsolete pcache_methods object that has now been replaced
6683 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
6684 ** retained in the header file for backwards compatibility only.
6686 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6687 struct sqlite3_pcache_methods {
6688 void *pArg;
6689 int (*xInit)(void*);
6690 void (*xShutdown)(void*);
6691 sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6692 void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6693 int (*xPagecount)(sqlite3_pcache*);
6694 void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6695 void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6696 void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6697 void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6698 void (*xDestroy)(sqlite3_pcache*);
6703 ** CAPI3REF: Online Backup Object
6705 ** The sqlite3_backup object records state information about an ongoing
6706 ** online backup operation. ^The sqlite3_backup object is created by
6707 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6708 ** [sqlite3_backup_finish()].
6710 ** See Also: [Using the SQLite Online Backup API]
6712 typedef struct sqlite3_backup sqlite3_backup;
6715 ** CAPI3REF: Online Backup API.
6717 ** The backup API copies the content of one database into another.
6718 ** It is useful either for creating backups of databases or
6719 ** for copying in-memory databases to or from persistent files.
6721 ** See Also: [Using the SQLite Online Backup API]
6723 ** ^SQLite holds a write transaction open on the destination database file
6724 ** for the duration of the backup operation.
6725 ** ^The source database is read-locked only while it is being read;
6726 ** it is not locked continuously for the entire backup operation.
6727 ** ^Thus, the backup may be performed on a live source database without
6728 ** preventing other database connections from
6729 ** reading or writing to the source database while the backup is underway.
6731 ** ^(To perform a backup operation:
6732 ** <ol>
6733 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
6734 ** backup,
6735 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6736 ** the data between the two databases, and finally
6737 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
6738 ** associated with the backup operation.
6739 ** </ol>)^
6740 ** There should be exactly one call to sqlite3_backup_finish() for each
6741 ** successful call to sqlite3_backup_init().
6743 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6745 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6746 ** [database connection] associated with the destination database
6747 ** and the database name, respectively.
6748 ** ^The database name is "main" for the main database, "temp" for the
6749 ** temporary database, or the name specified after the AS keyword in
6750 ** an [ATTACH] statement for an attached database.
6751 ** ^The S and M arguments passed to
6752 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6753 ** and database name of the source database, respectively.
6754 ** ^The source and destination [database connections] (parameters S and D)
6755 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6756 ** an error.
6758 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6759 ** returned and an error code and error message are stored in the
6760 ** destination [database connection] D.
6761 ** ^The error code and message for the failed call to sqlite3_backup_init()
6762 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6763 ** [sqlite3_errmsg16()] functions.
6764 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6765 ** [sqlite3_backup] object.
6766 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6767 ** sqlite3_backup_finish() functions to perform the specified backup
6768 ** operation.
6770 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6772 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6773 ** the source and destination databases specified by [sqlite3_backup] object B.
6774 ** ^If N is negative, all remaining source pages are copied.
6775 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6776 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6777 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6778 ** from source to destination, then it returns [SQLITE_DONE].
6779 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6780 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6781 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6782 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6783 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6785 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6786 ** <ol>
6787 ** <li> the destination database was opened read-only, or
6788 ** <li> the destination database is using write-ahead-log journaling
6789 ** and the destination and source page sizes differ, or
6790 ** <li> the destination database is an in-memory database and the
6791 ** destination and source page sizes differ.
6792 ** </ol>)^
6794 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6795 ** the [sqlite3_busy_handler | busy-handler function]
6796 ** is invoked (if one is specified). ^If the
6797 ** busy-handler returns non-zero before the lock is available, then
6798 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6799 ** sqlite3_backup_step() can be retried later. ^If the source
6800 ** [database connection]
6801 ** is being used to write to the source database when sqlite3_backup_step()
6802 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6803 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6804 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6805 ** [SQLITE_READONLY] is returned, then
6806 ** there is no point in retrying the call to sqlite3_backup_step(). These
6807 ** errors are considered fatal.)^ The application must accept
6808 ** that the backup operation has failed and pass the backup operation handle
6809 ** to the sqlite3_backup_finish() to release associated resources.
6811 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6812 ** on the destination file. ^The exclusive lock is not released until either
6813 ** sqlite3_backup_finish() is called or the backup operation is complete
6814 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
6815 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6816 ** lasts for the duration of the sqlite3_backup_step() call.
6817 ** ^Because the source database is not locked between calls to
6818 ** sqlite3_backup_step(), the source database may be modified mid-way
6819 ** through the backup process. ^If the source database is modified by an
6820 ** external process or via a database connection other than the one being
6821 ** used by the backup operation, then the backup will be automatically
6822 ** restarted by the next call to sqlite3_backup_step(). ^If the source
6823 ** database is modified by the using the same database connection as is used
6824 ** by the backup operation, then the backup database is automatically
6825 ** updated at the same time.
6827 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6829 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6830 ** application wishes to abandon the backup operation, the application
6831 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6832 ** ^The sqlite3_backup_finish() interfaces releases all
6833 ** resources associated with the [sqlite3_backup] object.
6834 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6835 ** active write-transaction on the destination database is rolled back.
6836 ** The [sqlite3_backup] object is invalid
6837 ** and may not be used following a call to sqlite3_backup_finish().
6839 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6840 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6841 ** sqlite3_backup_step() completed.
6842 ** ^If an out-of-memory condition or IO error occurred during any prior
6843 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6844 ** sqlite3_backup_finish() returns the corresponding [error code].
6846 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6847 ** is not a permanent error and does not affect the return value of
6848 ** sqlite3_backup_finish().
6850 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
6851 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
6853 ** ^Each call to sqlite3_backup_step() sets two values inside
6854 ** the [sqlite3_backup] object: the number of pages still to be backed
6855 ** up and the total number of pages in the source database file.
6856 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6857 ** retrieve these two values, respectively.
6859 ** ^The values returned by these functions are only updated by
6860 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6861 ** operation, then the values are not updated to account for any extra
6862 ** pages that need to be updated or the size of the source database file
6863 ** changing.
6865 ** <b>Concurrent Usage of Database Handles</b>
6867 ** ^The source [database connection] may be used by the application for other
6868 ** purposes while a backup operation is underway or being initialized.
6869 ** ^If SQLite is compiled and configured to support threadsafe database
6870 ** connections, then the source database connection may be used concurrently
6871 ** from within other threads.
6873 ** However, the application must guarantee that the destination
6874 ** [database connection] is not passed to any other API (by any thread) after
6875 ** sqlite3_backup_init() is called and before the corresponding call to
6876 ** sqlite3_backup_finish(). SQLite does not currently check to see
6877 ** if the application incorrectly accesses the destination [database connection]
6878 ** and so no error code is reported, but the operations may malfunction
6879 ** nevertheless. Use of the destination database connection while a
6880 ** backup is in progress might also also cause a mutex deadlock.
6882 ** If running in [shared cache mode], the application must
6883 ** guarantee that the shared cache used by the destination database
6884 ** is not accessed while the backup is running. In practice this means
6885 ** that the application must guarantee that the disk file being
6886 ** backed up to is not accessed by any connection within the process,
6887 ** not just the specific connection that was passed to sqlite3_backup_init().
6889 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6890 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6891 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6892 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6893 ** same time as another thread is invoking sqlite3_backup_step() it is
6894 ** possible that they return invalid values.
6896 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6897 sqlite3 *pDest, /* Destination database handle */
6898 const char *zDestName, /* Destination database name */
6899 sqlite3 *pSource, /* Source database handle */
6900 const char *zSourceName /* Source database name */
6902 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6903 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6904 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6905 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6908 ** CAPI3REF: Unlock Notification
6910 ** ^When running in shared-cache mode, a database operation may fail with
6911 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6912 ** individual tables within the shared-cache cannot be obtained. See
6913 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6914 ** ^This API may be used to register a callback that SQLite will invoke
6915 ** when the connection currently holding the required lock relinquishes it.
6916 ** ^This API is only available if the library was compiled with the
6917 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6919 ** See Also: [Using the SQLite Unlock Notification Feature].
6921 ** ^Shared-cache locks are released when a database connection concludes
6922 ** its current transaction, either by committing it or rolling it back.
6924 ** ^When a connection (known as the blocked connection) fails to obtain a
6925 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6926 ** identity of the database connection (the blocking connection) that
6927 ** has locked the required resource is stored internally. ^After an
6928 ** application receives an SQLITE_LOCKED error, it may call the
6929 ** sqlite3_unlock_notify() method with the blocked connection handle as
6930 ** the first argument to register for a callback that will be invoked
6931 ** when the blocking connections current transaction is concluded. ^The
6932 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6933 ** call that concludes the blocking connections transaction.
6935 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6936 ** there is a chance that the blocking connection will have already
6937 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6938 ** If this happens, then the specified callback is invoked immediately,
6939 ** from within the call to sqlite3_unlock_notify().)^
6941 ** ^If the blocked connection is attempting to obtain a write-lock on a
6942 ** shared-cache table, and more than one other connection currently holds
6943 ** a read-lock on the same table, then SQLite arbitrarily selects one of
6944 ** the other connections to use as the blocking connection.
6946 ** ^(There may be at most one unlock-notify callback registered by a
6947 ** blocked connection. If sqlite3_unlock_notify() is called when the
6948 ** blocked connection already has a registered unlock-notify callback,
6949 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6950 ** called with a NULL pointer as its second argument, then any existing
6951 ** unlock-notify callback is canceled. ^The blocked connections
6952 ** unlock-notify callback may also be canceled by closing the blocked
6953 ** connection using [sqlite3_close()].
6955 ** The unlock-notify callback is not reentrant. If an application invokes
6956 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6957 ** crash or deadlock may be the result.
6959 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6960 ** returns SQLITE_OK.
6962 ** <b>Callback Invocation Details</b>
6964 ** When an unlock-notify callback is registered, the application provides a
6965 ** single void* pointer that is passed to the callback when it is invoked.
6966 ** However, the signature of the callback function allows SQLite to pass
6967 ** it an array of void* context pointers. The first argument passed to
6968 ** an unlock-notify callback is a pointer to an array of void* pointers,
6969 ** and the second is the number of entries in the array.
6971 ** When a blocking connections transaction is concluded, there may be
6972 ** more than one blocked connection that has registered for an unlock-notify
6973 ** callback. ^If two or more such blocked connections have specified the
6974 ** same callback function, then instead of invoking the callback function
6975 ** multiple times, it is invoked once with the set of void* context pointers
6976 ** specified by the blocked connections bundled together into an array.
6977 ** This gives the application an opportunity to prioritize any actions
6978 ** related to the set of unblocked database connections.
6980 ** <b>Deadlock Detection</b>
6982 ** Assuming that after registering for an unlock-notify callback a
6983 ** database waits for the callback to be issued before taking any further
6984 ** action (a reasonable assumption), then using this API may cause the
6985 ** application to deadlock. For example, if connection X is waiting for
6986 ** connection Y's transaction to be concluded, and similarly connection
6987 ** Y is waiting on connection X's transaction, then neither connection
6988 ** will proceed and the system may remain deadlocked indefinitely.
6990 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6991 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6992 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6993 ** unlock-notify callback is registered. The system is said to be in
6994 ** a deadlocked state if connection A has registered for an unlock-notify
6995 ** callback on the conclusion of connection B's transaction, and connection
6996 ** B has itself registered for an unlock-notify callback when connection
6997 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6998 ** the system is also considered to be deadlocked if connection B has
6999 ** registered for an unlock-notify callback on the conclusion of connection
7000 ** C's transaction, where connection C is waiting on connection A. ^Any
7001 ** number of levels of indirection are allowed.
7003 ** <b>The "DROP TABLE" Exception</b>
7005 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7006 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7007 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7008 ** SQLite checks if there are any currently executing SELECT statements
7009 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7010 ** returned. In this case there is no "blocking connection", so invoking
7011 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7012 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7013 ** or "DROP INDEX" query, an infinite loop might be the result.
7015 ** One way around this problem is to check the extended error code returned
7016 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7017 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7018 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7019 ** SQLITE_LOCKED.)^
7021 SQLITE_API int sqlite3_unlock_notify(
7022 sqlite3 *pBlocked, /* Waiting connection */
7023 void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7024 void *pNotifyArg /* Argument to pass to xNotify */
7029 ** CAPI3REF: String Comparison
7031 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7032 ** and extensions to compare the contents of two buffers containing UTF-8
7033 ** strings in a case-independent fashion, using the same definition of "case
7034 ** independence" that SQLite uses internally when comparing identifiers.
7036 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7037 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7040 ** CAPI3REF: String Globbing
7042 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7043 ** the glob pattern P, and it returns non-zero if string X does not match
7044 ** the glob pattern P. ^The definition of glob pattern matching used in
7045 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7046 ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
7047 ** sensitive.
7049 ** Note that this routine returns zero on a match and non-zero if the strings
7050 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7052 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7055 ** CAPI3REF: Error Logging Interface
7057 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7058 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7059 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7060 ** used with [sqlite3_snprintf()] to generate the final output string.
7062 ** The sqlite3_log() interface is intended for use by extensions such as
7063 ** virtual tables, collating functions, and SQL functions. While there is
7064 ** nothing to prevent an application from calling sqlite3_log(), doing so
7065 ** is considered bad form.
7067 ** The zFormat string must not be NULL.
7069 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7070 ** will not use dynamically allocated memory. The log message is stored in
7071 ** a fixed-length buffer on the stack. If the log message is longer than
7072 ** a few hundred characters, it will be truncated to the length of the
7073 ** buffer.
7075 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7078 ** CAPI3REF: Write-Ahead Log Commit Hook
7080 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7081 ** will be invoked each time a database connection commits data to a
7082 ** [write-ahead log] (i.e. whenever a transaction is committed in
7083 ** [journal_mode | journal_mode=WAL mode]).
7085 ** ^The callback is invoked by SQLite after the commit has taken place and
7086 ** the associated write-lock on the database released, so the implementation
7087 ** may read, write or [checkpoint] the database as required.
7089 ** ^The first parameter passed to the callback function when it is invoked
7090 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7091 ** registering the callback. ^The second is a copy of the database handle.
7092 ** ^The third parameter is the name of the database that was written to -
7093 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7094 ** is the number of pages currently in the write-ahead log file,
7095 ** including those that were just committed.
7097 ** The callback function should normally return [SQLITE_OK]. ^If an error
7098 ** code is returned, that error will propagate back up through the
7099 ** SQLite code base to cause the statement that provoked the callback
7100 ** to report an error, though the commit will have still occurred. If the
7101 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7102 ** that does not correspond to any valid SQLite error code, the results
7103 ** are undefined.
7105 ** A single database handle may have at most a single write-ahead log callback
7106 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7107 ** previously registered write-ahead log callback. ^Note that the
7108 ** [sqlite3_wal_autocheckpoint()] interface and the
7109 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7110 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7112 SQLITE_API void *sqlite3_wal_hook(
7113 sqlite3*,
7114 int(*)(void *,sqlite3*,const char*,int),
7115 void*
7119 ** CAPI3REF: Configure an auto-checkpoint
7121 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7122 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7123 ** to automatically [checkpoint]
7124 ** after committing a transaction if there are N or
7125 ** more frames in the [write-ahead log] file. ^Passing zero or
7126 ** a negative value as the nFrame parameter disables automatic
7127 ** checkpoints entirely.
7129 ** ^The callback registered by this function replaces any existing callback
7130 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7131 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7132 ** configured by this function.
7134 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7135 ** from SQL.
7137 ** ^Every new [database connection] defaults to having the auto-checkpoint
7138 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7139 ** pages. The use of this interface
7140 ** is only necessary if the default setting is found to be suboptimal
7141 ** for a particular application.
7143 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7146 ** CAPI3REF: Checkpoint a database
7148 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7149 ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
7150 ** empty string, then a checkpoint is run on all databases of
7151 ** connection D. ^If the database connection D is not in
7152 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7154 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7155 ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
7156 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7157 ** run whenever the WAL reaches a certain size threshold.
7159 ** See also: [sqlite3_wal_checkpoint_v2()]
7161 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7164 ** CAPI3REF: Checkpoint a database
7166 ** Run a checkpoint operation on WAL database zDb attached to database
7167 ** handle db. The specific operation is determined by the value of the
7168 ** eMode parameter:
7170 ** <dl>
7171 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7172 ** Checkpoint as many frames as possible without waiting for any database
7173 ** readers or writers to finish. Sync the db file if all frames in the log
7174 ** are checkpointed. This mode is the same as calling
7175 ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7177 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7178 ** This mode blocks (calls the busy-handler callback) until there is no
7179 ** database writer and all readers are reading from the most recent database
7180 ** snapshot. It then checkpoints all frames in the log file and syncs the
7181 ** database file. This call blocks database writers while it is running,
7182 ** but not database readers.
7184 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7185 ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7186 ** checkpointing the log file it blocks (calls the busy-handler callback)
7187 ** until all readers are reading from the database file only. This ensures
7188 ** that the next client to write to the database file restarts the log file
7189 ** from the beginning. This call blocks database writers while it is running,
7190 ** but not database readers.
7191 ** </dl>
7193 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7194 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7195 ** the total number of checkpointed frames (including any that were already
7196 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7197 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7198 ** If no values are available because of an error, they are both set to -1
7199 ** before returning to communicate this to the caller.
7201 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7202 ** any other process is running a checkpoint operation at the same time, the
7203 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7204 ** busy-handler configured, it will not be invoked in this case.
7206 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7207 ** "writer" lock on the database file. If the writer lock cannot be obtained
7208 ** immediately, and a busy-handler is configured, it is invoked and the writer
7209 ** lock retried until either the busy-handler returns 0 or the lock is
7210 ** successfully obtained. The busy-handler is also invoked while waiting for
7211 ** database readers as described above. If the busy-handler returns 0 before
7212 ** the writer lock is obtained or while waiting for database readers, the
7213 ** checkpoint operation proceeds from that point in the same way as
7214 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7215 ** without blocking any further. SQLITE_BUSY is returned in this case.
7217 ** If parameter zDb is NULL or points to a zero length string, then the
7218 ** specified operation is attempted on all WAL databases. In this case the
7219 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7220 ** an SQLITE_BUSY error is encountered when processing one or more of the
7221 ** attached WAL databases, the operation is still attempted on any remaining
7222 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7223 ** error occurs while processing an attached database, processing is abandoned
7224 ** and the error code returned to the caller immediately. If no error
7225 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7226 ** databases, SQLITE_OK is returned.
7228 ** If database zDb is the name of an attached database that is not in WAL
7229 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7230 ** zDb is not NULL (or a zero length string) and is not the name of any
7231 ** attached database, SQLITE_ERROR is returned to the caller.
7233 SQLITE_API int sqlite3_wal_checkpoint_v2(
7234 sqlite3 *db, /* Database handle */
7235 const char *zDb, /* Name of attached database (or NULL) */
7236 int eMode, /* SQLITE_CHECKPOINT_* value */
7237 int *pnLog, /* OUT: Size of WAL log in frames */
7238 int *pnCkpt /* OUT: Total number of frames checkpointed */
7242 ** CAPI3REF: Checkpoint operation parameters
7244 ** These constants can be used as the 3rd parameter to
7245 ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
7246 ** documentation for additional information about the meaning and use of
7247 ** each of these values.
7249 #define SQLITE_CHECKPOINT_PASSIVE 0
7250 #define SQLITE_CHECKPOINT_FULL 1
7251 #define SQLITE_CHECKPOINT_RESTART 2
7254 ** CAPI3REF: Virtual Table Interface Configuration
7256 ** This function may be called by either the [xConnect] or [xCreate] method
7257 ** of a [virtual table] implementation to configure
7258 ** various facets of the virtual table interface.
7260 ** If this interface is invoked outside the context of an xConnect or
7261 ** xCreate virtual table method then the behavior is undefined.
7263 ** At present, there is only one option that may be configured using
7264 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
7265 ** may be added in the future.
7267 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7270 ** CAPI3REF: Virtual Table Configuration Options
7272 ** These macros define the various options to the
7273 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7274 ** can use to customize and optimize their behavior.
7276 ** <dl>
7277 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7278 ** <dd>Calls of the form
7279 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7280 ** where X is an integer. If X is zero, then the [virtual table] whose
7281 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7282 ** support constraints. In this configuration (which is the default) if
7283 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7284 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7285 ** specified as part of the users SQL statement, regardless of the actual
7286 ** ON CONFLICT mode specified.
7288 ** If X is non-zero, then the virtual table implementation guarantees
7289 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7290 ** any modifications to internal or persistent data structures have been made.
7291 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7292 ** is able to roll back a statement or database transaction, and abandon
7293 ** or continue processing the current SQL statement as appropriate.
7294 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7295 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7296 ** had been ABORT.
7298 ** Virtual table implementations that are required to handle OR REPLACE
7299 ** must do so within the [xUpdate] method. If a call to the
7300 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7301 ** CONFLICT policy is REPLACE, the virtual table implementation should
7302 ** silently replace the appropriate rows within the xUpdate callback and
7303 ** return SQLITE_OK. Or, if this is not possible, it may return
7304 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7305 ** constraint handling.
7306 ** </dl>
7308 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7311 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7313 ** This function may only be called from within a call to the [xUpdate] method
7314 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7315 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7316 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7317 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7318 ** [virtual table].
7320 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7323 ** CAPI3REF: Conflict resolution modes
7325 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7326 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7327 ** is for the SQL statement being evaluated.
7329 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7330 ** return value from the [sqlite3_set_authorizer()] callback and that
7331 ** [SQLITE_ABORT] is also a [result code].
7333 #define SQLITE_ROLLBACK 1
7334 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7335 #define SQLITE_FAIL 3
7336 /* #define SQLITE_ABORT 4 // Also an error code */
7337 #define SQLITE_REPLACE 5
7342 ** Undo the hack that converts floating point types to integer for
7343 ** builds on processors without floating point support.
7345 #ifdef SQLITE_OMIT_FLOATING_POINT
7346 # undef double
7347 #endif
7349 #if 0
7350 } /* End of the 'extern "C"' block */
7351 #endif
7352 #endif /* _SQLITE3_H_ */
7355 ** 2010 August 30
7357 ** The author disclaims copyright to this source code. In place of
7358 ** a legal notice, here is a blessing:
7360 ** May you do good and not evil.
7361 ** May you find forgiveness for yourself and forgive others.
7362 ** May you share freely, never taking more than you give.
7364 *************************************************************************
7367 #ifndef _SQLITE3RTREE_H_
7368 #define _SQLITE3RTREE_H_
7371 #if 0
7372 extern "C" {
7373 #endif
7375 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7378 ** Register a geometry callback named zGeom that can be used as part of an
7379 ** R-Tree geometry query as follows:
7381 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7383 SQLITE_API int sqlite3_rtree_geometry_callback(
7384 sqlite3 *db,
7385 const char *zGeom,
7386 #ifdef SQLITE_RTREE_INT_ONLY
7387 int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7388 #else
7389 int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7390 #endif
7391 void *pContext
7396 ** A pointer to a structure of the following type is passed as the first
7397 ** argument to callbacks registered using rtree_geometry_callback().
7399 struct sqlite3_rtree_geometry {
7400 void *pContext; /* Copy of pContext passed to s_r_g_c() */
7401 int nParam; /* Size of array aParam[] */
7402 double *aParam; /* Parameters passed to SQL geom function */
7403 void *pUser; /* Callback implementation user data */
7404 void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
7408 #if 0
7409 } /* end of the 'extern "C"' block */
7410 #endif
7412 #endif /* ifndef _SQLITE3RTREE_H_ */
7415 /************** End of sqlite3.h *********************************************/
7416 /************** Begin file sqliteInt.h ***************************************/
7418 ** 2001 September 15
7420 ** The author disclaims copyright to this source code. In place of
7421 ** a legal notice, here is a blessing:
7423 ** May you do good and not evil.
7424 ** May you find forgiveness for yourself and forgive others.
7425 ** May you share freely, never taking more than you give.
7427 *************************************************************************
7428 ** Internal interface definitions for SQLite.
7431 #ifndef _SQLITEINT_H_
7432 #define _SQLITEINT_H_
7435 ** These #defines should enable >2GB file support on POSIX if the
7436 ** underlying operating system supports it. If the OS lacks
7437 ** large file support, or if the OS is windows, these should be no-ops.
7439 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
7440 ** system #includes. Hence, this block of code must be the very first
7441 ** code in all source files.
7443 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
7444 ** on the compiler command line. This is necessary if you are compiling
7445 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
7446 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
7447 ** without this option, LFS is enable. But LFS does not exist in the kernel
7448 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
7449 ** portability you should omit LFS.
7451 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
7453 #ifndef SQLITE_DISABLE_LFS
7454 # define _LARGE_FILE 1
7455 # ifndef _FILE_OFFSET_BITS
7456 # define _FILE_OFFSET_BITS 64
7457 # endif
7458 # define _LARGEFILE_SOURCE 1
7459 #endif
7462 ** Include the configuration header output by 'configure' if we're using the
7463 ** autoconf-based build
7465 #ifdef _HAVE_SQLITE_CONFIG_H
7466 #include "config.h"
7467 #endif
7469 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
7470 /************** Begin file sqliteLimit.h *************************************/
7472 ** 2007 May 7
7474 ** The author disclaims copyright to this source code. In place of
7475 ** a legal notice, here is a blessing:
7477 ** May you do good and not evil.
7478 ** May you find forgiveness for yourself and forgive others.
7479 ** May you share freely, never taking more than you give.
7481 *************************************************************************
7483 ** This file defines various limits of what SQLite can process.
7487 ** The maximum length of a TEXT or BLOB in bytes. This also
7488 ** limits the size of a row in a table or index.
7490 ** The hard limit is the ability of a 32-bit signed integer
7491 ** to count the size: 2^31-1 or 2147483647.
7493 #ifndef SQLITE_MAX_LENGTH
7494 # define SQLITE_MAX_LENGTH 1000000000
7495 #endif
7498 ** This is the maximum number of
7500 ** * Columns in a table
7501 ** * Columns in an index
7502 ** * Columns in a view
7503 ** * Terms in the SET clause of an UPDATE statement
7504 ** * Terms in the result set of a SELECT statement
7505 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
7506 ** * Terms in the VALUES clause of an INSERT statement
7508 ** The hard upper limit here is 32676. Most database people will
7509 ** tell you that in a well-normalized database, you usually should
7510 ** not have more than a dozen or so columns in any table. And if
7511 ** that is the case, there is no point in having more than a few
7512 ** dozen values in any of the other situations described above.
7514 #ifndef SQLITE_MAX_COLUMN
7515 # define SQLITE_MAX_COLUMN 2000
7516 #endif
7519 ** The maximum length of a single SQL statement in bytes.
7521 ** It used to be the case that setting this value to zero would
7522 ** turn the limit off. That is no longer true. It is not possible
7523 ** to turn this limit off.
7525 #ifdef SQLITE_OMIT_FLOATING_POINT
7526 # define double sqlite_int64
7527 # define float sqlite_int64
7528 # define LONGDOUBLE_TYPE sqlite_int64
7529 # ifndef SQLITE_BIG_DBL
7530 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7531 # endif
7532 # define SQLITE_OMIT_DATETIME_FUNCS 1
7533 # define SQLITE_OMIT_TRACE 1
7534 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7535 # undef SQLITE_HAVE_ISNAN
7536 #else
7537 # ifdef __vax__
7538 # include <float.h>
7539 # define SQLITE_BIG_DBL DBL_MAX
7540 # define SQLITE_HUGE_DBL DBL_MAX
7541 # define SQLITE_HUGE_COST 1e38
7542 # endif
7543 #endif
7544 #ifndef SQLITE_BIG_DBL
7545 # define SQLITE_BIG_DBL (1e99)
7546 #endif
7547 #ifndef SQLITE_HUGE_DBL
7548 # define SQLITE_HUGE_DBL (1.0e+308)
7549 #endif
7550 #ifndef SQLITE_MAX_SQL_LENGTH
7551 # define SQLITE_MAX_SQL_LENGTH 1000000000
7552 #endif
7553 #ifndef SQLITE_HUGE_COST
7554 # define SQLITE_HUGE_COST 1e50
7555 #endif
7558 ** The maximum depth of an expression tree. This is limited to
7559 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
7560 ** want to place more severe limits on the complexity of an
7561 ** expression.
7563 ** A value of 0 used to mean that the limit was not enforced.
7564 ** But that is no longer true. The limit is now strictly enforced
7565 ** at all times.
7567 #ifndef SQLITE_MAX_EXPR_DEPTH
7568 # define SQLITE_MAX_EXPR_DEPTH 1000
7569 #endif
7572 ** The maximum number of terms in a compound SELECT statement.
7573 ** The code generator for compound SELECT statements does one
7574 ** level of recursion for each term. A stack overflow can result
7575 ** if the number of terms is too large. In practice, most SQL
7576 ** never has more than 3 or 4 terms. Use a value of 0 to disable
7577 ** any limit on the number of terms in a compount SELECT.
7579 #ifndef SQLITE_MAX_COMPOUND_SELECT
7580 # define SQLITE_MAX_COMPOUND_SELECT 500
7581 #endif
7584 ** The maximum number of opcodes in a VDBE program.
7585 ** Not currently enforced.
7587 #ifndef SQLITE_MAX_VDBE_OP
7588 # define SQLITE_MAX_VDBE_OP 25000
7589 #endif
7592 ** The maximum number of arguments to an SQL function.
7594 #ifndef SQLITE_MAX_FUNCTION_ARG
7595 # define SQLITE_MAX_FUNCTION_ARG 127
7596 #endif
7599 ** The maximum number of in-memory pages to use for the main database
7600 ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
7602 #ifndef SQLITE_DEFAULT_CACHE_SIZE
7603 # define SQLITE_DEFAULT_CACHE_SIZE 2000
7604 #endif
7605 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
7606 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
7607 #endif
7610 ** The default number of frames to accumulate in the log file before
7611 ** checkpointing the database in WAL mode.
7613 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
7614 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
7615 #endif
7618 ** The maximum number of attached databases. This must be between 0
7619 ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
7620 ** is used internally to track attached databases.
7622 #ifndef SQLITE_MAX_ATTACHED
7623 # define SQLITE_MAX_ATTACHED 10
7624 #endif
7628 ** The maximum value of a ?nnn wildcard that the parser will accept.
7630 #ifndef SQLITE_MAX_VARIABLE_NUMBER
7631 # define SQLITE_MAX_VARIABLE_NUMBER 999
7632 #endif
7634 /* Maximum page size. The upper bound on this value is 65536. This a limit
7635 ** imposed by the use of 16-bit offsets within each page.
7637 ** Earlier versions of SQLite allowed the user to change this value at
7638 ** compile time. This is no longer permitted, on the grounds that it creates
7639 ** a library that is technically incompatible with an SQLite library
7640 ** compiled with a different limit. If a process operating on a database
7641 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
7642 ** compiled with the default page-size limit will not be able to rollback
7643 ** the aborted transaction. This could lead to database corruption.
7645 #ifdef SQLITE_MAX_PAGE_SIZE
7646 # undef SQLITE_MAX_PAGE_SIZE
7647 #endif
7648 #define SQLITE_MAX_PAGE_SIZE 65536
7652 ** The default size of a database page.
7654 #ifndef SQLITE_DEFAULT_PAGE_SIZE
7655 # define SQLITE_DEFAULT_PAGE_SIZE 1024
7656 #endif
7657 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7658 # undef SQLITE_DEFAULT_PAGE_SIZE
7659 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7660 #endif
7663 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
7664 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
7665 ** device characteristics (sector-size and atomic write() support),
7666 ** SQLite may choose a larger value. This constant is the maximum value
7667 ** SQLite will choose on its own.
7669 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
7670 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
7671 #endif
7672 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
7673 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
7674 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
7675 #endif
7679 ** Maximum number of pages in one database file.
7681 ** This is really just the default value for the max_page_count pragma.
7682 ** This value can be lowered (or raised) at run-time using that the
7683 ** max_page_count macro.
7685 #ifndef SQLITE_MAX_PAGE_COUNT
7686 # define SQLITE_MAX_PAGE_COUNT 1073741823
7687 #endif
7690 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
7691 ** operator.
7693 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
7694 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
7695 #endif
7698 ** Maximum depth of recursion for triggers.
7700 ** A value of 1 means that a trigger program will not be able to itself
7701 ** fire any triggers. A value of 0 means that no trigger programs at all
7702 ** may be executed.
7704 #ifndef SQLITE_MAX_TRIGGER_DEPTH
7705 # define SQLITE_MAX_TRIGGER_DEPTH 1000
7706 #endif
7708 /************** End of sqliteLimit.h *****************************************/
7709 /************** Continuing where we left off in sqliteInt.h ******************/
7711 /* Disable nuisance warnings on Borland compilers */
7712 #if defined(__BORLANDC__)
7713 #pragma warn -rch /* unreachable code */
7714 #pragma warn -ccc /* Condition is always true or false */
7715 #pragma warn -aus /* Assigned value is never used */
7716 #pragma warn -csu /* Comparing signed and unsigned */
7717 #pragma warn -spa /* Suspicious pointer arithmetic */
7718 #endif
7720 /* Needed for various definitions... */
7721 #ifndef _GNU_SOURCE
7722 # define _GNU_SOURCE
7723 #endif
7725 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
7726 # define _BSD_SOURCE
7727 #endif
7730 ** Include standard header files as necessary
7732 #ifdef HAVE_STDINT_H
7733 #include <stdint.h>
7734 #endif
7735 #ifdef HAVE_INTTYPES_H
7736 #include <inttypes.h>
7737 #endif
7740 ** The following macros are used to cast pointers to integers and
7741 ** integers to pointers. The way you do this varies from one compiler
7742 ** to the next, so we have developed the following set of #if statements
7743 ** to generate appropriate macros for a wide range of compilers.
7745 ** The correct "ANSI" way to do this is to use the intptr_t type.
7746 ** Unfortunately, that typedef is not available on all compilers, or
7747 ** if it is available, it requires an #include of specific headers
7748 ** that vary from one machine to the next.
7750 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
7751 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
7752 ** So we have to define the macros in different ways depending on the
7753 ** compiler.
7755 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
7756 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
7757 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
7758 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
7759 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
7760 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
7761 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
7762 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
7763 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
7764 #else /* Generates a warning - but it always works */
7765 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
7766 # define SQLITE_PTR_TO_INT(X) ((int)(X))
7767 #endif
7770 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
7771 ** 0 means mutexes are permanently disable and the library is never
7772 ** threadsafe. 1 means the library is serialized which is the highest
7773 ** level of threadsafety. 2 means the library is multithreaded - multiple
7774 ** threads can use SQLite as long as no two threads try to use the same
7775 ** database connection at the same time.
7777 ** Older versions of SQLite used an optional THREADSAFE macro.
7778 ** We support that for legacy.
7780 #if !defined(SQLITE_THREADSAFE)
7781 # if defined(THREADSAFE)
7782 # define SQLITE_THREADSAFE THREADSAFE
7783 # else
7784 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
7785 # endif
7786 #endif
7789 ** Powersafe overwrite is on by default. But can be turned off using
7790 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
7792 #ifndef SQLITE_POWERSAFE_OVERWRITE
7793 # define SQLITE_POWERSAFE_OVERWRITE 1
7794 #endif
7797 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
7798 ** It determines whether or not the features related to
7799 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
7800 ** be overridden at runtime using the sqlite3_config() API.
7802 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
7803 # define SQLITE_DEFAULT_MEMSTATUS 1
7804 #endif
7807 ** Exactly one of the following macros must be defined in order to
7808 ** specify which memory allocation subsystem to use.
7810 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
7811 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
7812 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
7813 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
7815 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
7816 ** assert() macro is enabled, each call into the Win32 native heap subsystem
7817 ** will cause HeapValidate to be called. If heap validation should fail, an
7818 ** assertion will be triggered.
7820 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
7821 ** the default.
7823 #if defined(SQLITE_SYSTEM_MALLOC) \
7824 + defined(SQLITE_WIN32_MALLOC) \
7825 + defined(SQLITE_ZERO_MALLOC) \
7826 + defined(SQLITE_MEMDEBUG)>1
7827 # error "Two or more of the following compile-time configuration options\
7828 are defined but at most one is allowed:\
7829 SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
7830 SQLITE_ZERO_MALLOC"
7831 #endif
7832 #if defined(SQLITE_SYSTEM_MALLOC) \
7833 + defined(SQLITE_WIN32_MALLOC) \
7834 + defined(SQLITE_ZERO_MALLOC) \
7835 + defined(SQLITE_MEMDEBUG)==0
7836 # define SQLITE_SYSTEM_MALLOC 1
7837 #endif
7840 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
7841 ** sizes of memory allocations below this value where possible.
7843 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
7844 # define SQLITE_MALLOC_SOFT_LIMIT 1024
7845 #endif
7848 ** We need to define _XOPEN_SOURCE as follows in order to enable
7849 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
7850 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
7851 ** it.
7853 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
7854 # define _XOPEN_SOURCE 600
7855 #endif
7858 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
7859 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
7860 ** make it true by defining or undefining NDEBUG.
7862 ** Setting NDEBUG makes the code smaller and faster by disabling the
7863 ** assert() statements in the code. So we want the default action
7864 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
7865 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
7866 ** feature.
7868 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
7869 # define NDEBUG 1
7870 #endif
7871 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
7872 # undef NDEBUG
7873 #endif
7876 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
7878 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
7879 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
7880 #endif
7883 ** The testcase() macro is used to aid in coverage testing. When
7884 ** doing coverage testing, the condition inside the argument to
7885 ** testcase() must be evaluated both true and false in order to
7886 ** get full branch coverage. The testcase() macro is inserted
7887 ** to help ensure adequate test coverage in places where simple
7888 ** condition/decision coverage is inadequate. For example, testcase()
7889 ** can be used to make sure boundary values are tested. For
7890 ** bitmask tests, testcase() can be used to make sure each bit
7891 ** is significant and used at least once. On switch statements
7892 ** where multiple cases go to the same block of code, testcase()
7893 ** can insure that all cases are evaluated.
7896 #ifdef SQLITE_COVERAGE_TEST
7897 SQLITE_PRIVATE void sqlite3Coverage(int);
7898 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
7899 #else
7900 # define testcase(X)
7901 #endif
7904 ** The TESTONLY macro is used to enclose variable declarations or
7905 ** other bits of code that are needed to support the arguments
7906 ** within testcase() and assert() macros.
7908 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
7909 # define TESTONLY(X) X
7910 #else
7911 # define TESTONLY(X)
7912 #endif
7915 ** Sometimes we need a small amount of code such as a variable initialization
7916 ** to setup for a later assert() statement. We do not want this code to
7917 ** appear when assert() is disabled. The following macro is therefore
7918 ** used to contain that setup code. The "VVA" acronym stands for
7919 ** "Verification, Validation, and Accreditation". In other words, the
7920 ** code within VVA_ONLY() will only run during verification processes.
7922 #ifndef NDEBUG
7923 # define VVA_ONLY(X) X
7924 #else
7925 # define VVA_ONLY(X)
7926 #endif
7929 ** The ALWAYS and NEVER macros surround boolean expressions which
7930 ** are intended to always be true or false, respectively. Such
7931 ** expressions could be omitted from the code completely. But they
7932 ** are included in a few cases in order to enhance the resilience
7933 ** of SQLite to unexpected behavior - to make the code "self-healing"
7934 ** or "ductile" rather than being "brittle" and crashing at the first
7935 ** hint of unplanned behavior.
7937 ** In other words, ALWAYS and NEVER are added for defensive code.
7939 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
7940 ** be true and false so that the unreachable code they specify will
7941 ** not be counted as untested code.
7943 #if defined(SQLITE_COVERAGE_TEST)
7944 # define ALWAYS(X) (1)
7945 # define NEVER(X) (0)
7946 #elif !defined(NDEBUG)
7947 # define ALWAYS(X) ((X)?1:(assert(0),0))
7948 # define NEVER(X) ((X)?(assert(0),1):0)
7949 #else
7950 # define ALWAYS(X) (X)
7951 # define NEVER(X) (X)
7952 #endif
7955 ** Return true (non-zero) if the input is a integer that is too large
7956 ** to fit in 32-bits. This macro is used inside of various testcase()
7957 ** macros to verify that we have tested SQLite for large-file support.
7959 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
7962 ** The macro unlikely() is a hint that surrounds a boolean
7963 ** expression that is usually false. Macro likely() surrounds
7964 ** a boolean expression that is usually true. These hints could,
7965 ** in theory, be used by the compiler to generate better code, but
7966 ** currently they are just comments for human readers.
7968 #define likely(X) (X)
7969 #define unlikely(X) (X)
7971 /************** Include hash.h in the middle of sqliteInt.h ******************/
7972 /************** Begin file hash.h ********************************************/
7974 ** 2001 September 22
7976 ** The author disclaims copyright to this source code. In place of
7977 ** a legal notice, here is a blessing:
7979 ** May you do good and not evil.
7980 ** May you find forgiveness for yourself and forgive others.
7981 ** May you share freely, never taking more than you give.
7983 *************************************************************************
7984 ** This is the header file for the generic hash-table implementation
7985 ** used in SQLite.
7987 #ifndef _SQLITE_HASH_H_
7988 #define _SQLITE_HASH_H_
7990 /* Forward declarations of structures. */
7991 typedef struct Hash Hash;
7992 typedef struct HashElem HashElem;
7994 /* A complete hash table is an instance of the following structure.
7995 ** The internals of this structure are intended to be opaque -- client
7996 ** code should not attempt to access or modify the fields of this structure
7997 ** directly. Change this structure only by using the routines below.
7998 ** However, some of the "procedures" and "functions" for modifying and
7999 ** accessing this structure are really macros, so we can't really make
8000 ** this structure opaque.
8002 ** All elements of the hash table are on a single doubly-linked list.
8003 ** Hash.first points to the head of this list.
8005 ** There are Hash.htsize buckets. Each bucket points to a spot in
8006 ** the global doubly-linked list. The contents of the bucket are the
8007 ** element pointed to plus the next _ht.count-1 elements in the list.
8009 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
8010 ** by a linear search of the global list. For small tables, the
8011 ** Hash.ht table is never allocated because if there are few elements
8012 ** in the table, it is faster to do a linear search than to manage
8013 ** the hash table.
8015 struct Hash {
8016 unsigned int htsize; /* Number of buckets in the hash table */
8017 unsigned int count; /* Number of entries in this table */
8018 HashElem *first; /* The first element of the array */
8019 struct _ht { /* the hash table */
8020 int count; /* Number of entries with this hash */
8021 HashElem *chain; /* Pointer to first entry with this hash */
8022 } *ht;
8025 /* Each element in the hash table is an instance of the following
8026 ** structure. All elements are stored on a single doubly-linked list.
8028 ** Again, this structure is intended to be opaque, but it can't really
8029 ** be opaque because it is used by macros.
8031 struct HashElem {
8032 HashElem *next, *prev; /* Next and previous elements in the table */
8033 void *data; /* Data associated with this element */
8034 const char *pKey; int nKey; /* Key associated with this element */
8038 ** Access routines. To delete, insert a NULL pointer.
8040 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8041 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
8042 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
8043 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8046 ** Macros for looping over all elements of a hash table. The idiom is
8047 ** like this:
8049 ** Hash h;
8050 ** HashElem *p;
8051 ** ...
8052 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8053 ** SomeStructure *pData = sqliteHashData(p);
8054 ** // do something with pData
8055 ** }
8057 #define sqliteHashFirst(H) ((H)->first)
8058 #define sqliteHashNext(E) ((E)->next)
8059 #define sqliteHashData(E) ((E)->data)
8060 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
8061 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
8064 ** Number of entries in a hash table
8066 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
8068 #endif /* _SQLITE_HASH_H_ */
8070 /************** End of hash.h ************************************************/
8071 /************** Continuing where we left off in sqliteInt.h ******************/
8072 /************** Include parse.h in the middle of sqliteInt.h *****************/
8073 /************** Begin file parse.h *******************************************/
8074 #define TK_SEMI 1
8075 #define TK_EXPLAIN 2
8076 #define TK_QUERY 3
8077 #define TK_PLAN 4
8078 #define TK_BEGIN 5
8079 #define TK_TRANSACTION 6
8080 #define TK_DEFERRED 7
8081 #define TK_IMMEDIATE 8
8082 #define TK_EXCLUSIVE 9
8083 #define TK_COMMIT 10
8084 #define TK_END 11
8085 #define TK_ROLLBACK 12
8086 #define TK_SAVEPOINT 13
8087 #define TK_RELEASE 14
8088 #define TK_TO 15
8089 #define TK_TABLE 16
8090 #define TK_CREATE 17
8091 #define TK_IF 18
8092 #define TK_NOT 19
8093 #define TK_EXISTS 20
8094 #define TK_TEMP 21
8095 #define TK_LP 22
8096 #define TK_RP 23
8097 #define TK_AS 24
8098 #define TK_WITHOUT 25
8099 #define TK_COMMA 26
8100 #define TK_ID 27
8101 #define TK_INDEXED 28
8102 #define TK_ABORT 29
8103 #define TK_ACTION 30
8104 #define TK_AFTER 31
8105 #define TK_ANALYZE 32
8106 #define TK_ASC 33
8107 #define TK_ATTACH 34
8108 #define TK_BEFORE 35
8109 #define TK_BY 36
8110 #define TK_CASCADE 37
8111 #define TK_CAST 38
8112 #define TK_COLUMNKW 39
8113 #define TK_CONFLICT 40
8114 #define TK_DATABASE 41
8115 #define TK_DESC 42
8116 #define TK_DETACH 43
8117 #define TK_EACH 44
8118 #define TK_FAIL 45
8119 #define TK_FOR 46
8120 #define TK_IGNORE 47
8121 #define TK_INITIALLY 48
8122 #define TK_INSTEAD 49
8123 #define TK_LIKE_KW 50
8124 #define TK_MATCH 51
8125 #define TK_NO 52
8126 #define TK_KEY 53
8127 #define TK_OF 54
8128 #define TK_OFFSET 55
8129 #define TK_PRAGMA 56
8130 #define TK_RAISE 57
8131 #define TK_RECURSIVE 58
8132 #define TK_REPLACE 59
8133 #define TK_RESTRICT 60
8134 #define TK_ROW 61
8135 #define TK_TRIGGER 62
8136 #define TK_VACUUM 63
8137 #define TK_VIEW 64
8138 #define TK_VIRTUAL 65
8139 #define TK_WITH 66
8140 #define TK_REINDEX 67
8141 #define TK_RENAME 68
8142 #define TK_CTIME_KW 69
8143 #define TK_ANY 70
8144 #define TK_OR 71
8145 #define TK_AND 72
8146 #define TK_IS 73
8147 #define TK_BETWEEN 74
8148 #define TK_IN 75
8149 #define TK_ISNULL 76
8150 #define TK_NOTNULL 77
8151 #define TK_NE 78
8152 #define TK_EQ 79
8153 #define TK_GT 80
8154 #define TK_LE 81
8155 #define TK_LT 82
8156 #define TK_GE 83
8157 #define TK_ESCAPE 84
8158 #define TK_BITAND 85
8159 #define TK_BITOR 86
8160 #define TK_LSHIFT 87
8161 #define TK_RSHIFT 88
8162 #define TK_PLUS 89
8163 #define TK_MINUS 90
8164 #define TK_STAR 91
8165 #define TK_SLASH 92
8166 #define TK_REM 93
8167 #define TK_CONCAT 94
8168 #define TK_COLLATE 95
8169 #define TK_BITNOT 96
8170 #define TK_STRING 97
8171 #define TK_JOIN_KW 98
8172 #define TK_CONSTRAINT 99
8173 #define TK_DEFAULT 100
8174 #define TK_NULL 101
8175 #define TK_PRIMARY 102
8176 #define TK_UNIQUE 103
8177 #define TK_CHECK 104
8178 #define TK_REFERENCES 105
8179 #define TK_AUTOINCR 106
8180 #define TK_ON 107
8181 #define TK_INSERT 108
8182 #define TK_DELETE 109
8183 #define TK_UPDATE 110
8184 #define TK_SET 111
8185 #define TK_DEFERRABLE 112
8186 #define TK_FOREIGN 113
8187 #define TK_DROP 114
8188 #define TK_UNION 115
8189 #define TK_ALL 116
8190 #define TK_EXCEPT 117
8191 #define TK_INTERSECT 118
8192 #define TK_SELECT 119
8193 #define TK_VALUES 120
8194 #define TK_DISTINCT 121
8195 #define TK_DOT 122
8196 #define TK_FROM 123
8197 #define TK_JOIN 124
8198 #define TK_USING 125
8199 #define TK_ORDER 126
8200 #define TK_GROUP 127
8201 #define TK_HAVING 128
8202 #define TK_LIMIT 129
8203 #define TK_WHERE 130
8204 #define TK_INTO 131
8205 #define TK_INTEGER 132
8206 #define TK_FLOAT 133
8207 #define TK_BLOB 134
8208 #define TK_VARIABLE 135
8209 #define TK_CASE 136
8210 #define TK_WHEN 137
8211 #define TK_THEN 138
8212 #define TK_ELSE 139
8213 #define TK_INDEX 140
8214 #define TK_ALTER 141
8215 #define TK_ADD 142
8216 #define TK_TO_TEXT 143
8217 #define TK_TO_BLOB 144
8218 #define TK_TO_NUMERIC 145
8219 #define TK_TO_INT 146
8220 #define TK_TO_REAL 147
8221 #define TK_ISNOT 148
8222 #define TK_END_OF_FILE 149
8223 #define TK_ILLEGAL 150
8224 #define TK_SPACE 151
8225 #define TK_UNCLOSED_STRING 152
8226 #define TK_FUNCTION 153
8227 #define TK_COLUMN 154
8228 #define TK_AGG_FUNCTION 155
8229 #define TK_AGG_COLUMN 156
8230 #define TK_UMINUS 157
8231 #define TK_UPLUS 158
8232 #define TK_REGISTER 159
8234 /************** End of parse.h ***********************************************/
8235 /************** Continuing where we left off in sqliteInt.h ******************/
8236 #include <stdio.h>
8237 #include <stdlib.h>
8238 #include <string.h>
8239 #include <assert.h>
8240 #include <stddef.h>
8243 ** If compiling for a processor that lacks floating point support,
8244 ** substitute integer for floating-point
8246 #ifdef SQLITE_OMIT_FLOATING_POINT
8247 # define double sqlite_int64
8248 # define float sqlite_int64
8249 # define LONGDOUBLE_TYPE sqlite_int64
8250 # ifndef SQLITE_BIG_DBL
8251 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8252 # endif
8253 # define SQLITE_OMIT_DATETIME_FUNCS 1
8254 # define SQLITE_OMIT_TRACE 1
8255 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8256 # undef SQLITE_HAVE_ISNAN
8257 #endif
8258 #ifndef SQLITE_BIG_DBL
8259 # define SQLITE_BIG_DBL (1e99)
8260 #endif
8263 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8264 ** afterward. Having this macro allows us to cause the C compiler
8265 ** to omit code used by TEMP tables without messy #ifndef statements.
8267 #ifdef SQLITE_OMIT_TEMPDB
8268 #define OMIT_TEMPDB 1
8269 #else
8270 #define OMIT_TEMPDB 0
8271 #endif
8274 ** The "file format" number is an integer that is incremented whenever
8275 ** the VDBE-level file format changes. The following macros define the
8276 ** the default file format for new databases and the maximum file format
8277 ** that the library can read.
8279 #define SQLITE_MAX_FILE_FORMAT 4
8280 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8281 # define SQLITE_DEFAULT_FILE_FORMAT 4
8282 #endif
8285 ** Determine whether triggers are recursive by default. This can be
8286 ** changed at run-time using a pragma.
8288 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8289 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8290 #endif
8293 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8294 ** on the command-line
8296 #ifndef SQLITE_TEMP_STORE
8297 # define SQLITE_TEMP_STORE 1
8298 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
8299 #endif
8302 ** GCC does not define the offsetof() macro so we'll have to do it
8303 ** ourselves.
8305 #ifndef offsetof
8306 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8307 #endif
8310 ** Macros to compute minimum and maximum of two numbers.
8312 #define MIN(A,B) ((A)<(B)?(A):(B))
8313 #define MAX(A,B) ((A)>(B)?(A):(B))
8316 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
8317 ** not, there are still machines out there that use EBCDIC.)
8319 #if 'A' == '\301'
8320 # define SQLITE_EBCDIC 1
8321 #else
8322 # define SQLITE_ASCII 1
8323 #endif
8326 ** Integers of known sizes. These typedefs might change for architectures
8327 ** where the sizes very. Preprocessor macros are available so that the
8328 ** types can be conveniently redefined at compile-type. Like this:
8330 ** cc '-DUINTPTR_TYPE=long long int' ...
8332 #ifndef UINT32_TYPE
8333 # ifdef HAVE_UINT32_T
8334 # define UINT32_TYPE uint32_t
8335 # else
8336 # define UINT32_TYPE unsigned int
8337 # endif
8338 #endif
8339 #ifndef UINT16_TYPE
8340 # ifdef HAVE_UINT16_T
8341 # define UINT16_TYPE uint16_t
8342 # else
8343 # define UINT16_TYPE unsigned short int
8344 # endif
8345 #endif
8346 #ifndef INT16_TYPE
8347 # ifdef HAVE_INT16_T
8348 # define INT16_TYPE int16_t
8349 # else
8350 # define INT16_TYPE short int
8351 # endif
8352 #endif
8353 #ifndef UINT8_TYPE
8354 # ifdef HAVE_UINT8_T
8355 # define UINT8_TYPE uint8_t
8356 # else
8357 # define UINT8_TYPE unsigned char
8358 # endif
8359 #endif
8360 #ifndef INT8_TYPE
8361 # ifdef HAVE_INT8_T
8362 # define INT8_TYPE int8_t
8363 # else
8364 # define INT8_TYPE signed char
8365 # endif
8366 #endif
8367 #ifndef LONGDOUBLE_TYPE
8368 # define LONGDOUBLE_TYPE long double
8369 #endif
8370 typedef sqlite_int64 i64; /* 8-byte signed integer */
8371 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
8372 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
8373 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
8374 typedef INT16_TYPE i16; /* 2-byte signed integer */
8375 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
8376 typedef INT8_TYPE i8; /* 1-byte signed integer */
8379 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8380 ** that can be stored in a u32 without loss of data. The value
8381 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
8382 ** have to specify the value in the less intuitive manner shown:
8384 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
8387 ** The datatype used to store estimates of the number of rows in a
8388 ** table or index. This is an unsigned integer type. For 99.9% of
8389 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
8390 ** can be used at compile-time if desired.
8392 #ifdef SQLITE_64BIT_STATS
8393 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
8394 #else
8395 typedef u32 tRowcnt; /* 32-bit is the default */
8396 #endif
8399 ** Estimated quantities used for query planning are stored as 16-bit
8400 ** logarithms. For quantity X, the value stored is 10*log2(X). This
8401 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
8402 ** But the allowed values are "grainy". Not every value is representable.
8403 ** For example, quantities 16 and 17 are both represented by a LogEst
8404 ** of 40. However, since LogEst quantatites are suppose to be estimates,
8405 ** not exact values, this imprecision is not a problem.
8407 ** "LogEst" is short for "Logarithimic Estimate".
8409 ** Examples:
8410 ** 1 -> 0 20 -> 43 10000 -> 132
8411 ** 2 -> 10 25 -> 46 25000 -> 146
8412 ** 3 -> 16 100 -> 66 1000000 -> 199
8413 ** 4 -> 20 1000 -> 99 1048576 -> 200
8414 ** 10 -> 33 1024 -> 100 4294967296 -> 320
8416 ** The LogEst can be negative to indicate fractional values.
8417 ** Examples:
8419 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
8421 typedef INT16_TYPE LogEst;
8424 ** Macros to determine whether the machine is big or little endian,
8425 ** evaluated at runtime.
8427 #ifdef SQLITE_AMALGAMATION
8428 SQLITE_PRIVATE const int sqlite3one = 1;
8429 #else
8430 SQLITE_PRIVATE const int sqlite3one;
8431 #endif
8432 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8433 || defined(__x86_64) || defined(__x86_64__)
8434 # define SQLITE_BIGENDIAN 0
8435 # define SQLITE_LITTLEENDIAN 1
8436 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
8437 #else
8438 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
8439 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8440 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8441 #endif
8444 ** Constants for the largest and smallest possible 64-bit signed integers.
8445 ** These macros are designed to work correctly on both 32-bit and 64-bit
8446 ** compilers.
8448 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
8449 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8452 ** Round up a number to the next larger multiple of 8. This is used
8453 ** to force 8-byte alignment on 64-bit architectures.
8455 #define ROUND8(x) (((x)+7)&~7)
8458 ** Round down to the nearest multiple of 8
8460 #define ROUNDDOWN8(x) ((x)&~7)
8463 ** Assert that the pointer X is aligned to an 8-byte boundary. This
8464 ** macro is used only within assert() to verify that the code gets
8465 ** all alignment restrictions correct.
8467 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8468 ** underlying malloc() implemention might return us 4-byte aligned
8469 ** pointers. In that case, only verify 4-byte alignment.
8471 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8472 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
8473 #else
8474 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
8475 #endif
8478 ** Disable MMAP on platforms where it is known to not work
8480 #if defined(__OpenBSD__) || defined(__QNXNTO__)
8481 # undef SQLITE_MAX_MMAP_SIZE
8482 # define SQLITE_MAX_MMAP_SIZE 0
8483 #endif
8486 ** Default maximum size of memory used by memory-mapped I/O in the VFS
8488 #ifdef __APPLE__
8489 # include <TargetConditionals.h>
8490 # if TARGET_OS_IPHONE
8491 # undef SQLITE_MAX_MMAP_SIZE
8492 # define SQLITE_MAX_MMAP_SIZE 0
8493 # endif
8494 #endif
8495 #ifndef SQLITE_MAX_MMAP_SIZE
8496 # if defined(__linux__) \
8497 || defined(_WIN32) \
8498 || (defined(__APPLE__) && defined(__MACH__)) \
8499 || defined(__sun)
8500 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
8501 # else
8502 # define SQLITE_MAX_MMAP_SIZE 0
8503 # endif
8504 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8505 #endif
8508 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
8509 ** default MMAP_SIZE is specified at compile-time, make sure that it does
8510 ** not exceed the maximum mmap size.
8512 #ifndef SQLITE_DEFAULT_MMAP_SIZE
8513 # define SQLITE_DEFAULT_MMAP_SIZE 0
8514 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
8515 #endif
8516 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8517 # undef SQLITE_DEFAULT_MMAP_SIZE
8518 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8519 #endif
8522 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
8523 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
8524 ** define SQLITE_ENABLE_STAT3_OR_STAT4
8526 #ifdef SQLITE_ENABLE_STAT4
8527 # undef SQLITE_ENABLE_STAT3
8528 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8529 #elif SQLITE_ENABLE_STAT3
8530 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
8531 #elif SQLITE_ENABLE_STAT3_OR_STAT4
8532 # undef SQLITE_ENABLE_STAT3_OR_STAT4
8533 #endif
8536 ** An instance of the following structure is used to store the busy-handler
8537 ** callback for a given sqlite handle.
8539 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8540 ** callback for the database handle. Each pager opened via the sqlite
8541 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8542 ** callback is currently invoked only from within pager.c.
8544 typedef struct BusyHandler BusyHandler;
8545 struct BusyHandler {
8546 int (*xFunc)(void *,int); /* The busy callback */
8547 void *pArg; /* First arg to busy callback */
8548 int nBusy; /* Incremented with each busy call */
8552 ** Name of the master database table. The master database table
8553 ** is a special table that holds the names and attributes of all
8554 ** user tables and indices.
8556 #define MASTER_NAME "sqlite_master"
8557 #define TEMP_MASTER_NAME "sqlite_temp_master"
8560 ** The root-page of the master database table.
8562 #define MASTER_ROOT 1
8565 ** The name of the schema table.
8567 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8570 ** A convenience macro that returns the number of elements in
8571 ** an array.
8573 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
8576 ** Determine if the argument is a power of two
8578 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8581 ** The following value as a destructor means to use sqlite3DbFree().
8582 ** The sqlite3DbFree() routine requires two parameters instead of the
8583 ** one parameter that destructors normally want. So we have to introduce
8584 ** this magic value that the code knows to handle differently. Any
8585 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8586 ** and SQLITE_TRANSIENT.
8588 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
8591 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8592 ** not support Writable Static Data (WSD) such as global and static variables.
8593 ** All variables must either be on the stack or dynamically allocated from
8594 ** the heap. When WSD is unsupported, the variable declarations scattered
8595 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
8596 ** macro is used for this purpose. And instead of referencing the variable
8597 ** directly, we use its constant as a key to lookup the run-time allocated
8598 ** buffer that holds real variable. The constant is also the initializer
8599 ** for the run-time allocated buffer.
8601 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8602 ** macros become no-ops and have zero performance impact.
8604 #ifdef SQLITE_OMIT_WSD
8605 #define SQLITE_WSD const
8606 #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8607 #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8608 SQLITE_API int sqlite3_wsd_init(int N, int J);
8609 SQLITE_API void *sqlite3_wsd_find(void *K, int L);
8610 #else
8611 #define SQLITE_WSD
8612 #define GLOBAL(t,v) v
8613 #define sqlite3GlobalConfig sqlite3Config
8614 #endif
8617 ** The following macros are used to suppress compiler warnings and to
8618 ** make it clear to human readers when a function parameter is deliberately
8619 ** left unused within the body of a function. This usually happens when
8620 ** a function is called via a function pointer. For example the
8621 ** implementation of an SQL aggregate step callback may not use the
8622 ** parameter indicating the number of arguments passed to the aggregate,
8623 ** if it knows that this is enforced elsewhere.
8625 ** When a function parameter is not used at all within the body of a function,
8626 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8627 ** However, these macros may also be used to suppress warnings related to
8628 ** parameters that may or may not be used depending on compilation options.
8629 ** For example those parameters only used in assert() statements. In these
8630 ** cases the parameters are named as per the usual conventions.
8632 #define UNUSED_PARAMETER(x) (void)(x)
8633 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8636 ** Forward references to structures
8638 typedef struct AggInfo AggInfo;
8639 typedef struct AuthContext AuthContext;
8640 typedef struct AutoincInfo AutoincInfo;
8641 typedef struct Bitvec Bitvec;
8642 typedef struct CollSeq CollSeq;
8643 typedef struct Column Column;
8644 typedef struct Db Db;
8645 typedef struct Schema Schema;
8646 typedef struct Expr Expr;
8647 typedef struct ExprList ExprList;
8648 typedef struct ExprSpan ExprSpan;
8649 typedef struct FKey FKey;
8650 typedef struct FuncDestructor FuncDestructor;
8651 typedef struct FuncDef FuncDef;
8652 typedef struct FuncDefHash FuncDefHash;
8653 typedef struct IdList IdList;
8654 typedef struct Index Index;
8655 typedef struct IndexSample IndexSample;
8656 typedef struct KeyClass KeyClass;
8657 typedef struct KeyInfo KeyInfo;
8658 typedef struct Lookaside Lookaside;
8659 typedef struct LookasideSlot LookasideSlot;
8660 typedef struct Module Module;
8661 typedef struct NameContext NameContext;
8662 typedef struct Parse Parse;
8663 typedef struct PrintfArguments PrintfArguments;
8664 typedef struct RowSet RowSet;
8665 typedef struct Savepoint Savepoint;
8666 typedef struct Select Select;
8667 typedef struct SelectDest SelectDest;
8668 typedef struct SrcList SrcList;
8669 typedef struct StrAccum StrAccum;
8670 typedef struct Table Table;
8671 typedef struct TableLock TableLock;
8672 typedef struct Token Token;
8673 typedef struct Trigger Trigger;
8674 typedef struct TriggerPrg TriggerPrg;
8675 typedef struct TriggerStep TriggerStep;
8676 typedef struct UnpackedRecord UnpackedRecord;
8677 typedef struct VTable VTable;
8678 typedef struct VtabCtx VtabCtx;
8679 typedef struct Walker Walker;
8680 typedef struct WhereInfo WhereInfo;
8681 typedef struct With With;
8684 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
8685 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8686 ** pointer types (i.e. FuncDef) defined above.
8688 /************** Include btree.h in the middle of sqliteInt.h *****************/
8689 /************** Begin file btree.h *******************************************/
8691 ** 2001 September 15
8693 ** The author disclaims copyright to this source code. In place of
8694 ** a legal notice, here is a blessing:
8696 ** May you do good and not evil.
8697 ** May you find forgiveness for yourself and forgive others.
8698 ** May you share freely, never taking more than you give.
8700 *************************************************************************
8701 ** This header file defines the interface that the sqlite B-Tree file
8702 ** subsystem. See comments in the source code for a detailed description
8703 ** of what each interface routine does.
8705 #ifndef _BTREE_H_
8706 #define _BTREE_H_
8708 /* TODO: This definition is just included so other modules compile. It
8709 ** needs to be revisited.
8711 #define SQLITE_N_BTREE_META 10
8714 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8715 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8717 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8718 #define SQLITE_DEFAULT_AUTOVACUUM 0
8719 #endif
8721 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
8722 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
8723 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
8726 ** Forward declarations of structure
8728 typedef struct Btree Btree;
8729 typedef struct BtCursor BtCursor;
8730 typedef struct BtShared BtShared;
8733 SQLITE_PRIVATE int sqlite3BtreeOpen(
8734 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
8735 const char *zFilename, /* Name of database file to open */
8736 sqlite3 *db, /* Associated database connection */
8737 Btree **ppBtree, /* Return open Btree* here */
8738 int flags, /* Flags */
8739 int vfsFlags /* Flags passed through to VFS open */
8742 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8743 ** following values.
8745 ** NOTE: These values must match the corresponding PAGER_ values in
8746 ** pager.h.
8748 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
8749 #define BTREE_MEMORY 2 /* This is an in-memory DB */
8750 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
8751 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
8753 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8754 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8755 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
8756 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
8757 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8758 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8759 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8760 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8761 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8762 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8763 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8764 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8765 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8766 #endif
8767 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8768 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8769 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8770 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8771 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8772 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8773 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8774 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8775 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8776 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8777 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8778 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8779 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8780 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8781 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8782 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8784 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8785 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8786 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8788 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8790 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8791 ** of the flags shown below.
8793 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8794 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8795 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
8796 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8797 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
8798 ** indices.)
8800 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
8801 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
8803 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8804 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8805 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8807 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8808 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8810 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8813 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8814 ** should be one of the following values. The integer values are assigned
8815 ** to constants so that the offset of the corresponding field in an
8816 ** SQLite database header may be found using the following formula:
8818 ** offset = 36 + (idx * 4)
8820 ** For example, the free-page-count field is located at byte offset 36 of
8821 ** the database file header. The incr-vacuum-flag field is located at
8822 ** byte offset 64 (== 36+4*7).
8824 #define BTREE_FREE_PAGE_COUNT 0
8825 #define BTREE_SCHEMA_VERSION 1
8826 #define BTREE_FILE_FORMAT 2
8827 #define BTREE_DEFAULT_CACHE_SIZE 3
8828 #define BTREE_LARGEST_ROOT_PAGE 4
8829 #define BTREE_TEXT_ENCODING 5
8830 #define BTREE_USER_VERSION 6
8831 #define BTREE_INCR_VACUUM 7
8832 #define BTREE_APPLICATION_ID 8
8835 ** Values that may be OR'd together to form the second argument of an
8836 ** sqlite3BtreeCursorHints() call.
8838 #define BTREE_BULKLOAD 0x00000001
8840 SQLITE_PRIVATE int sqlite3BtreeCursor(
8841 Btree*, /* BTree containing table to open */
8842 int iTable, /* Index of root page */
8843 int wrFlag, /* 1 for writing. 0 for read-only */
8844 struct KeyInfo*, /* First argument to compare function */
8845 BtCursor *pCursor /* Space to write cursor structure */
8847 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8848 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8850 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8851 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8852 BtCursor*,
8853 UnpackedRecord *pUnKey,
8854 i64 intKey,
8855 int bias,
8856 int *pRes
8858 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8859 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8860 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8861 const void *pData, int nData,
8862 int nZero, int bias, int seekResult);
8863 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8864 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8865 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8866 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8867 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8868 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8869 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8870 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
8871 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
8872 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8873 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8874 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8875 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8877 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8878 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8880 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8881 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8882 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8883 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8884 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8886 #ifndef NDEBUG
8887 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8888 #endif
8890 #ifndef SQLITE_OMIT_BTREECOUNT
8891 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8892 #endif
8894 #ifdef SQLITE_TEST
8895 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8896 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8897 #endif
8899 #ifndef SQLITE_OMIT_WAL
8900 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8901 #endif
8904 ** If we are not using shared cache, then there is no need to
8905 ** use mutexes to access the BtShared structures. So make the
8906 ** Enter and Leave procedures no-ops.
8908 #ifndef SQLITE_OMIT_SHARED_CACHE
8909 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
8910 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
8911 #else
8912 # define sqlite3BtreeEnter(X)
8913 # define sqlite3BtreeEnterAll(X)
8914 #endif
8916 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8917 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
8918 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
8919 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
8920 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
8921 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
8922 #ifndef NDEBUG
8923 /* These routines are used inside assert() statements only. */
8924 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
8925 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8926 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8927 #endif
8928 #else
8930 # define sqlite3BtreeSharable(X) 0
8931 # define sqlite3BtreeLeave(X)
8932 # define sqlite3BtreeEnterCursor(X)
8933 # define sqlite3BtreeLeaveCursor(X)
8934 # define sqlite3BtreeLeaveAll(X)
8936 # define sqlite3BtreeHoldsMutex(X) 1
8937 # define sqlite3BtreeHoldsAllMutexes(X) 1
8938 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8939 #endif
8942 #endif /* _BTREE_H_ */
8944 /************** End of btree.h ***********************************************/
8945 /************** Continuing where we left off in sqliteInt.h ******************/
8946 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8947 /************** Begin file vdbe.h ********************************************/
8949 ** 2001 September 15
8951 ** The author disclaims copyright to this source code. In place of
8952 ** a legal notice, here is a blessing:
8954 ** May you do good and not evil.
8955 ** May you find forgiveness for yourself and forgive others.
8956 ** May you share freely, never taking more than you give.
8958 *************************************************************************
8959 ** Header file for the Virtual DataBase Engine (VDBE)
8961 ** This header defines the interface to the virtual database engine
8962 ** or VDBE. The VDBE implements an abstract machine that runs a
8963 ** simple program to access and modify the underlying database.
8965 #ifndef _SQLITE_VDBE_H_
8966 #define _SQLITE_VDBE_H_
8967 /* #include <stdio.h> */
8970 ** A single VDBE is an opaque structure named "Vdbe". Only routines
8971 ** in the source file sqliteVdbe.c are allowed to see the insides
8972 ** of this structure.
8974 typedef struct Vdbe Vdbe;
8977 ** The names of the following types declared in vdbeInt.h are required
8978 ** for the VdbeOp definition.
8980 typedef struct Mem Mem;
8981 typedef struct SubProgram SubProgram;
8984 ** A single instruction of the virtual machine has an opcode
8985 ** and as many as three operands. The instruction is recorded
8986 ** as an instance of the following structure:
8988 struct VdbeOp {
8989 u8 opcode; /* What operation to perform */
8990 signed char p4type; /* One of the P4_xxx constants for p4 */
8991 u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
8992 u8 p5; /* Fifth parameter is an unsigned character */
8993 int p1; /* First operand */
8994 int p2; /* Second parameter (often the jump destination) */
8995 int p3; /* The third parameter */
8996 union { /* fourth parameter */
8997 int i; /* Integer value if p4type==P4_INT32 */
8998 void *p; /* Generic pointer */
8999 char *z; /* Pointer to data for string (char array) types */
9000 i64 *pI64; /* Used when p4type is P4_INT64 */
9001 double *pReal; /* Used when p4type is P4_REAL */
9002 FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
9003 CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
9004 Mem *pMem; /* Used when p4type is P4_MEM */
9005 VTable *pVtab; /* Used when p4type is P4_VTAB */
9006 KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
9007 int *ai; /* Used when p4type is P4_INTARRAY */
9008 SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
9009 int (*xAdvance)(BtCursor *, int *);
9010 } p4;
9011 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9012 char *zComment; /* Comment to improve readability */
9013 #endif
9014 #ifdef VDBE_PROFILE
9015 int cnt; /* Number of times this instruction was executed */
9016 u64 cycles; /* Total time spent executing this instruction */
9017 #endif
9019 typedef struct VdbeOp VdbeOp;
9023 ** A sub-routine used to implement a trigger program.
9025 struct SubProgram {
9026 VdbeOp *aOp; /* Array of opcodes for sub-program */
9027 int nOp; /* Elements in aOp[] */
9028 int nMem; /* Number of memory cells required */
9029 int nCsr; /* Number of cursors required */
9030 int nOnce; /* Number of OP_Once instructions */
9031 void *token; /* id that may be used to recursive triggers */
9032 SubProgram *pNext; /* Next sub-program already visited */
9036 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9037 ** it takes up less space.
9039 struct VdbeOpList {
9040 u8 opcode; /* What operation to perform */
9041 signed char p1; /* First operand */
9042 signed char p2; /* Second parameter (often the jump destination) */
9043 signed char p3; /* Third parameter */
9045 typedef struct VdbeOpList VdbeOpList;
9048 ** Allowed values of VdbeOp.p4type
9050 #define P4_NOTUSED 0 /* The P4 parameter is not used */
9051 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
9052 #define P4_STATIC (-2) /* Pointer to a static string */
9053 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
9054 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
9055 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
9056 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
9057 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
9058 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9059 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9060 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
9061 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
9062 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
9063 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9064 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
9065 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9067 /* Error message codes for OP_Halt */
9068 #define P5_ConstraintNotNull 1
9069 #define P5_ConstraintUnique 2
9070 #define P5_ConstraintCheck 3
9071 #define P5_ConstraintFK 4
9074 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
9075 ** number of columns of data returned by the statement.
9077 #define COLNAME_NAME 0
9078 #define COLNAME_DECLTYPE 1
9079 #define COLNAME_DATABASE 2
9080 #define COLNAME_TABLE 3
9081 #define COLNAME_COLUMN 4
9082 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9083 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
9084 #else
9085 # ifdef SQLITE_OMIT_DECLTYPE
9086 # define COLNAME_N 1 /* Store only the name */
9087 # else
9088 # define COLNAME_N 2 /* Store the name and decltype */
9089 # endif
9090 #endif
9093 ** The following macro converts a relative address in the p2 field
9094 ** of a VdbeOp structure into a negative number so that
9095 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
9096 ** the macro again restores the address.
9098 #define ADDR(X) (-1-(X))
9101 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9102 ** header file that defines a number for each opcode used by the VDBE.
9104 /************** Include opcodes.h in the middle of vdbe.h ********************/
9105 /************** Begin file opcodes.h *****************************************/
9106 /* Automatically generated. Do not edit */
9107 /* See the mkopcodeh.awk script for details */
9108 #define OP_Function 1 /* synopsis: r[P3]=func(r[P2@P5]) */
9109 #define OP_Savepoint 2
9110 #define OP_AutoCommit 3
9111 #define OP_Transaction 4
9112 #define OP_SorterNext 5
9113 #define OP_PrevIfOpen 6
9114 #define OP_NextIfOpen 7
9115 #define OP_Prev 8
9116 #define OP_Next 9
9117 #define OP_AggStep 10 /* synopsis: accum=r[P3] step(r[P2@P5]) */
9118 #define OP_Checkpoint 11
9119 #define OP_JournalMode 12
9120 #define OP_Vacuum 13
9121 #define OP_VFilter 14 /* synopsis: iPlan=r[P3] zPlan='P4' */
9122 #define OP_VUpdate 15 /* synopsis: data=r[P3@P2] */
9123 #define OP_Goto 16
9124 #define OP_Gosub 17
9125 #define OP_Return 18
9126 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
9127 #define OP_Yield 20
9128 #define OP_HaltIfNull 21 /* synopsis: if r[P3] null then halt */
9129 #define OP_Halt 22
9130 #define OP_Integer 23 /* synopsis: r[P2]=P1 */
9131 #define OP_Int64 24 /* synopsis: r[P2]=P4 */
9132 #define OP_String 25 /* synopsis: r[P2]='P4' (len=P1) */
9133 #define OP_Null 26 /* synopsis: r[P2..P3]=NULL */
9134 #define OP_Blob 27 /* synopsis: r[P2]=P4 (len=P1) */
9135 #define OP_Variable 28 /* synopsis: r[P2]=parameter(P1,P4) */
9136 #define OP_Move 29 /* synopsis: r[P2@P3]=r[P1@P3] */
9137 #define OP_Copy 30 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
9138 #define OP_SCopy 31 /* synopsis: r[P2]=r[P1] */
9139 #define OP_ResultRow 32 /* synopsis: output=r[P1@P2] */
9140 #define OP_CollSeq 33
9141 #define OP_AddImm 34 /* synopsis: r[P1]=r[P1]+P2 */
9142 #define OP_MustBeInt 35
9143 #define OP_RealAffinity 36
9144 #define OP_Permutation 37
9145 #define OP_Compare 38
9146 #define OP_Jump 39
9147 #define OP_Once 40
9148 #define OP_If 41
9149 #define OP_IfNot 42
9150 #define OP_Column 43 /* synopsis: r[P3]=PX */
9151 #define OP_Affinity 44 /* synopsis: affinity(r[P1@P2]) */
9152 #define OP_MakeRecord 45 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
9153 #define OP_Count 46 /* synopsis: r[P2]=count() */
9154 #define OP_ReadCookie 47
9155 #define OP_SetCookie 48
9156 #define OP_VerifyCookie 49
9157 #define OP_OpenRead 50 /* synopsis: root=P2 iDb=P3 */
9158 #define OP_OpenWrite 51 /* synopsis: root=P2 iDb=P3 */
9159 #define OP_OpenAutoindex 52 /* synopsis: nColumn=P2 */
9160 #define OP_OpenEphemeral 53 /* synopsis: nColumn=P2 */
9161 #define OP_SorterOpen 54
9162 #define OP_OpenPseudo 55 /* synopsis: content in r[P2@P3] */
9163 #define OP_Close 56
9164 #define OP_SeekLt 57 /* synopsis: key=r[P3@P4] */
9165 #define OP_SeekLe 58 /* synopsis: key=r[P3@P4] */
9166 #define OP_SeekGe 59 /* synopsis: key=r[P3@P4] */
9167 #define OP_SeekGt 60 /* synopsis: key=r[P3@P4] */
9168 #define OP_Seek 61 /* synopsis: intkey=r[P2] */
9169 #define OP_NoConflict 62 /* synopsis: key=r[P3@P4] */
9170 #define OP_NotFound 63 /* synopsis: key=r[P3@P4] */
9171 #define OP_Found 64 /* synopsis: key=r[P3@P4] */
9172 #define OP_NotExists 65 /* synopsis: intkey=r[P3] */
9173 #define OP_Sequence 66 /* synopsis: r[P2]=rowid */
9174 #define OP_NewRowid 67 /* synopsis: r[P2]=rowid */
9175 #define OP_Insert 68 /* synopsis: intkey=r[P3] data=r[P2] */
9176 #define OP_InsertInt 69 /* synopsis: intkey=P3 data=r[P2] */
9177 #define OP_Delete 70
9178 #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9179 #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9180 #define OP_ResetCount 73
9181 #define OP_SorterCompare 74 /* synopsis: if key(P1)!=rtrim(r[P3],P4) goto P2 */
9182 #define OP_SorterData 75 /* synopsis: r[P2]=data */
9183 #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9184 #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9185 #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9186 #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9187 #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9188 #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9189 #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9190 #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9191 #define OP_RowKey 84 /* synopsis: r[P2]=key */
9192 #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9193 #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9194 #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9195 #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9196 #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9197 #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9198 #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9199 #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9200 #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9201 #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9202 #define OP_RowData 95 /* synopsis: r[P2]=data */
9203 #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9204 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
9205 #define OP_Rowid 98 /* synopsis: r[P2]=rowid */
9206 #define OP_NullRow 99
9207 #define OP_Last 100
9208 #define OP_SorterSort 101
9209 #define OP_Sort 102
9210 #define OP_Rewind 103
9211 #define OP_SorterInsert 104
9212 #define OP_IdxInsert 105 /* synopsis: key=r[P2] */
9213 #define OP_IdxDelete 106 /* synopsis: key=r[P2@P3] */
9214 #define OP_IdxRowid 107 /* synopsis: r[P2]=rowid */
9215 #define OP_IdxLT 108 /* synopsis: key=r[P3@P4] */
9216 #define OP_IdxGE 109 /* synopsis: key=r[P3@P4] */
9217 #define OP_Destroy 110
9218 #define OP_Clear 111
9219 #define OP_CreateIndex 112 /* synopsis: r[P2]=root iDb=P1 */
9220 #define OP_CreateTable 113 /* synopsis: r[P2]=root iDb=P1 */
9221 #define OP_ParseSchema 114
9222 #define OP_LoadAnalysis 115
9223 #define OP_DropTable 116
9224 #define OP_DropIndex 117
9225 #define OP_DropTrigger 118
9226 #define OP_IntegrityCk 119
9227 #define OP_RowSetAdd 120 /* synopsis: rowset(P1)=r[P2] */
9228 #define OP_RowSetRead 121 /* synopsis: r[P3]=rowset(P1) */
9229 #define OP_RowSetTest 122 /* synopsis: if r[P3] in rowset(P1) goto P2 */
9230 #define OP_Program 123
9231 #define OP_Param 124
9232 #define OP_FkCounter 125 /* synopsis: fkctr[P1]+=P2 */
9233 #define OP_FkIfZero 126 /* synopsis: if fkctr[P1]==0 goto P2 */
9234 #define OP_MemMax 127 /* synopsis: r[P1]=max(r[P1],r[P2]) */
9235 #define OP_IfPos 128 /* synopsis: if r[P1]>0 goto P2 */
9236 #define OP_IfNeg 129 /* synopsis: if r[P1]<0 goto P2 */
9237 #define OP_IfZero 130 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2 */
9238 #define OP_AggFinal 131 /* synopsis: accum=r[P1] N=P2 */
9239 #define OP_IncrVacuum 132
9240 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
9241 #define OP_Expire 134
9242 #define OP_TableLock 135 /* synopsis: iDb=P1 root=P2 write=P3 */
9243 #define OP_VBegin 136
9244 #define OP_VCreate 137
9245 #define OP_VDestroy 138
9246 #define OP_VOpen 139
9247 #define OP_VColumn 140 /* synopsis: r[P3]=vcolumn(P2) */
9248 #define OP_VNext 141
9249 #define OP_VRename 142
9250 #define OP_ToText 143 /* same as TK_TO_TEXT */
9251 #define OP_ToBlob 144 /* same as TK_TO_BLOB */
9252 #define OP_ToNumeric 145 /* same as TK_TO_NUMERIC */
9253 #define OP_ToInt 146 /* same as TK_TO_INT */
9254 #define OP_ToReal 147 /* same as TK_TO_REAL */
9255 #define OP_Pagecount 148
9256 #define OP_MaxPgcnt 149
9257 #define OP_Trace 150
9258 #define OP_Noop 151
9259 #define OP_Explain 152
9262 /* Properties such as "out2" or "jump" that are specified in
9263 ** comments following the "case" for each opcode in the vdbe.c
9264 ** are encoded into bitvectors as follows:
9266 #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
9267 #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
9268 #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
9269 #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
9270 #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
9271 #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
9272 #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
9273 #define OPFLG_INITIALIZER {\
9274 /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9275 /* 8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
9276 /* 16 */ 0x01, 0x01, 0x04, 0x24, 0x04, 0x10, 0x00, 0x02,\
9277 /* 24 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x20,\
9278 /* 32 */ 0x00, 0x00, 0x04, 0x05, 0x04, 0x00, 0x00, 0x01,\
9279 /* 40 */ 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x02,\
9280 /* 48 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9281 /* 56 */ 0x00, 0x11, 0x11, 0x11, 0x11, 0x08, 0x11, 0x11,\
9282 /* 64 */ 0x11, 0x11, 0x02, 0x02, 0x00, 0x00, 0x00, 0x4c,\
9283 /* 72 */ 0x4c, 0x00, 0x00, 0x00, 0x05, 0x05, 0x15, 0x15,\
9284 /* 80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
9285 /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
9286 /* 96 */ 0x24, 0x02, 0x02, 0x00, 0x01, 0x01, 0x01, 0x01,\
9287 /* 104 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
9288 /* 112 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9289 /* 120 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
9290 /* 128 */ 0x05, 0x05, 0x05, 0x00, 0x01, 0x02, 0x00, 0x00,\
9291 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04,\
9292 /* 144 */ 0x04, 0x04, 0x04, 0x04, 0x02, 0x02, 0x00, 0x00,\
9293 /* 152 */ 0x00,}
9295 /************** End of opcodes.h *********************************************/
9296 /************** Continuing where we left off in vdbe.h ***********************/
9299 ** Prototypes for the VDBE interface. See comments on the implementation
9300 ** for a description of what each of these routines does.
9302 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9303 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9304 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9305 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9306 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9307 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9308 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9309 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
9310 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9311 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9312 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9313 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9314 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9315 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9316 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9317 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9318 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9319 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
9320 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9321 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9322 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9323 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9324 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9325 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9326 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9327 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9328 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9329 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9330 #ifdef SQLITE_DEBUG
9331 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9332 #endif
9333 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9334 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9335 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9336 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9337 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9338 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9339 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9340 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9341 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9342 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9343 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9344 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9345 #ifndef SQLITE_OMIT_TRACE
9346 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9347 #endif
9349 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9350 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9351 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9353 #ifndef SQLITE_OMIT_TRIGGER
9354 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9355 #endif
9357 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
9358 ** each VDBE opcode.
9360 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
9361 ** comments in VDBE programs that show key decision points in the code
9362 ** generator.
9364 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9365 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
9366 # define VdbeComment(X) sqlite3VdbeComment X
9367 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9368 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
9369 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
9370 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
9371 # else
9372 # define VdbeModuleComment(X)
9373 # endif
9374 #else
9375 # define VdbeComment(X)
9376 # define VdbeNoopComment(X)
9377 # define VdbeModuleComment(X)
9378 #endif
9380 #endif
9382 /************** End of vdbe.h ************************************************/
9383 /************** Continuing where we left off in sqliteInt.h ******************/
9384 /************** Include pager.h in the middle of sqliteInt.h *****************/
9385 /************** Begin file pager.h *******************************************/
9387 ** 2001 September 15
9389 ** The author disclaims copyright to this source code. In place of
9390 ** a legal notice, here is a blessing:
9392 ** May you do good and not evil.
9393 ** May you find forgiveness for yourself and forgive others.
9394 ** May you share freely, never taking more than you give.
9396 *************************************************************************
9397 ** This header file defines the interface that the sqlite page cache
9398 ** subsystem. The page cache subsystem reads and writes a file a page
9399 ** at a time and provides a journal for rollback.
9402 #ifndef _PAGER_H_
9403 #define _PAGER_H_
9406 ** Default maximum size for persistent journal files. A negative
9407 ** value means no limit. This value may be overridden using the
9408 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9410 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9411 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9412 #endif
9415 ** The type used to represent a page number. The first page in a file
9416 ** is called page 1. 0 is used to represent "not a page".
9418 typedef u32 Pgno;
9421 ** Each open file is managed by a separate instance of the "Pager" structure.
9423 typedef struct Pager Pager;
9426 ** Handle type for pages.
9428 typedef struct PgHdr DbPage;
9431 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9432 ** reserved for working around a windows/posix incompatibility). It is
9433 ** used in the journal to signify that the remainder of the journal file
9434 ** is devoted to storing a master journal name - there are no more pages to
9435 ** roll back. See comments for function writeMasterJournal() in pager.c
9436 ** for details.
9438 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9441 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9443 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9445 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
9446 #define PAGER_MEMORY 0x0002 /* In-memory database */
9449 ** Valid values for the second argument to sqlite3PagerLockingMode().
9451 #define PAGER_LOCKINGMODE_QUERY -1
9452 #define PAGER_LOCKINGMODE_NORMAL 0
9453 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
9456 ** Numeric constants that encode the journalmode.
9458 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
9459 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
9460 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
9461 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
9462 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
9463 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
9464 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
9467 ** Flags that make up the mask passed to sqlite3PagerAcquire().
9469 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
9470 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
9473 ** Flags for sqlite3PagerSetFlags()
9475 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
9476 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
9477 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
9478 #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
9479 #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
9480 #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
9481 #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
9482 #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
9485 ** The remainder of this file contains the declarations of the functions
9486 ** that make up the Pager sub-system API. See source code comments for
9487 ** a detailed description of each routine.
9490 /* Open and close a Pager connection. */
9491 SQLITE_PRIVATE int sqlite3PagerOpen(
9492 sqlite3_vfs*,
9493 Pager **ppPager,
9494 const char*,
9495 int,
9496 int,
9497 int,
9498 void(*)(DbPage*)
9500 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9501 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9503 /* Functions used to configure a Pager object. */
9504 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9505 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9506 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9507 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9508 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9509 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9510 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
9511 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9512 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9513 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9514 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9515 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9516 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9518 /* Functions used to obtain and release page references. */
9519 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9520 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9521 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9522 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9523 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9524 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
9526 /* Operations on page references. */
9527 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9528 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9529 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9530 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9531 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
9532 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
9534 /* Functions used to manage pager transactions and savepoints. */
9535 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9536 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9537 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9538 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9539 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
9540 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9541 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9542 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9543 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9544 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9546 #ifndef SQLITE_OMIT_WAL
9547 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9548 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
9549 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
9550 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9551 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
9552 #endif
9554 #ifdef SQLITE_ENABLE_ZIPVFS
9555 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
9556 #endif
9558 /* Functions used to query pager state and configuration. */
9559 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9560 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9561 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9562 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9563 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9564 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9565 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9566 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9567 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9568 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9569 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9570 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9571 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9573 /* Functions used to truncate the database file. */
9574 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9576 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9577 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9578 #endif
9580 /* Functions to support testing and debugging. */
9581 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9582 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
9583 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
9584 #endif
9585 #ifdef SQLITE_TEST
9586 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
9587 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
9588 void disable_simulated_io_errors(void);
9589 void enable_simulated_io_errors(void);
9590 #else
9591 # define disable_simulated_io_errors()
9592 # define enable_simulated_io_errors()
9593 #endif
9595 #endif /* _PAGER_H_ */
9597 /************** End of pager.h ***********************************************/
9598 /************** Continuing where we left off in sqliteInt.h ******************/
9599 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9600 /************** Begin file pcache.h ******************************************/
9602 ** 2008 August 05
9604 ** The author disclaims copyright to this source code. In place of
9605 ** a legal notice, here is a blessing:
9607 ** May you do good and not evil.
9608 ** May you find forgiveness for yourself and forgive others.
9609 ** May you share freely, never taking more than you give.
9611 *************************************************************************
9612 ** This header file defines the interface that the sqlite page cache
9613 ** subsystem.
9616 #ifndef _PCACHE_H_
9618 typedef struct PgHdr PgHdr;
9619 typedef struct PCache PCache;
9622 ** Every page in the cache is controlled by an instance of the following
9623 ** structure.
9625 struct PgHdr {
9626 sqlite3_pcache_page *pPage; /* Pcache object page handle */
9627 void *pData; /* Page data */
9628 void *pExtra; /* Extra content */
9629 PgHdr *pDirty; /* Transient list of dirty pages */
9630 Pager *pPager; /* The pager this page is part of */
9631 Pgno pgno; /* Page number for this page */
9632 #ifdef SQLITE_CHECK_PAGES
9633 u32 pageHash; /* Hash of page content */
9634 #endif
9635 u16 flags; /* PGHDR flags defined below */
9637 /**********************************************************************
9638 ** Elements above are public. All that follows is private to pcache.c
9639 ** and should not be accessed by other modules.
9641 i16 nRef; /* Number of users of this page */
9642 PCache *pCache; /* Cache that owns this page */
9644 PgHdr *pDirtyNext; /* Next element in list of dirty pages */
9645 PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
9648 /* Bit values for PgHdr.flags */
9649 #define PGHDR_DIRTY 0x002 /* Page has changed */
9650 #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
9651 ** writing this page to the database */
9652 #define PGHDR_NEED_READ 0x008 /* Content is unread */
9653 #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
9654 #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
9656 #define PGHDR_MMAP 0x040 /* This is an mmap page object */
9658 /* Initialize and shutdown the page cache subsystem */
9659 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9660 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9662 /* Page cache buffer management:
9663 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9665 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9667 /* Create a new pager cache.
9668 ** Under memory stress, invoke xStress to try to make pages clean.
9669 ** Only clean and unpinned pages can be reclaimed.
9671 SQLITE_PRIVATE void sqlite3PcacheOpen(
9672 int szPage, /* Size of every page */
9673 int szExtra, /* Extra space associated with each page */
9674 int bPurgeable, /* True if pages are on backing store */
9675 int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9676 void *pStress, /* Argument to xStress */
9677 PCache *pToInit /* Preallocated space for the PCache */
9680 /* Modify the page-size after the cache has been created. */
9681 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9683 /* Return the size in bytes of a PCache object. Used to preallocate
9684 ** storage space.
9686 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9688 /* One release per successful fetch. Page is pinned until released.
9689 ** Reference counted.
9691 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9692 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9694 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
9695 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
9696 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
9697 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
9699 /* Change a page number. Used by incr-vacuum. */
9700 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9702 /* Remove all pages with pgno>x. Reset the cache if x==0 */
9703 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9705 /* Get a list of all dirty pages in the cache, sorted by page number */
9706 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9708 /* Reset and close the cache object */
9709 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9711 /* Clear flags from pages of the page cache */
9712 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9714 /* Discard the contents of the cache */
9715 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9717 /* Return the total number of outstanding page references */
9718 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9720 /* Increment the reference count of an existing page */
9721 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9723 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9725 /* Return the total number of pages stored in the cache */
9726 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9728 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9729 /* Iterate through all dirty pages currently stored in the cache. This
9730 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
9731 ** library is built.
9733 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9734 #endif
9736 /* Set and get the suggested cache-size for the specified pager-cache.
9738 ** If no global maximum is configured, then the system attempts to limit
9739 ** the total number of pages cached by purgeable pager-caches to the sum
9740 ** of the suggested cache-sizes.
9742 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9743 #ifdef SQLITE_TEST
9744 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9745 #endif
9747 /* Free up as much memory as possible from the page cache */
9748 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9750 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9751 /* Try to return memory used by the pcache module to the main memory heap */
9752 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9753 #endif
9755 #ifdef SQLITE_TEST
9756 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9757 #endif
9759 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9761 #endif /* _PCACHE_H_ */
9763 /************** End of pcache.h **********************************************/
9764 /************** Continuing where we left off in sqliteInt.h ******************/
9766 /************** Include os.h in the middle of sqliteInt.h ********************/
9767 /************** Begin file os.h **********************************************/
9769 ** 2001 September 16
9771 ** The author disclaims copyright to this source code. In place of
9772 ** a legal notice, here is a blessing:
9774 ** May you do good and not evil.
9775 ** May you find forgiveness for yourself and forgive others.
9776 ** May you share freely, never taking more than you give.
9778 ******************************************************************************
9780 ** This header file (together with is companion C source-code file
9781 ** "os.c") attempt to abstract the underlying operating system so that
9782 ** the SQLite library will work on both POSIX and windows systems.
9784 ** This header file is #include-ed by sqliteInt.h and thus ends up
9785 ** being included by every source file.
9787 #ifndef _SQLITE_OS_H_
9788 #define _SQLITE_OS_H_
9791 ** Figure out if we are dealing with Unix, Windows, or some other
9792 ** operating system. After the following block of preprocess macros,
9793 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
9794 ** will defined to either 1 or 0. One of the four will be 1. The other
9795 ** three will be 0.
9797 #if defined(SQLITE_OS_OTHER)
9798 # if SQLITE_OS_OTHER==1
9799 # undef SQLITE_OS_UNIX
9800 # define SQLITE_OS_UNIX 0
9801 # undef SQLITE_OS_WIN
9802 # define SQLITE_OS_WIN 0
9803 # else
9804 # undef SQLITE_OS_OTHER
9805 # endif
9806 #endif
9807 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9808 # define SQLITE_OS_OTHER 0
9809 # ifndef SQLITE_OS_WIN
9810 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9811 # define SQLITE_OS_WIN 1
9812 # define SQLITE_OS_UNIX 0
9813 # else
9814 # define SQLITE_OS_WIN 0
9815 # define SQLITE_OS_UNIX 1
9816 # endif
9817 # else
9818 # define SQLITE_OS_UNIX 0
9819 # endif
9820 #else
9821 # ifndef SQLITE_OS_WIN
9822 # define SQLITE_OS_WIN 0
9823 # endif
9824 #endif
9826 #if SQLITE_OS_WIN
9827 # include <windows.h>
9828 #endif
9831 ** Determine if we are dealing with Windows NT.
9833 ** We ought to be able to determine if we are compiling for win98 or winNT
9834 ** using the _WIN32_WINNT macro as follows:
9836 ** #if defined(_WIN32_WINNT)
9837 ** # define SQLITE_OS_WINNT 1
9838 ** #else
9839 ** # define SQLITE_OS_WINNT 0
9840 ** #endif
9842 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9843 ** so the above test does not work. We'll just assume that everything is
9844 ** winNT unless the programmer explicitly says otherwise by setting
9845 ** SQLITE_OS_WINNT to 0.
9847 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9848 # define SQLITE_OS_WINNT 1
9849 #endif
9852 ** Determine if we are dealing with WindowsCE - which has a much
9853 ** reduced API.
9855 #if defined(_WIN32_WCE)
9856 # define SQLITE_OS_WINCE 1
9857 #else
9858 # define SQLITE_OS_WINCE 0
9859 #endif
9862 ** Determine if we are dealing with WinRT, which provides only a subset of
9863 ** the full Win32 API.
9865 #if !defined(SQLITE_OS_WINRT)
9866 # define SQLITE_OS_WINRT 0
9867 #endif
9869 /* If the SET_FULLSYNC macro is not defined above, then make it
9870 ** a no-op
9872 #ifndef SET_FULLSYNC
9873 # define SET_FULLSYNC(x,y)
9874 #endif
9877 ** The default size of a disk sector
9879 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9880 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9881 #endif
9884 ** Temporary files are named starting with this prefix followed by 16 random
9885 ** alphanumeric characters, and no file extension. They are stored in the
9886 ** OS's standard temporary file directory, and are deleted prior to exit.
9887 ** If sqlite is being embedded in another program, you may wish to change the
9888 ** prefix to reflect your program's name, so that if your program exits
9889 ** prematurely, old temporary files can be easily identified. This can be done
9890 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9892 ** 2006-10-31: The default prefix used to be "sqlite_". But then
9893 ** Mcafee started using SQLite in their anti-virus product and it
9894 ** started putting files with the "sqlite" name in the c:/temp folder.
9895 ** This annoyed many windows users. Those users would then do a
9896 ** Google search for "sqlite", find the telephone numbers of the
9897 ** developers and call to wake them up at night and complain.
9898 ** For this reason, the default name prefix is changed to be "sqlite"
9899 ** spelled backwards. So the temp files are still identified, but
9900 ** anybody smart enough to figure out the code is also likely smart
9901 ** enough to know that calling the developer will not help get rid
9902 ** of the file.
9904 #ifndef SQLITE_TEMP_FILE_PREFIX
9905 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9906 #endif
9909 ** The following values may be passed as the second argument to
9910 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9912 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
9913 ** RESERVED: A single process may hold a RESERVED lock on a file at
9914 ** any time. Other processes may hold and obtain new SHARED locks.
9915 ** PENDING: A single process may hold a PENDING lock on a file at
9916 ** any one time. Existing SHARED locks may persist, but no new
9917 ** SHARED locks may be obtained by other processes.
9918 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9920 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9921 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9922 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9923 ** sqlite3OsLock().
9925 #define NO_LOCK 0
9926 #define SHARED_LOCK 1
9927 #define RESERVED_LOCK 2
9928 #define PENDING_LOCK 3
9929 #define EXCLUSIVE_LOCK 4
9932 ** File Locking Notes: (Mostly about windows but also some info for Unix)
9934 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9935 ** those functions are not available. So we use only LockFile() and
9936 ** UnlockFile().
9938 ** LockFile() prevents not just writing but also reading by other processes.
9939 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
9940 ** byte out of a specific range of bytes. The lock byte is obtained at
9941 ** random so two separate readers can probably access the file at the
9942 ** same time, unless they are unlucky and choose the same lock byte.
9943 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9944 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
9945 ** a single byte of the file that is designated as the reserved lock byte.
9946 ** A PENDING_LOCK is obtained by locking a designated byte different from
9947 ** the RESERVED_LOCK byte.
9949 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9950 ** which means we can use reader/writer locks. When reader/writer locks
9951 ** are used, the lock is placed on the same range of bytes that is used
9952 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
9953 ** will support two or more Win95 readers or two or more WinNT readers.
9954 ** But a single Win95 reader will lock out all WinNT readers and a single
9955 ** WinNT reader will lock out all other Win95 readers.
9957 ** The following #defines specify the range of bytes used for locking.
9958 ** SHARED_SIZE is the number of bytes available in the pool from which
9959 ** a random byte is selected for a shared lock. The pool of bytes for
9960 ** shared locks begins at SHARED_FIRST.
9962 ** The same locking strategy and
9963 ** byte ranges are used for Unix. This leaves open the possiblity of having
9964 ** clients on win95, winNT, and unix all talking to the same shared file
9965 ** and all locking correctly. To do so would require that samba (or whatever
9966 ** tool is being used for file sharing) implements locks correctly between
9967 ** windows and unix. I'm guessing that isn't likely to happen, but by
9968 ** using the same locking range we are at least open to the possibility.
9970 ** Locking in windows is manditory. For this reason, we cannot store
9971 ** actual data in the bytes used for locking. The pager never allocates
9972 ** the pages involved in locking therefore. SHARED_SIZE is selected so
9973 ** that all locks will fit on a single page even at the minimum page size.
9974 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
9975 ** is set high so that we don't have to allocate an unused page except
9976 ** for very large databases. But one should test the page skipping logic
9977 ** by setting PENDING_BYTE low and running the entire regression suite.
9979 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9980 ** file format. Depending on how it is changed, you might not notice
9981 ** the incompatibility right away, even running a full regression test.
9982 ** The default location of PENDING_BYTE is the first byte past the
9983 ** 1GB boundary.
9986 #ifdef SQLITE_OMIT_WSD
9987 # define PENDING_BYTE (0x40000000)
9988 #else
9989 # define PENDING_BYTE sqlite3PendingByte
9990 #endif
9991 #define RESERVED_BYTE (PENDING_BYTE+1)
9992 #define SHARED_FIRST (PENDING_BYTE+2)
9993 #define SHARED_SIZE 510
9996 ** Wrapper around OS specific sqlite3_os_init() function.
9998 SQLITE_PRIVATE int sqlite3OsInit(void);
10001 ** Functions for accessing sqlite3_file methods
10003 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10004 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10005 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10006 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10007 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10008 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10009 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10010 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10011 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10012 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10013 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10014 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10015 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10016 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10017 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10018 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10019 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10020 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10021 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10022 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10026 ** Functions for accessing sqlite3_vfs methods
10028 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10029 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10030 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10031 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10032 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10033 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10034 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10035 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10036 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10037 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
10038 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10039 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10040 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10043 ** Convenience functions for opening and closing files using
10044 ** sqlite3_malloc() to obtain space for the file-handle structure.
10046 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10047 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10049 #endif /* _SQLITE_OS_H_ */
10051 /************** End of os.h **************************************************/
10052 /************** Continuing where we left off in sqliteInt.h ******************/
10053 /************** Include mutex.h in the middle of sqliteInt.h *****************/
10054 /************** Begin file mutex.h *******************************************/
10056 ** 2007 August 28
10058 ** The author disclaims copyright to this source code. In place of
10059 ** a legal notice, here is a blessing:
10061 ** May you do good and not evil.
10062 ** May you find forgiveness for yourself and forgive others.
10063 ** May you share freely, never taking more than you give.
10065 *************************************************************************
10067 ** This file contains the common header for all mutex implementations.
10068 ** The sqliteInt.h header #includes this file so that it is available
10069 ** to all source files. We break it out in an effort to keep the code
10070 ** better organized.
10072 ** NOTE: source files should *not* #include this header file directly.
10073 ** Source files should #include the sqliteInt.h file and let that file
10074 ** include this one indirectly.
10079 ** Figure out what version of the code to use. The choices are
10081 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
10082 ** mutexes implemention cannot be overridden
10083 ** at start-time.
10085 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
10086 ** mutual exclusion is provided. But this
10087 ** implementation can be overridden at
10088 ** start-time.
10090 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
10092 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
10094 #if !SQLITE_THREADSAFE
10095 # define SQLITE_MUTEX_OMIT
10096 #endif
10097 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10098 # if SQLITE_OS_UNIX
10099 # define SQLITE_MUTEX_PTHREADS
10100 # elif SQLITE_OS_WIN
10101 # define SQLITE_MUTEX_W32
10102 # else
10103 # define SQLITE_MUTEX_NOOP
10104 # endif
10105 #endif
10107 #ifdef SQLITE_MUTEX_OMIT
10109 ** If this is a no-op implementation, implement everything as macros.
10111 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
10112 #define sqlite3_mutex_free(X)
10113 #define sqlite3_mutex_enter(X)
10114 #define sqlite3_mutex_try(X) SQLITE_OK
10115 #define sqlite3_mutex_leave(X)
10116 #define sqlite3_mutex_held(X) ((void)(X),1)
10117 #define sqlite3_mutex_notheld(X) ((void)(X),1)
10118 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
10119 #define sqlite3MutexInit() SQLITE_OK
10120 #define sqlite3MutexEnd()
10121 #define MUTEX_LOGIC(X)
10122 #else
10123 #define MUTEX_LOGIC(X) X
10124 #endif /* defined(SQLITE_MUTEX_OMIT) */
10126 /************** End of mutex.h ***********************************************/
10127 /************** Continuing where we left off in sqliteInt.h ******************/
10131 ** Each database file to be accessed by the system is an instance
10132 ** of the following structure. There are normally two of these structures
10133 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
10134 ** aDb[1] is the database file used to hold temporary tables. Additional
10135 ** databases may be attached.
10137 struct Db {
10138 char *zName; /* Name of this database */
10139 Btree *pBt; /* The B*Tree structure for this database file */
10140 u8 safety_level; /* How aggressive at syncing data to disk */
10141 Schema *pSchema; /* Pointer to database schema (possibly shared) */
10145 ** An instance of the following structure stores a database schema.
10147 ** Most Schema objects are associated with a Btree. The exception is
10148 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10149 ** In shared cache mode, a single Schema object can be shared by multiple
10150 ** Btrees that refer to the same underlying BtShared object.
10152 ** Schema objects are automatically deallocated when the last Btree that
10153 ** references them is destroyed. The TEMP Schema is manually freed by
10154 ** sqlite3_close().
10156 ** A thread must be holding a mutex on the corresponding Btree in order
10157 ** to access Schema content. This implies that the thread must also be
10158 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10159 ** For a TEMP Schema, only the connection mutex is required.
10161 struct Schema {
10162 int schema_cookie; /* Database schema version number for this file */
10163 int iGeneration; /* Generation counter. Incremented with each change */
10164 Hash tblHash; /* All tables indexed by name */
10165 Hash idxHash; /* All (named) indices indexed by name */
10166 Hash trigHash; /* All triggers indexed by name */
10167 Hash fkeyHash; /* All foreign keys by referenced table name */
10168 Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
10169 u8 file_format; /* Schema format version for this file */
10170 u8 enc; /* Text encoding used by this database */
10171 u16 flags; /* Flags associated with this schema */
10172 int cache_size; /* Number of pages to use in the cache */
10176 ** These macros can be used to test, set, or clear bits in the
10177 ** Db.pSchema->flags field.
10179 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
10180 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
10181 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
10182 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
10185 ** Allowed values for the DB.pSchema->flags field.
10187 ** The DB_SchemaLoaded flag is set after the database schema has been
10188 ** read into internal hash tables.
10190 ** DB_UnresetViews means that one or more views have column names that
10191 ** have been filled out. If the schema changes, these column names might
10192 ** changes and so the view will need to be reset.
10194 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
10195 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
10196 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
10199 ** The number of different kinds of things that can be limited
10200 ** using the sqlite3_limit() interface.
10202 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
10205 ** Lookaside malloc is a set of fixed-size buffers that can be used
10206 ** to satisfy small transient memory allocation requests for objects
10207 ** associated with a particular database connection. The use of
10208 ** lookaside malloc provides a significant performance enhancement
10209 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10210 ** SQL statements.
10212 ** The Lookaside structure holds configuration information about the
10213 ** lookaside malloc subsystem. Each available memory allocation in
10214 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10215 ** objects.
10217 ** Lookaside allocations are only allowed for objects that are associated
10218 ** with a particular database connection. Hence, schema information cannot
10219 ** be stored in lookaside because in shared cache mode the schema information
10220 ** is shared by multiple database connections. Therefore, while parsing
10221 ** schema information, the Lookaside.bEnabled flag is cleared so that
10222 ** lookaside allocations are not used to construct the schema objects.
10224 struct Lookaside {
10225 u16 sz; /* Size of each buffer in bytes */
10226 u8 bEnabled; /* False to disable new lookaside allocations */
10227 u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
10228 int nOut; /* Number of buffers currently checked out */
10229 int mxOut; /* Highwater mark for nOut */
10230 int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
10231 LookasideSlot *pFree; /* List of available buffers */
10232 void *pStart; /* First byte of available memory space */
10233 void *pEnd; /* First byte past end of available space */
10235 struct LookasideSlot {
10236 LookasideSlot *pNext; /* Next buffer in the list of free buffers */
10240 ** A hash table for function definitions.
10242 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10243 ** Collisions are on the FuncDef.pHash chain.
10245 struct FuncDefHash {
10246 FuncDef *a[23]; /* Hash table for functions */
10250 ** Each database connection is an instance of the following structure.
10252 struct sqlite3 {
10253 sqlite3_vfs *pVfs; /* OS Interface */
10254 struct Vdbe *pVdbe; /* List of active virtual machines */
10255 CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
10256 sqlite3_mutex *mutex; /* Connection mutex */
10257 Db *aDb; /* All backends */
10258 int nDb; /* Number of backends currently in use */
10259 int flags; /* Miscellaneous flags. See below */
10260 i64 lastRowid; /* ROWID of most recent insert (see above) */
10261 i64 szMmap; /* Default mmap_size setting */
10262 unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
10263 int errCode; /* Most recent error code (SQLITE_*) */
10264 int errMask; /* & result codes with this before returning */
10265 u16 dbOptFlags; /* Flags to enable/disable optimizations */
10266 u8 autoCommit; /* The auto-commit flag. */
10267 u8 temp_store; /* 1: file 2: memory 0: default */
10268 u8 mallocFailed; /* True if we have seen a malloc failure */
10269 u8 dfltLockMode; /* Default locking-mode for attached dbs */
10270 signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
10271 u8 suppressErr; /* Do not issue error messages if true */
10272 u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
10273 u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
10274 int nextPagesize; /* Pagesize after VACUUM if >0 */
10275 u32 magic; /* Magic number for detect library misuse */
10276 int nChange; /* Value returned by sqlite3_changes() */
10277 int nTotalChange; /* Value returned by sqlite3_total_changes() */
10278 int aLimit[SQLITE_N_LIMIT]; /* Limits */
10279 struct sqlite3InitInfo { /* Information used during initialization */
10280 int newTnum; /* Rootpage of table being initialized */
10281 u8 iDb; /* Which db file is being initialized */
10282 u8 busy; /* TRUE if currently initializing */
10283 u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
10284 } init;
10285 int nVdbeActive; /* Number of VDBEs currently running */
10286 int nVdbeRead; /* Number of active VDBEs that read or write */
10287 int nVdbeWrite; /* Number of active VDBEs that read and write */
10288 int nVdbeExec; /* Number of nested calls to VdbeExec() */
10289 int nExtension; /* Number of loaded extensions */
10290 void **aExtension; /* Array of shared library handles */
10291 void (*xTrace)(void*,const char*); /* Trace function */
10292 void *pTraceArg; /* Argument to the trace function */
10293 void (*xProfile)(void*,const char*,u64); /* Profiling function */
10294 void *pProfileArg; /* Argument to profile function */
10295 void *pCommitArg; /* Argument to xCommitCallback() */
10296 int (*xCommitCallback)(void*); /* Invoked at every commit. */
10297 void *pRollbackArg; /* Argument to xRollbackCallback() */
10298 void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10299 void *pUpdateArg;
10300 void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10301 #ifndef SQLITE_OMIT_WAL
10302 int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10303 void *pWalArg;
10304 #endif
10305 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10306 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10307 void *pCollNeededArg;
10308 sqlite3_value *pErr; /* Most recent error message */
10309 union {
10310 volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10311 double notUsed1; /* Spacer */
10312 } u1;
10313 Lookaside lookaside; /* Lookaside malloc configuration */
10314 #ifndef SQLITE_OMIT_AUTHORIZATION
10315 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
10316 /* Access authorization function */
10317 void *pAuthArg; /* 1st argument to the access auth function */
10318 #endif
10319 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10320 int (*xProgress)(void *); /* The progress callback */
10321 void *pProgressArg; /* Argument to the progress callback */
10322 unsigned nProgressOps; /* Number of opcodes for progress callback */
10323 #endif
10324 #ifndef SQLITE_OMIT_VIRTUALTABLE
10325 int nVTrans; /* Allocated size of aVTrans */
10326 Hash aModule; /* populated by sqlite3_create_module() */
10327 VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
10328 VTable **aVTrans; /* Virtual tables with open transactions */
10329 VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
10330 #endif
10331 FuncDefHash aFunc; /* Hash table of connection functions */
10332 Hash aCollSeq; /* All collating sequences */
10333 BusyHandler busyHandler; /* Busy callback */
10334 Db aDbStatic[2]; /* Static space for the 2 default backends */
10335 Savepoint *pSavepoint; /* List of active savepoints */
10336 int busyTimeout; /* Busy handler timeout, in msec */
10337 int nSavepoint; /* Number of non-transaction savepoints */
10338 int nStatement; /* Number of nested statement-transactions */
10339 i64 nDeferredCons; /* Net deferred constraints this transaction. */
10340 i64 nDeferredImmCons; /* Net deferred immediate constraints */
10341 int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
10343 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10344 /* The following variables are all protected by the STATIC_MASTER
10345 ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
10347 ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10348 ** unlock so that it can proceed.
10350 ** When X.pBlockingConnection==Y, that means that something that X tried
10351 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10352 ** held by Y.
10354 sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10355 sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
10356 void *pUnlockArg; /* Argument to xUnlockNotify */
10357 void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
10358 sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
10359 #endif
10363 ** A macro to discover the encoding of a database.
10365 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10368 ** Possible values for the sqlite3.flags.
10370 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
10371 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
10372 #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
10373 #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
10374 #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
10375 #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
10376 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
10377 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
10378 /* DELETE, or UPDATE and return */
10379 /* the count using a callback. */
10380 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
10381 /* result set is empty */
10382 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
10383 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
10384 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
10385 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
10386 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
10387 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
10388 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
10389 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
10390 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
10391 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
10392 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
10393 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
10394 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
10395 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
10396 #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
10397 #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
10398 #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
10399 #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
10403 ** Bits of the sqlite3.dbOptFlags field that are used by the
10404 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10405 ** selectively disable various optimizations.
10407 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
10408 #define SQLITE_ColumnCache 0x0002 /* Column cache */
10409 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
10410 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
10411 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
10412 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
10413 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
10414 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
10415 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
10416 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
10417 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
10418 #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
10419 #define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */
10420 #define SQLITE_AllOpts 0xffff /* All optimizations */
10423 ** Macros for testing whether or not optimizations are enabled or disabled.
10425 #ifndef SQLITE_OMIT_BUILTIN_TEST
10426 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
10427 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
10428 #else
10429 #define OptimizationDisabled(db, mask) 0
10430 #define OptimizationEnabled(db, mask) 1
10431 #endif
10434 ** Return true if it OK to factor constant expressions into the initialization
10435 ** code. The argument is a Parse object for the code generator.
10437 #define ConstFactorOk(P) \
10438 ((P)->cookieGoto>0 && OptimizationEnabled((P)->db,SQLITE_FactorOutConst))
10441 ** Possible values for the sqlite.magic field.
10442 ** The numbers are obtained at random and have no special meaning, other
10443 ** than being distinct from one another.
10445 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
10446 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
10447 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
10448 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
10449 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
10450 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
10453 ** Each SQL function is defined by an instance of the following
10454 ** structure. A pointer to this structure is stored in the sqlite.aFunc
10455 ** hash table. When multiple functions have the same name, the hash table
10456 ** points to a linked list of these structures.
10458 struct FuncDef {
10459 i16 nArg; /* Number of arguments. -1 means unlimited */
10460 u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
10461 void *pUserData; /* User data parameter */
10462 FuncDef *pNext; /* Next function with same name */
10463 void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10464 void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10465 void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
10466 char *zName; /* SQL name of the function. */
10467 FuncDef *pHash; /* Next with a different name but the same hash */
10468 FuncDestructor *pDestructor; /* Reference counted destructor function */
10472 ** This structure encapsulates a user-function destructor callback (as
10473 ** configured using create_function_v2()) and a reference counter. When
10474 ** create_function_v2() is called to create a function with a destructor,
10475 ** a single object of this type is allocated. FuncDestructor.nRef is set to
10476 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10477 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10478 ** member of each of the new FuncDef objects is set to point to the allocated
10479 ** FuncDestructor.
10481 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10482 ** count on this object is decremented. When it reaches 0, the destructor
10483 ** is invoked and the FuncDestructor structure freed.
10485 struct FuncDestructor {
10486 int nRef;
10487 void (*xDestroy)(void *);
10488 void *pUserData;
10492 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
10493 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
10494 ** are assert() statements in the code to verify this.
10496 #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
10497 #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
10498 #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
10499 #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
10500 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
10501 #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
10502 #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
10503 #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
10504 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
10505 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
10506 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
10509 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10510 ** used to create the initializers for the FuncDef structures.
10512 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
10513 ** Used to create a scalar function definition of a function zName
10514 ** implemented by C function xFunc that accepts nArg arguments. The
10515 ** value passed as iArg is cast to a (void*) and made available
10516 ** as the user-data (sqlite3_user_data()) for the function. If
10517 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10519 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
10520 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
10522 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10523 ** Used to create an aggregate function definition implemented by
10524 ** the C functions xStep and xFinal. The first four parameters
10525 ** are interpreted in the same way as the first 4 parameters to
10526 ** FUNCTION().
10528 ** LIKEFUNC(zName, nArg, pArg, flags)
10529 ** Used to create a scalar function definition of a function zName
10530 ** that accepts nArg arguments and is implemented by a call to C
10531 ** function likeFunc. Argument pArg is cast to a (void *) and made
10532 ** available as the function user-data (sqlite3_user_data()). The
10533 ** FuncDef.flags variable is set to the value passed as the flags
10534 ** parameter.
10536 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10537 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10538 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10539 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
10540 {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10541 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10542 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10543 {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
10544 SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10545 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10546 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
10547 pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10548 #define LIKEFUNC(zName, nArg, arg, flags) \
10549 {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
10550 (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10551 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10552 {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
10553 SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10556 ** All current savepoints are stored in a linked list starting at
10557 ** sqlite3.pSavepoint. The first element in the list is the most recently
10558 ** opened savepoint. Savepoints are added to the list by the vdbe
10559 ** OP_Savepoint instruction.
10561 struct Savepoint {
10562 char *zName; /* Savepoint name (nul-terminated) */
10563 i64 nDeferredCons; /* Number of deferred fk violations */
10564 i64 nDeferredImmCons; /* Number of deferred imm fk. */
10565 Savepoint *pNext; /* Parent savepoint (if any) */
10569 ** The following are used as the second parameter to sqlite3Savepoint(),
10570 ** and as the P1 argument to the OP_Savepoint instruction.
10572 #define SAVEPOINT_BEGIN 0
10573 #define SAVEPOINT_RELEASE 1
10574 #define SAVEPOINT_ROLLBACK 2
10578 ** Each SQLite module (virtual table definition) is defined by an
10579 ** instance of the following structure, stored in the sqlite3.aModule
10580 ** hash table.
10582 struct Module {
10583 const sqlite3_module *pModule; /* Callback pointers */
10584 const char *zName; /* Name passed to create_module() */
10585 void *pAux; /* pAux passed to create_module() */
10586 void (*xDestroy)(void *); /* Module destructor function */
10590 ** information about each column of an SQL table is held in an instance
10591 ** of this structure.
10593 struct Column {
10594 char *zName; /* Name of this column */
10595 Expr *pDflt; /* Default value of this column */
10596 char *zDflt; /* Original text of the default value */
10597 char *zType; /* Data type for this column */
10598 char *zColl; /* Collating sequence. If NULL, use the default */
10599 u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
10600 char affinity; /* One of the SQLITE_AFF_... values */
10601 u8 szEst; /* Estimated size of this column. INT==1 */
10602 u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
10605 /* Allowed values for Column.colFlags:
10607 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
10608 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
10611 ** A "Collating Sequence" is defined by an instance of the following
10612 ** structure. Conceptually, a collating sequence consists of a name and
10613 ** a comparison routine that defines the order of that sequence.
10615 ** If CollSeq.xCmp is NULL, it means that the
10616 ** collating sequence is undefined. Indices built on an undefined
10617 ** collating sequence may not be read or written.
10619 struct CollSeq {
10620 char *zName; /* Name of the collating sequence, UTF-8 encoded */
10621 u8 enc; /* Text encoding handled by xCmp() */
10622 void *pUser; /* First argument to xCmp() */
10623 int (*xCmp)(void*,int, const void*, int, const void*);
10624 void (*xDel)(void*); /* Destructor for pUser */
10628 ** A sort order can be either ASC or DESC.
10630 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
10631 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
10634 ** Column affinity types.
10636 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10637 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
10638 ** the speed a little by numbering the values consecutively.
10640 ** But rather than start with 0 or 1, we begin with 'a'. That way,
10641 ** when multiple affinity types are concatenated into a string and
10642 ** used as the P4 operand, they will be more readable.
10644 ** Note also that the numeric types are grouped together so that testing
10645 ** for a numeric type is a single comparison.
10647 #define SQLITE_AFF_TEXT 'a'
10648 #define SQLITE_AFF_NONE 'b'
10649 #define SQLITE_AFF_NUMERIC 'c'
10650 #define SQLITE_AFF_INTEGER 'd'
10651 #define SQLITE_AFF_REAL 'e'
10653 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
10656 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10657 ** affinity value.
10659 #define SQLITE_AFF_MASK 0x67
10662 ** Additional bit values that can be ORed with an affinity without
10663 ** changing the affinity.
10665 #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
10666 #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
10667 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
10670 ** An object of this type is created for each virtual table present in
10671 ** the database schema.
10673 ** If the database schema is shared, then there is one instance of this
10674 ** structure for each database connection (sqlite3*) that uses the shared
10675 ** schema. This is because each database connection requires its own unique
10676 ** instance of the sqlite3_vtab* handle used to access the virtual table
10677 ** implementation. sqlite3_vtab* handles can not be shared between
10678 ** database connections, even when the rest of the in-memory database
10679 ** schema is shared, as the implementation often stores the database
10680 ** connection handle passed to it via the xConnect() or xCreate() method
10681 ** during initialization internally. This database connection handle may
10682 ** then be used by the virtual table implementation to access real tables
10683 ** within the database. So that they appear as part of the callers
10684 ** transaction, these accesses need to be made via the same database
10685 ** connection as that used to execute SQL operations on the virtual table.
10687 ** All VTable objects that correspond to a single table in a shared
10688 ** database schema are initially stored in a linked-list pointed to by
10689 ** the Table.pVTable member variable of the corresponding Table object.
10690 ** When an sqlite3_prepare() operation is required to access the virtual
10691 ** table, it searches the list for the VTable that corresponds to the
10692 ** database connection doing the preparing so as to use the correct
10693 ** sqlite3_vtab* handle in the compiled query.
10695 ** When an in-memory Table object is deleted (for example when the
10696 ** schema is being reloaded for some reason), the VTable objects are not
10697 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10698 ** immediately. Instead, they are moved from the Table.pVTable list to
10699 ** another linked list headed by the sqlite3.pDisconnect member of the
10700 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
10701 ** next time a statement is prepared using said sqlite3*. This is done
10702 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10703 ** Refer to comments above function sqlite3VtabUnlockList() for an
10704 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10705 ** list without holding the corresponding sqlite3.mutex mutex.
10707 ** The memory for objects of this type is always allocated by
10708 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10709 ** the first argument.
10711 struct VTable {
10712 sqlite3 *db; /* Database connection associated with this table */
10713 Module *pMod; /* Pointer to module implementation */
10714 sqlite3_vtab *pVtab; /* Pointer to vtab instance */
10715 int nRef; /* Number of pointers to this structure */
10716 u8 bConstraint; /* True if constraints are supported */
10717 int iSavepoint; /* Depth of the SAVEPOINT stack */
10718 VTable *pNext; /* Next in linked list (see above) */
10722 ** Each SQL table is represented in memory by an instance of the
10723 ** following structure.
10725 ** Table.zName is the name of the table. The case of the original
10726 ** CREATE TABLE statement is stored, but case is not significant for
10727 ** comparisons.
10729 ** Table.nCol is the number of columns in this table. Table.aCol is a
10730 ** pointer to an array of Column structures, one for each column.
10732 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10733 ** the column that is that key. Otherwise Table.iPKey is negative. Note
10734 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10735 ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
10736 ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
10737 ** is generated for each row of the table. TF_HasPrimaryKey is set if
10738 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10740 ** Table.tnum is the page number for the root BTree page of the table in the
10741 ** database file. If Table.iDb is the index of the database table backend
10742 ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
10743 ** holds temporary tables and indices. If TF_Ephemeral is set
10744 ** then the table is stored in a file that is automatically deleted
10745 ** when the VDBE cursor to the table is closed. In this case Table.tnum
10746 ** refers VDBE cursor number that holds the table open, not to the root
10747 ** page number. Transient tables are used to hold the results of a
10748 ** sub-query that appears instead of a real table name in the FROM clause
10749 ** of a SELECT statement.
10751 struct Table {
10752 char *zName; /* Name of the table or view */
10753 Column *aCol; /* Information about each column */
10754 Index *pIndex; /* List of SQL indexes on this table. */
10755 Select *pSelect; /* NULL for tables. Points to definition if a view. */
10756 FKey *pFKey; /* Linked list of all foreign keys in this table */
10757 char *zColAff; /* String defining the affinity of each column */
10758 #ifndef SQLITE_OMIT_CHECK
10759 ExprList *pCheck; /* All CHECK constraints */
10760 #endif
10761 tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
10762 int tnum; /* Root BTree node for this table (see note above) */
10763 i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
10764 i16 nCol; /* Number of columns in this table */
10765 u16 nRef; /* Number of pointers to this Table */
10766 LogEst szTabRow; /* Estimated size of each table row in bytes */
10767 u8 tabFlags; /* Mask of TF_* values */
10768 u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
10769 #ifndef SQLITE_OMIT_ALTERTABLE
10770 int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
10771 #endif
10772 #ifndef SQLITE_OMIT_VIRTUALTABLE
10773 int nModuleArg; /* Number of arguments to the module */
10774 char **azModuleArg; /* Text of all module args. [0] is module name */
10775 VTable *pVTable; /* List of VTable objects. */
10776 #endif
10777 Trigger *pTrigger; /* List of triggers stored in pSchema */
10778 Schema *pSchema; /* Schema that contains this table */
10779 Table *pNextZombie; /* Next on the Parse.pZombieTab list */
10783 ** Allowed values for Table.tabFlags.
10785 #define TF_Readonly 0x01 /* Read-only system table */
10786 #define TF_Ephemeral 0x02 /* An ephemeral table */
10787 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
10788 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
10789 #define TF_Virtual 0x10 /* Is a virtual table */
10790 #define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */
10794 ** Test to see whether or not a table is a virtual table. This is
10795 ** done as a macro so that it will be optimized out when virtual
10796 ** table support is omitted from the build.
10798 #ifndef SQLITE_OMIT_VIRTUALTABLE
10799 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
10800 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10801 #else
10802 # define IsVirtual(X) 0
10803 # define IsHiddenColumn(X) 0
10804 #endif
10806 /* Does the table have a rowid */
10807 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
10810 ** Each foreign key constraint is an instance of the following structure.
10812 ** A foreign key is associated with two tables. The "from" table is
10813 ** the table that contains the REFERENCES clause that creates the foreign
10814 ** key. The "to" table is the table that is named in the REFERENCES clause.
10815 ** Consider this example:
10817 ** CREATE TABLE ex1(
10818 ** a INTEGER PRIMARY KEY,
10819 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10820 ** );
10822 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10823 ** Equivalent names:
10825 ** from-table == child-table
10826 ** to-table == parent-table
10828 ** Each REFERENCES clause generates an instance of the following structure
10829 ** which is attached to the from-table. The to-table need not exist when
10830 ** the from-table is created. The existence of the to-table is not checked.
10832 ** The list of all parents for child Table X is held at X.pFKey.
10834 ** A list of all children for a table named Z (which might not even exist)
10835 ** is held in Schema.fkeyHash with a hash key of Z.
10837 struct FKey {
10838 Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
10839 FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
10840 char *zTo; /* Name of table that the key points to (aka: Parent) */
10841 FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
10842 FKey *pPrevTo; /* Previous with the same zTo */
10843 int nCol; /* Number of columns in this key */
10844 /* EV: R-30323-21917 */
10845 u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
10846 u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
10847 Trigger *apTrigger[2];/* Triggers for aAction[] actions */
10848 struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
10849 int iFrom; /* Index of column in pFrom */
10850 char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
10851 } aCol[1]; /* One entry for each of nCol columns */
10855 ** SQLite supports many different ways to resolve a constraint
10856 ** error. ROLLBACK processing means that a constraint violation
10857 ** causes the operation in process to fail and for the current transaction
10858 ** to be rolled back. ABORT processing means the operation in process
10859 ** fails and any prior changes from that one operation are backed out,
10860 ** but the transaction is not rolled back. FAIL processing means that
10861 ** the operation in progress stops and returns an error code. But prior
10862 ** changes due to the same operation are not backed out and no rollback
10863 ** occurs. IGNORE means that the particular row that caused the constraint
10864 ** error is not inserted or updated. Processing continues and no error
10865 ** is returned. REPLACE means that preexisting database rows that caused
10866 ** a UNIQUE constraint violation are removed so that the new insert or
10867 ** update can proceed. Processing continues and no error is reported.
10869 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10870 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10871 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
10872 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
10873 ** referenced table row is propagated into the row that holds the
10874 ** foreign key.
10876 ** The following symbolic values are used to record which type
10877 ** of action to take.
10879 #define OE_None 0 /* There is no constraint to check */
10880 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
10881 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
10882 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
10883 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
10884 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
10886 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10887 #define OE_SetNull 7 /* Set the foreign key value to NULL */
10888 #define OE_SetDflt 8 /* Set the foreign key value to its default */
10889 #define OE_Cascade 9 /* Cascade the changes */
10891 #define OE_Default 10 /* Do whatever the default action is */
10895 ** An instance of the following structure is passed as the first
10896 ** argument to sqlite3VdbeKeyCompare and is used to control the
10897 ** comparison of the two index keys.
10899 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
10900 ** are nField slots for the columns of an index then one extra slot
10901 ** for the rowid at the end.
10903 struct KeyInfo {
10904 u32 nRef; /* Number of references to this KeyInfo object */
10905 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
10906 u16 nField; /* Number of key columns in the index */
10907 u16 nXField; /* Number of columns beyond the key columns */
10908 sqlite3 *db; /* The database connection */
10909 u8 *aSortOrder; /* Sort order for each column. */
10910 CollSeq *aColl[1]; /* Collating sequence for each term of the key */
10914 ** An instance of the following structure holds information about a
10915 ** single index record that has already been parsed out into individual
10916 ** values.
10918 ** A record is an object that contains one or more fields of data.
10919 ** Records are used to store the content of a table row and to store
10920 ** the key of an index. A blob encoding of a record is created by
10921 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10922 ** OP_Column opcode.
10924 ** This structure holds a record that has already been disassembled
10925 ** into its constituent fields.
10927 struct UnpackedRecord {
10928 KeyInfo *pKeyInfo; /* Collation and sort-order information */
10929 u16 nField; /* Number of entries in apMem[] */
10930 u8 flags; /* Boolean settings. UNPACKED_... below */
10931 Mem *aMem; /* Values */
10935 ** Allowed values of UnpackedRecord.flags
10937 #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
10938 #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
10941 ** Each SQL index is represented in memory by an
10942 ** instance of the following structure.
10944 ** The columns of the table that are to be indexed are described
10945 ** by the aiColumn[] field of this structure. For example, suppose
10946 ** we have the following table and index:
10948 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10949 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
10951 ** In the Table structure describing Ex1, nCol==3 because there are
10952 ** three columns in the table. In the Index structure describing
10953 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10954 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
10955 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10956 ** The second column to be indexed (c1) has an index of 0 in
10957 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10959 ** The Index.onError field determines whether or not the indexed columns
10960 ** must be unique and what to do if they are not. When Index.onError=OE_None,
10961 ** it means this is not a unique index. Otherwise it is a unique index
10962 ** and the value of Index.onError indicate the which conflict resolution
10963 ** algorithm to employ whenever an attempt is made to insert a non-unique
10964 ** element.
10966 struct Index {
10967 char *zName; /* Name of this index */
10968 i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
10969 tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
10970 Table *pTable; /* The SQL table being indexed */
10971 char *zColAff; /* String defining the affinity of each column */
10972 Index *pNext; /* The next index associated with the same table */
10973 Schema *pSchema; /* Schema containing this index */
10974 u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
10975 char **azColl; /* Array of collation sequence names for index */
10976 Expr *pPartIdxWhere; /* WHERE clause for partial indices */
10977 KeyInfo *pKeyInfo; /* A KeyInfo object suitable for this index */
10978 int tnum; /* DB Page containing root of this index */
10979 LogEst szIdxRow; /* Estimated average row size in bytes */
10980 u16 nKeyCol; /* Number of columns forming the key */
10981 u16 nColumn; /* Number of columns stored in the index */
10982 u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10983 unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10984 unsigned bUnordered:1; /* Use this index for == or IN queries only */
10985 unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
10986 unsigned isResized:1; /* True if resizeIndexObject() has been called */
10987 unsigned isCovering:1; /* True if this is a covering index */
10988 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
10989 int nSample; /* Number of elements in aSample[] */
10990 int nSampleCol; /* Size of IndexSample.anEq[] and so on */
10991 tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
10992 IndexSample *aSample; /* Samples of the left-most key */
10993 #endif
10997 ** Each sample stored in the sqlite_stat3 table is represented in memory
10998 ** using a structure of this type. See documentation at the top of the
10999 ** analyze.c source file for additional information.
11001 struct IndexSample {
11002 void *p; /* Pointer to sampled record */
11003 int n; /* Size of record in bytes */
11004 tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
11005 tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
11006 tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
11010 ** Each token coming out of the lexer is an instance of
11011 ** this structure. Tokens are also used as part of an expression.
11013 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11014 ** may contain random values. Do not make any assumptions about Token.dyn
11015 ** and Token.n when Token.z==0.
11017 struct Token {
11018 const char *z; /* Text of the token. Not NULL-terminated! */
11019 unsigned int n; /* Number of characters in this token */
11023 ** An instance of this structure contains information needed to generate
11024 ** code for a SELECT that contains aggregate functions.
11026 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11027 ** pointer to this structure. The Expr.iColumn field is the index in
11028 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11029 ** code for that node.
11031 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11032 ** original Select structure that describes the SELECT statement. These
11033 ** fields do not need to be freed when deallocating the AggInfo structure.
11035 struct AggInfo {
11036 u8 directMode; /* Direct rendering mode means take data directly
11037 ** from source tables rather than from accumulators */
11038 u8 useSortingIdx; /* In direct mode, reference the sorting index rather
11039 ** than the source table */
11040 int sortingIdx; /* Cursor number of the sorting index */
11041 int sortingIdxPTab; /* Cursor number of pseudo-table */
11042 int nSortingColumn; /* Number of columns in the sorting index */
11043 int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
11044 ExprList *pGroupBy; /* The group by clause */
11045 struct AggInfo_col { /* For each column used in source tables */
11046 Table *pTab; /* Source table */
11047 int iTable; /* Cursor number of the source table */
11048 int iColumn; /* Column number within the source table */
11049 int iSorterColumn; /* Column number in the sorting index */
11050 int iMem; /* Memory location that acts as accumulator */
11051 Expr *pExpr; /* The original expression */
11052 } *aCol;
11053 int nColumn; /* Number of used entries in aCol[] */
11054 int nAccumulator; /* Number of columns that show through to the output.
11055 ** Additional columns are used only as parameters to
11056 ** aggregate functions */
11057 struct AggInfo_func { /* For each aggregate function */
11058 Expr *pExpr; /* Expression encoding the function */
11059 FuncDef *pFunc; /* The aggregate function implementation */
11060 int iMem; /* Memory location that acts as accumulator */
11061 int iDistinct; /* Ephemeral table used to enforce DISTINCT */
11062 } *aFunc;
11063 int nFunc; /* Number of entries in aFunc[] */
11067 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11068 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
11069 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
11070 ** it uses less memory in the Expr object, which is a big memory user
11071 ** in systems with lots of prepared statements. And few applications
11072 ** need more than about 10 or 20 variables. But some extreme users want
11073 ** to have prepared statements with over 32767 variables, and for them
11074 ** the option is available (at compile-time).
11076 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
11077 typedef i16 ynVar;
11078 #else
11079 typedef int ynVar;
11080 #endif
11083 ** Each node of an expression in the parse tree is an instance
11084 ** of this structure.
11086 ** Expr.op is the opcode. The integer parser token codes are reused
11087 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11088 ** code representing the ">=" operator. This same integer code is reused
11089 ** to represent the greater-than-or-equal-to operator in the expression
11090 ** tree.
11092 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
11093 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11094 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
11095 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11096 ** then Expr.token contains the name of the function.
11098 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11099 ** binary operator. Either or both may be NULL.
11101 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11102 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11103 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11104 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11105 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
11106 ** valid.
11108 ** An expression of the form ID or ID.ID refers to a column in a table.
11109 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11110 ** the integer cursor number of a VDBE cursor pointing to that table and
11111 ** Expr.iColumn is the column number for the specific column. If the
11112 ** expression is used as a result in an aggregate SELECT, then the
11113 ** value is also stored in the Expr.iAgg column in the aggregate so that
11114 ** it can be accessed after all aggregates are computed.
11116 ** If the expression is an unbound variable marker (a question mark
11117 ** character '?' in the original SQL) then the Expr.iTable holds the index
11118 ** number for that variable.
11120 ** If the expression is a subquery then Expr.iColumn holds an integer
11121 ** register number containing the result of the subquery. If the
11122 ** subquery gives a constant result, then iTable is -1. If the subquery
11123 ** gives a different answer at different times during statement processing
11124 ** then iTable is the address of a subroutine that computes the subquery.
11126 ** If the Expr is of type OP_Column, and the table it is selecting from
11127 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11128 ** corresponding table definition.
11130 ** ALLOCATION NOTES:
11132 ** Expr objects can use a lot of memory space in database schema. To
11133 ** help reduce memory requirements, sometimes an Expr object will be
11134 ** truncated. And to reduce the number of memory allocations, sometimes
11135 ** two or more Expr objects will be stored in a single memory allocation,
11136 ** together with Expr.zToken strings.
11138 ** If the EP_Reduced and EP_TokenOnly flags are set when
11139 ** an Expr object is truncated. When EP_Reduced is set, then all
11140 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11141 ** are contained within the same memory allocation. Note, however, that
11142 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11143 ** allocated, regardless of whether or not EP_Reduced is set.
11145 struct Expr {
11146 u8 op; /* Operation performed by this node */
11147 char affinity; /* The affinity of the column or 0 if not a column */
11148 u32 flags; /* Various flags. EP_* See below */
11149 union {
11150 char *zToken; /* Token value. Zero terminated and dequoted */
11151 int iValue; /* Non-negative integer value if EP_IntValue */
11152 } u;
11154 /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11155 ** space is allocated for the fields below this point. An attempt to
11156 ** access them will result in a segfault or malfunction.
11157 *********************************************************************/
11159 Expr *pLeft; /* Left subnode */
11160 Expr *pRight; /* Right subnode */
11161 union {
11162 ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11163 Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11164 } x;
11166 /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11167 ** space is allocated for the fields below this point. An attempt to
11168 ** access them will result in a segfault or malfunction.
11169 *********************************************************************/
11171 #if SQLITE_MAX_EXPR_DEPTH>0
11172 int nHeight; /* Height of the tree headed by this node */
11173 #endif
11174 int iTable; /* TK_COLUMN: cursor number of table holding column
11175 ** TK_REGISTER: register number
11176 ** TK_TRIGGER: 1 -> new, 0 -> old
11177 ** EP_Unlikely: 1000 times likelihood */
11178 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
11179 ** TK_VARIABLE: variable number (always >= 1). */
11180 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11181 i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
11182 u8 op2; /* TK_REGISTER: original value of Expr.op
11183 ** TK_COLUMN: the value of p5 for OP_Column
11184 ** TK_AGG_FUNCTION: nesting depth */
11185 AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11186 Table *pTab; /* Table for TK_COLUMN expressions. */
11190 ** The following are the meanings of bits in the Expr.flags field.
11192 #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
11193 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
11194 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
11195 #define EP_Error 0x000008 /* Expression contains one or more errors */
11196 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
11197 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11198 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11199 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11200 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */
11201 /* unused 0x000200 */
11202 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
11203 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11204 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
11205 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11206 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11207 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
11208 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11209 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11210 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
11211 #define EP_Constant 0x080000 /* Node is a constant */
11214 ** These macros can be used to test, set, or clear bits in the
11215 ** Expr.flags field.
11217 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
11218 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
11219 #define ExprSetProperty(E,P) (E)->flags|=(P)
11220 #define ExprClearProperty(E,P) (E)->flags&=~(P)
11222 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
11223 ** and Accreditation only. It works like ExprSetProperty() during VVA
11224 ** processes but is a no-op for delivery.
11226 #ifdef SQLITE_DEBUG
11227 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
11228 #else
11229 # define ExprSetVVAProperty(E,P)
11230 #endif
11233 ** Macros to determine the number of bytes required by a normal Expr
11234 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
11235 ** and an Expr struct with the EP_TokenOnly flag set.
11237 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
11238 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
11239 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
11242 ** Flags passed to the sqlite3ExprDup() function. See the header comment
11243 ** above sqlite3ExprDup() for details.
11245 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
11248 ** A list of expressions. Each expression may optionally have a
11249 ** name. An expr/name combination can be used in several ways, such
11250 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11251 ** list of "ID = expr" items in an UPDATE. A list of expressions can
11252 ** also be used as the argument to a function, in which case the a.zName
11253 ** field is not used.
11255 ** By default the Expr.zSpan field holds a human-readable description of
11256 ** the expression that is used in the generation of error messages and
11257 ** column labels. In this case, Expr.zSpan is typically the text of a
11258 ** column expression as it exists in a SELECT statement. However, if
11259 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11260 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
11261 ** form is used for name resolution with nested FROM clauses.
11263 struct ExprList {
11264 int nExpr; /* Number of expressions on the list */
11265 int iECursor; /* VDBE Cursor associated with this ExprList */
11266 struct ExprList_item { /* For each expression in the list */
11267 Expr *pExpr; /* The list of expressions */
11268 char *zName; /* Token associated with this expression */
11269 char *zSpan; /* Original text of the expression */
11270 u8 sortOrder; /* 1 for DESC or 0 for ASC */
11271 unsigned done :1; /* A flag to indicate when processing is finished */
11272 unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11273 unsigned reusable :1; /* Constant expression is reusable */
11274 union {
11275 struct {
11276 u16 iOrderByCol; /* For ORDER BY, column number in result set */
11277 u16 iAlias; /* Index into Parse.aAlias[] for zName */
11278 } x;
11279 int iConstExprReg; /* Register in which Expr value is cached */
11280 } u;
11281 } *a; /* Alloc a power of two greater or equal to nExpr */
11285 ** An instance of this structure is used by the parser to record both
11286 ** the parse tree for an expression and the span of input text for an
11287 ** expression.
11289 struct ExprSpan {
11290 Expr *pExpr; /* The expression parse tree */
11291 const char *zStart; /* First character of input text */
11292 const char *zEnd; /* One character past the end of input text */
11296 ** An instance of this structure can hold a simple list of identifiers,
11297 ** such as the list "a,b,c" in the following statements:
11299 ** INSERT INTO t(a,b,c) VALUES ...;
11300 ** CREATE INDEX idx ON t(a,b,c);
11301 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11303 ** The IdList.a.idx field is used when the IdList represents the list of
11304 ** column names after a table name in an INSERT statement. In the statement
11306 ** INSERT INTO t(a,b,c) ...
11308 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11310 struct IdList {
11311 struct IdList_item {
11312 char *zName; /* Name of the identifier */
11313 int idx; /* Index in some Table.aCol[] of a column named zName */
11314 } *a;
11315 int nId; /* Number of identifiers on the list */
11319 ** The bitmask datatype defined below is used for various optimizations.
11321 ** Changing this from a 64-bit to a 32-bit type limits the number of
11322 ** tables in a join to 32 instead of 64. But it also reduces the size
11323 ** of the library by 738 bytes on ix86.
11325 typedef u64 Bitmask;
11328 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
11330 #define BMS ((int)(sizeof(Bitmask)*8))
11333 ** A bit in a Bitmask
11335 #define MASKBIT(n) (((Bitmask)1)<<(n))
11336 #define MASKBIT32(n) (((unsigned int)1)<<(n))
11339 ** The following structure describes the FROM clause of a SELECT statement.
11340 ** Each table or subquery in the FROM clause is a separate element of
11341 ** the SrcList.a[] array.
11343 ** With the addition of multiple database support, the following structure
11344 ** can also be used to describe a particular table such as the table that
11345 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
11346 ** such a table must be a simple name: ID. But in SQLite, the table can
11347 ** now be identified by a database name, a dot, then the table name: ID.ID.
11349 ** The jointype starts out showing the join type between the current table
11350 ** and the next table on the list. The parser builds the list this way.
11351 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11352 ** jointype expresses the join between the table and the previous table.
11354 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11355 ** contains more than 63 columns and the 64-th or later column is used.
11357 struct SrcList {
11358 u8 nSrc; /* Number of tables or subqueries in the FROM clause */
11359 u8 nAlloc; /* Number of entries allocated in a[] below */
11360 struct SrcList_item {
11361 Schema *pSchema; /* Schema to which this item is fixed */
11362 char *zDatabase; /* Name of database holding this table */
11363 char *zName; /* Name of the table */
11364 char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
11365 Table *pTab; /* An SQL table corresponding to zName */
11366 Select *pSelect; /* A SELECT statement used in place of a table name */
11367 int addrFillSub; /* Address of subroutine to manifest a subquery */
11368 int regReturn; /* Register holding return address of addrFillSub */
11369 u8 jointype; /* Type of join between this able and the previous */
11370 unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
11371 unsigned isCorrelated :1; /* True if sub-query is correlated */
11372 unsigned viaCoroutine :1; /* Implemented as a co-routine */
11373 unsigned isRecursive :1; /* True for recursive reference in WITH */
11374 #ifndef SQLITE_OMIT_EXPLAIN
11375 u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
11376 #endif
11377 int iCursor; /* The VDBE cursor number used to access this table */
11378 Expr *pOn; /* The ON clause of a join */
11379 IdList *pUsing; /* The USING clause of a join */
11380 Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
11381 char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
11382 Index *pIndex; /* Index structure corresponding to zIndex, if any */
11383 } a[1]; /* One entry for each identifier on the list */
11387 ** Permitted values of the SrcList.a.jointype field
11389 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
11390 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
11391 #define JT_NATURAL 0x0004 /* True for a "natural" join */
11392 #define JT_LEFT 0x0008 /* Left outer join */
11393 #define JT_RIGHT 0x0010 /* Right outer join */
11394 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
11395 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
11399 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11400 ** and the WhereInfo.wctrlFlags member.
11402 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
11403 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
11404 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
11405 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
11406 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
11407 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
11408 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
11409 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
11410 #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
11411 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
11412 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
11413 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
11415 /* Allowed return values from sqlite3WhereIsDistinct()
11417 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
11418 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
11419 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
11420 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
11423 ** A NameContext defines a context in which to resolve table and column
11424 ** names. The context consists of a list of tables (the pSrcList) field and
11425 ** a list of named expression (pEList). The named expression list may
11426 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
11427 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
11428 ** pEList corresponds to the result set of a SELECT and is NULL for
11429 ** other statements.
11431 ** NameContexts can be nested. When resolving names, the inner-most
11432 ** context is searched first. If no match is found, the next outer
11433 ** context is checked. If there is still no match, the next context
11434 ** is checked. This process continues until either a match is found
11435 ** or all contexts are check. When a match is found, the nRef member of
11436 ** the context containing the match is incremented.
11438 ** Each subquery gets a new NameContext. The pNext field points to the
11439 ** NameContext in the parent query. Thus the process of scanning the
11440 ** NameContext list corresponds to searching through successively outer
11441 ** subqueries looking for a match.
11443 struct NameContext {
11444 Parse *pParse; /* The parser */
11445 SrcList *pSrcList; /* One or more tables used to resolve names */
11446 ExprList *pEList; /* Optional list of result-set columns */
11447 AggInfo *pAggInfo; /* Information about aggregates at this level */
11448 NameContext *pNext; /* Next outer name context. NULL for outermost */
11449 int nRef; /* Number of names resolved by this context */
11450 int nErr; /* Number of errors encountered while resolving names */
11451 u8 ncFlags; /* Zero or more NC_* flags defined below */
11455 ** Allowed values for the NameContext, ncFlags field.
11457 #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
11458 #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
11459 #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
11460 #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
11461 #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
11464 ** An instance of the following structure contains all information
11465 ** needed to generate code for a single SELECT statement.
11467 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
11468 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11469 ** limit and nOffset to the value of the offset (or 0 if there is not
11470 ** offset). But later on, nLimit and nOffset become the memory locations
11471 ** in the VDBE that record the limit and offset counters.
11473 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11474 ** These addresses must be stored so that we can go back and fill in
11475 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
11476 ** the number of columns in P2 can be computed at the same time
11477 ** as the OP_OpenEphm instruction is coded because not
11478 ** enough information about the compound query is known at that point.
11479 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11480 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
11481 ** sequences for the ORDER BY clause.
11483 struct Select {
11484 ExprList *pEList; /* The fields of the result */
11485 u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11486 u16 selFlags; /* Various SF_* values */
11487 int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
11488 int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
11489 u64 nSelectRow; /* Estimated number of result rows */
11490 SrcList *pSrc; /* The FROM clause */
11491 Expr *pWhere; /* The WHERE clause */
11492 ExprList *pGroupBy; /* The GROUP BY clause */
11493 Expr *pHaving; /* The HAVING clause */
11494 ExprList *pOrderBy; /* The ORDER BY clause */
11495 Select *pPrior; /* Prior select in a compound select statement */
11496 Select *pNext; /* Next select to the left in a compound */
11497 Select *pRightmost; /* Right-most select in a compound select statement */
11498 Expr *pLimit; /* LIMIT expression. NULL means not used. */
11499 Expr *pOffset; /* OFFSET expression. NULL means not used. */
11500 With *pWith; /* WITH clause attached to this select. Or NULL. */
11504 ** Allowed values for Select.selFlags. The "SF" prefix stands for
11505 ** "Select Flag".
11507 #define SF_Distinct 0x0001 /* Output should be DISTINCT */
11508 #define SF_Resolved 0x0002 /* Identifiers have been resolved */
11509 #define SF_Aggregate 0x0004 /* Contains aggregate functions */
11510 #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
11511 #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
11512 #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
11513 #define SF_UseSorter 0x0040 /* Sort using a sorter */
11514 #define SF_Values 0x0080 /* Synthesized from VALUES clause */
11515 #define SF_Materialize 0x0100 /* Force materialization of views */
11516 #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
11517 #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
11518 #define SF_Recursive 0x0800 /* The recursive part of a recursive CTE */
11522 ** The results of a SELECT can be distributed in several ways, as defined
11523 ** by one of the following macros. The "SRT" prefix means "SELECT Result
11524 ** Type".
11526 ** SRT_Union Store results as a key in a temporary index
11527 ** identified by pDest->iSDParm.
11529 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
11531 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
11532 ** set is not empty.
11534 ** SRT_Discard Throw the results away. This is used by SELECT
11535 ** statements within triggers whose only purpose is
11536 ** the side-effects of functions.
11538 ** All of the above are free to ignore their ORDER BY clause. Those that
11539 ** follow must honor the ORDER BY clause.
11541 ** SRT_Output Generate a row of output (using the OP_ResultRow
11542 ** opcode) for each row in the result set.
11544 ** SRT_Mem Only valid if the result is a single column.
11545 ** Store the first column of the first result row
11546 ** in register pDest->iSDParm then abandon the rest
11547 ** of the query. This destination implies "LIMIT 1".
11549 ** SRT_Set The result must be a single column. Store each
11550 ** row of result as the key in table pDest->iSDParm.
11551 ** Apply the affinity pDest->affSdst before storing
11552 ** results. Used to implement "IN (SELECT ...)".
11554 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
11555 ** the result there. The cursor is left open after
11556 ** returning. This is like SRT_Table except that
11557 ** this destination uses OP_OpenEphemeral to create
11558 ** the table first.
11560 ** SRT_Coroutine Generate a co-routine that returns a new row of
11561 ** results each time it is invoked. The entry point
11562 ** of the co-routine is stored in register pDest->iSDParm
11563 ** and the result row is stored in pDest->nDest registers
11564 ** starting with pDest->iSdst.
11566 ** SRT_Table Store results in temporary table pDest->iSDParm.
11567 ** This is like SRT_EphemTab except that the table
11568 ** is assumed to already be open.
11570 ** SRT_DistTable Store results in a temporary table pDest->iSDParm.
11571 ** But also use temporary table pDest->iSDParm+1 as
11572 ** a record of all prior results and ignore any duplicate
11573 ** rows. Name means: "Distinct Table".
11575 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
11576 ** an index). Append a sequence number so that all entries
11577 ** are distinct.
11579 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
11580 ** the same record has never been stored before. The
11581 ** index at pDest->iSDParm+1 hold all prior stores.
11583 #define SRT_Union 1 /* Store result as keys in an index */
11584 #define SRT_Except 2 /* Remove result from a UNION index */
11585 #define SRT_Exists 3 /* Store 1 if the result is not empty */
11586 #define SRT_Discard 4 /* Do not save the results anywhere */
11588 /* The ORDER BY clause is ignored for all of the above */
11589 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11591 #define SRT_Output 5 /* Output each row of result */
11592 #define SRT_Mem 6 /* Store result in a memory cell */
11593 #define SRT_Set 7 /* Store results as keys in an index */
11594 #define SRT_EphemTab 8 /* Create transient tab and store like SRT_Table */
11595 #define SRT_Coroutine 9 /* Generate a single row of result */
11596 #define SRT_Table 10 /* Store result as data with an automatic rowid */
11597 #define SRT_DistTable 11 /* Like SRT_Table, but unique results only */
11598 #define SRT_Queue 12 /* Store result in an queue */
11599 #define SRT_DistQueue 13 /* Like SRT_Queue, but unique results only */
11602 ** An instance of this object describes where to put of the results of
11603 ** a SELECT statement.
11605 struct SelectDest {
11606 u8 eDest; /* How to dispose of the results. On of SRT_* above. */
11607 char affSdst; /* Affinity used when eDest==SRT_Set */
11608 int iSDParm; /* A parameter used by the eDest disposal method */
11609 int iSdst; /* Base register where results are written */
11610 int nSdst; /* Number of registers allocated */
11611 ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
11615 ** During code generation of statements that do inserts into AUTOINCREMENT
11616 ** tables, the following information is attached to the Table.u.autoInc.p
11617 ** pointer of each autoincrement table to record some side information that
11618 ** the code generator needs. We have to keep per-table autoincrement
11619 ** information in case inserts are down within triggers. Triggers do not
11620 ** normally coordinate their activities, but we do need to coordinate the
11621 ** loading and saving of autoincrement information.
11623 struct AutoincInfo {
11624 AutoincInfo *pNext; /* Next info block in a list of them all */
11625 Table *pTab; /* Table this info block refers to */
11626 int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
11627 int regCtr; /* Memory register holding the rowid counter */
11631 ** Size of the column cache
11633 #ifndef SQLITE_N_COLCACHE
11634 # define SQLITE_N_COLCACHE 10
11635 #endif
11638 ** At least one instance of the following structure is created for each
11639 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11640 ** statement. All such objects are stored in the linked list headed at
11641 ** Parse.pTriggerPrg and deleted once statement compilation has been
11642 ** completed.
11644 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11645 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11646 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11647 ** The Parse.pTriggerPrg list never contains two entries with the same
11648 ** values for both pTrigger and orconf.
11650 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11651 ** accessed (or set to 0 for triggers fired as a result of INSERT
11652 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11653 ** a mask of new.* columns used by the program.
11655 struct TriggerPrg {
11656 Trigger *pTrigger; /* Trigger this program was coded from */
11657 TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
11658 SubProgram *pProgram; /* Program implementing pTrigger/orconf */
11659 int orconf; /* Default ON CONFLICT policy */
11660 u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
11664 ** The yDbMask datatype for the bitmask of all attached databases.
11666 #if SQLITE_MAX_ATTACHED>30
11667 typedef sqlite3_uint64 yDbMask;
11668 #else
11669 typedef unsigned int yDbMask;
11670 #endif
11673 ** An SQL parser context. A copy of this structure is passed through
11674 ** the parser and down into all the parser action routine in order to
11675 ** carry around information that is global to the entire parse.
11677 ** The structure is divided into two parts. When the parser and code
11678 ** generate call themselves recursively, the first part of the structure
11679 ** is constant but the second part is reset at the beginning and end of
11680 ** each recursion.
11682 ** The nTableLock and aTableLock variables are only used if the shared-cache
11683 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11684 ** used to store the set of table-locks required by the statement being
11685 ** compiled. Function sqlite3TableLock() is used to add entries to the
11686 ** list.
11688 struct Parse {
11689 sqlite3 *db; /* The main database structure */
11690 char *zErrMsg; /* An error message */
11691 Vdbe *pVdbe; /* An engine for executing database bytecode */
11692 int rc; /* Return code from execution */
11693 u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
11694 u8 checkSchema; /* Causes schema cookie check after an error */
11695 u8 nested; /* Number of nested calls to the parser/code generator */
11696 u8 nTempReg; /* Number of temporary registers in aTempReg[] */
11697 u8 nTempInUse; /* Number of aTempReg[] currently checked out */
11698 u8 nColCache; /* Number of entries in aColCache[] */
11699 u8 iColCache; /* Next entry in aColCache[] to replace */
11700 u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
11701 u8 mayAbort; /* True if statement may throw an ABORT exception */
11702 u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
11703 int aTempReg[8]; /* Holding area for temporary registers */
11704 int nRangeReg; /* Size of the temporary register block */
11705 int iRangeReg; /* First register in temporary register block */
11706 int nErr; /* Number of errors seen */
11707 int nTab; /* Number of previously allocated VDBE cursors */
11708 int nMem; /* Number of memory cells used so far */
11709 int nSet; /* Number of sets used so far */
11710 int nOnce; /* Number of OP_Once instructions so far */
11711 int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
11712 int nLabel; /* Number of labels used */
11713 int *aLabel; /* Space to hold the labels */
11714 int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
11715 int ckBase; /* Base register of data during check constraints */
11716 int iPartIdxTab; /* Table corresponding to a partial index */
11717 int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11718 int iCacheCnt; /* Counter used to generate aColCache[].lru values */
11719 struct yColCache {
11720 int iTable; /* Table cursor number */
11721 int iColumn; /* Table column number */
11722 u8 tempReg; /* iReg is a temp register that needs to be freed */
11723 int iLevel; /* Nesting level */
11724 int iReg; /* Reg with value of this column. 0 means none. */
11725 int lru; /* Least recently used entry has the smallest value */
11726 } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
11727 ExprList *pConstExpr;/* Constant expressions */
11728 yDbMask writeMask; /* Start a write transaction on these databases */
11729 yDbMask cookieMask; /* Bitmask of schema verified databases */
11730 int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
11731 int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
11732 int regRowid; /* Register holding rowid of CREATE TABLE entry */
11733 int regRoot; /* Register holding root page number for new objects */
11734 int nMaxArg; /* Max args passed to user function by sub-program */
11735 Token constraintName;/* Name of the constraint currently being parsed */
11736 #ifndef SQLITE_OMIT_SHARED_CACHE
11737 int nTableLock; /* Number of locks in aTableLock */
11738 TableLock *aTableLock; /* Required table locks for shared-cache mode */
11739 #endif
11740 AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
11742 /* Information used while coding trigger programs. */
11743 Parse *pToplevel; /* Parse structure for main program (or NULL) */
11744 Table *pTriggerTab; /* Table triggers are being coded for */
11745 int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
11746 int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */
11747 u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
11748 u32 oldmask; /* Mask of old.* columns referenced */
11749 u32 newmask; /* Mask of new.* columns referenced */
11750 u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
11751 u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
11752 u8 disableTriggers; /* True to disable triggers */
11754 /* Above is constant between recursions. Below is reset before and after
11755 ** each recursion */
11757 int nVar; /* Number of '?' variables seen in the SQL so far */
11758 int nzVar; /* Number of available slots in azVar[] */
11759 u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
11760 u8 explain; /* True if the EXPLAIN flag is found on the query */
11761 #ifndef SQLITE_OMIT_VIRTUALTABLE
11762 u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
11763 int nVtabLock; /* Number of virtual tables to lock */
11764 #endif
11765 int nAlias; /* Number of aliased result set columns */
11766 int nHeight; /* Expression tree height of current sub-select */
11767 #ifndef SQLITE_OMIT_EXPLAIN
11768 int iSelectId; /* ID of current select for EXPLAIN output */
11769 int iNextSelectId; /* Next available select ID for EXPLAIN output */
11770 #endif
11771 char **azVar; /* Pointers to names of parameters */
11772 Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
11773 const char *zTail; /* All SQL text past the last semicolon parsed */
11774 Table *pNewTable; /* A table being constructed by CREATE TABLE */
11775 Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
11776 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11777 Token sNameToken; /* Token with unqualified schema object name */
11778 Token sLastToken; /* The last token parsed */
11779 #ifndef SQLITE_OMIT_VIRTUALTABLE
11780 Token sArg; /* Complete text of a module argument */
11781 Table **apVtabLock; /* Pointer to virtual tables needing locking */
11782 #endif
11783 Table *pZombieTab; /* List of Table objects to delete after code gen */
11784 TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
11785 With *pWith; /* Current WITH clause, or NULL */
11786 u8 bFreeWith; /* True if pWith should be freed with parser */
11790 ** Return true if currently inside an sqlite3_declare_vtab() call.
11792 #ifdef SQLITE_OMIT_VIRTUALTABLE
11793 #define IN_DECLARE_VTAB 0
11794 #else
11795 #define IN_DECLARE_VTAB (pParse->declareVtab)
11796 #endif
11799 ** An instance of the following structure can be declared on a stack and used
11800 ** to save the Parse.zAuthContext value so that it can be restored later.
11802 struct AuthContext {
11803 const char *zAuthContext; /* Put saved Parse.zAuthContext here */
11804 Parse *pParse; /* The Parse structure */
11808 ** Bitfield flags for P5 value in various opcodes.
11810 #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
11811 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
11812 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
11813 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
11814 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
11815 #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
11816 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
11817 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
11818 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
11819 #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
11820 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
11823 * Each trigger present in the database schema is stored as an instance of
11824 * struct Trigger.
11826 * Pointers to instances of struct Trigger are stored in two ways.
11827 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11828 * database). This allows Trigger structures to be retrieved by name.
11829 * 2. All triggers associated with a single table form a linked list, using the
11830 * pNext member of struct Trigger. A pointer to the first element of the
11831 * linked list is stored as the "pTrigger" member of the associated
11832 * struct Table.
11834 * The "step_list" member points to the first element of a linked list
11835 * containing the SQL statements specified as the trigger program.
11837 struct Trigger {
11838 char *zName; /* The name of the trigger */
11839 char *table; /* The table or view to which the trigger applies */
11840 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
11841 u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11842 Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
11843 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
11844 the <column-list> is stored here */
11845 Schema *pSchema; /* Schema containing the trigger */
11846 Schema *pTabSchema; /* Schema containing the table */
11847 TriggerStep *step_list; /* Link list of trigger program steps */
11848 Trigger *pNext; /* Next trigger associated with the table */
11852 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
11853 ** determine which.
11855 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11856 ** In that cases, the constants below can be ORed together.
11858 #define TRIGGER_BEFORE 1
11859 #define TRIGGER_AFTER 2
11862 * An instance of struct TriggerStep is used to store a single SQL statement
11863 * that is a part of a trigger-program.
11865 * Instances of struct TriggerStep are stored in a singly linked list (linked
11866 * using the "pNext" member) referenced by the "step_list" member of the
11867 * associated struct Trigger instance. The first element of the linked list is
11868 * the first step of the trigger-program.
11870 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11871 * "SELECT" statement. The meanings of the other members is determined by the
11872 * value of "op" as follows:
11874 * (op == TK_INSERT)
11875 * orconf -> stores the ON CONFLICT algorithm
11876 * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
11877 * this stores a pointer to the SELECT statement. Otherwise NULL.
11878 * target -> A token holding the quoted name of the table to insert into.
11879 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11880 * this stores values to be inserted. Otherwise NULL.
11881 * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11882 * statement, then this stores the column-names to be
11883 * inserted into.
11885 * (op == TK_DELETE)
11886 * target -> A token holding the quoted name of the table to delete from.
11887 * pWhere -> The WHERE clause of the DELETE statement if one is specified.
11888 * Otherwise NULL.
11890 * (op == TK_UPDATE)
11891 * target -> A token holding the quoted name of the table to update rows of.
11892 * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
11893 * Otherwise NULL.
11894 * pExprList -> A list of the columns to update and the expressions to update
11895 * them to. See sqlite3Update() documentation of "pChanges"
11896 * argument.
11899 struct TriggerStep {
11900 u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11901 u8 orconf; /* OE_Rollback etc. */
11902 Trigger *pTrig; /* The trigger that this step is a part of */
11903 Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11904 Token target; /* Target table for DELETE, UPDATE, INSERT */
11905 Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
11906 ExprList *pExprList; /* SET clause for UPDATE. */
11907 IdList *pIdList; /* Column names for INSERT */
11908 TriggerStep *pNext; /* Next in the link-list */
11909 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
11913 ** The following structure contains information used by the sqliteFix...
11914 ** routines as they walk the parse tree to make database references
11915 ** explicit.
11917 typedef struct DbFixer DbFixer;
11918 struct DbFixer {
11919 Parse *pParse; /* The parsing context. Error messages written here */
11920 Schema *pSchema; /* Fix items to this schema */
11921 int bVarOnly; /* Check for variable references only */
11922 const char *zDb; /* Make sure all objects are contained in this database */
11923 const char *zType; /* Type of the container - used for error messages */
11924 const Token *pName; /* Name of the container - used for error messages */
11928 ** An objected used to accumulate the text of a string where we
11929 ** do not necessarily know how big the string will be in the end.
11931 struct StrAccum {
11932 sqlite3 *db; /* Optional database for lookaside. Can be NULL */
11933 char *zBase; /* A base allocation. Not from malloc. */
11934 char *zText; /* The string collected so far */
11935 int nChar; /* Length of the string so far */
11936 int nAlloc; /* Amount of space allocated in zText */
11937 int mxAlloc; /* Maximum allowed string length */
11938 u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
11939 u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
11941 #define STRACCUM_NOMEM 1
11942 #define STRACCUM_TOOBIG 2
11945 ** A pointer to this structure is used to communicate information
11946 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11948 typedef struct {
11949 sqlite3 *db; /* The database being initialized */
11950 char **pzErrMsg; /* Error message stored here */
11951 int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
11952 int rc; /* Result code stored here */
11953 } InitData;
11956 ** Structure containing global configuration data for the SQLite library.
11958 ** This structure also contains some state information.
11960 struct Sqlite3Config {
11961 int bMemstat; /* True to enable memory status */
11962 int bCoreMutex; /* True to enable core mutexing */
11963 int bFullMutex; /* True to enable full mutexing */
11964 int bOpenUri; /* True to interpret filenames as URIs */
11965 int bUseCis; /* Use covering indices for full-scans */
11966 int mxStrlen; /* Maximum string length */
11967 int neverCorrupt; /* Database is always well-formed */
11968 int szLookaside; /* Default lookaside buffer size */
11969 int nLookaside; /* Default lookaside buffer count */
11970 sqlite3_mem_methods m; /* Low-level memory allocation interface */
11971 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
11972 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
11973 void *pHeap; /* Heap storage space */
11974 int nHeap; /* Size of pHeap[] */
11975 int mnReq, mxReq; /* Min and max heap requests sizes */
11976 sqlite3_int64 szMmap; /* mmap() space per open file */
11977 sqlite3_int64 mxMmap; /* Maximum value for szMmap */
11978 void *pScratch; /* Scratch memory */
11979 int szScratch; /* Size of each scratch buffer */
11980 int nScratch; /* Number of scratch buffers */
11981 void *pPage; /* Page cache memory */
11982 int szPage; /* Size of each page in pPage[] */
11983 int nPage; /* Number of pages in pPage[] */
11984 int mxParserStack; /* maximum depth of the parser stack */
11985 int sharedCacheEnabled; /* true if shared-cache mode enabled */
11986 /* The above might be initialized to non-zero. The following need to always
11987 ** initially be zero, however. */
11988 int isInit; /* True after initialization has finished */
11989 int inProgress; /* True while initialization in progress */
11990 int isMutexInit; /* True after mutexes are initialized */
11991 int isMallocInit; /* True after malloc is initialized */
11992 int isPCacheInit; /* True after malloc is initialized */
11993 sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
11994 int nRefInitMutex; /* Number of users of pInitMutex */
11995 void (*xLog)(void*,int,const char*); /* Function for logging */
11996 void *pLogArg; /* First argument to xLog() */
11997 int bLocaltimeFault; /* True to fail localtime() calls */
11998 #ifdef SQLITE_ENABLE_SQLLOG
11999 void(*xSqllog)(void*,sqlite3*,const char*, int);
12000 void *pSqllogArg;
12001 #endif
12005 ** This macro is used inside of assert() statements to indicate that
12006 ** the assert is only valid on a well-formed database. Instead of:
12008 ** assert( X );
12010 ** One writes:
12012 ** assert( X || CORRUPT_DB );
12014 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
12015 ** that the database is definitely corrupt, only that it might be corrupt.
12016 ** For most test cases, CORRUPT_DB is set to false using a special
12017 ** sqlite3_test_control(). This enables assert() statements to prove
12018 ** things that are always true for well-formed databases.
12020 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
12023 ** Context pointer passed down through the tree-walk.
12025 struct Walker {
12026 int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
12027 int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
12028 void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12029 Parse *pParse; /* Parser context. */
12030 int walkerDepth; /* Number of subqueries */
12031 union { /* Extra data for callback */
12032 NameContext *pNC; /* Naming context */
12033 int i; /* Integer value */
12034 SrcList *pSrcList; /* FROM clause */
12035 struct SrcCount *pSrcCount; /* Counting column references */
12036 } u;
12039 /* Forward declarations */
12040 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12041 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12042 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12043 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12044 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12047 ** Return code from the parse-tree walking primitives and their
12048 ** callbacks.
12050 #define WRC_Continue 0 /* Continue down into children */
12051 #define WRC_Prune 1 /* Omit children but continue walking siblings */
12052 #define WRC_Abort 2 /* Abandon the tree walk */
12055 ** An instance of this structure represents a set of one or more CTEs
12056 ** (common table expressions) created by a single WITH clause.
12058 struct With {
12059 int nCte; /* Number of CTEs in the WITH clause */
12060 With *pOuter; /* Containing WITH clause, or NULL */
12061 struct Cte { /* For each CTE in the WITH clause.... */
12062 char *zName; /* Name of this CTE */
12063 ExprList *pCols; /* List of explicit column names, or NULL */
12064 Select *pSelect; /* The definition of this CTE */
12065 const char *zErr; /* Error message for circular references */
12066 } a[1];
12070 ** Assuming zIn points to the first byte of a UTF-8 character,
12071 ** advance zIn to point to the first byte of the next UTF-8 character.
12073 #define SQLITE_SKIP_UTF8(zIn) { \
12074 if( (*(zIn++))>=0xc0 ){ \
12075 while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
12080 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
12081 ** the same name but without the _BKPT suffix. These macros invoke
12082 ** routines that report the line-number on which the error originated
12083 ** using sqlite3_log(). The routines also provide a convenient place
12084 ** to set a debugger breakpoint.
12086 SQLITE_PRIVATE int sqlite3CorruptError(int);
12087 SQLITE_PRIVATE int sqlite3MisuseError(int);
12088 SQLITE_PRIVATE int sqlite3CantopenError(int);
12089 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12090 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12091 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12095 ** FTS4 is really an extension for FTS3. It is enabled using the
12096 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
12097 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
12099 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12100 # define SQLITE_ENABLE_FTS3
12101 #endif
12104 ** The ctype.h header is needed for non-ASCII systems. It is also
12105 ** needed by FTS3 when FTS3 is included in the amalgamation.
12107 #if !defined(SQLITE_ASCII) || \
12108 (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12109 # include <ctype.h>
12110 #endif
12113 ** The following macros mimic the standard library functions toupper(),
12114 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12115 ** sqlite versions only work for ASCII characters, regardless of locale.
12117 #ifdef SQLITE_ASCII
12118 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12119 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12120 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12121 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12122 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12123 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12124 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
12125 #else
12126 # define sqlite3Toupper(x) toupper((unsigned char)(x))
12127 # define sqlite3Isspace(x) isspace((unsigned char)(x))
12128 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
12129 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
12130 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
12131 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
12132 # define sqlite3Tolower(x) tolower((unsigned char)(x))
12133 #endif
12136 ** Internal function prototypes
12138 #define sqlite3StrICmp sqlite3_stricmp
12139 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12140 #define sqlite3StrNICmp sqlite3_strnicmp
12142 SQLITE_PRIVATE int sqlite3MallocInit(void);
12143 SQLITE_PRIVATE void sqlite3MallocEnd(void);
12144 SQLITE_PRIVATE void *sqlite3Malloc(int);
12145 SQLITE_PRIVATE void *sqlite3MallocZero(int);
12146 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
12147 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
12148 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12149 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
12150 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
12151 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
12152 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
12153 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12154 SQLITE_PRIVATE int sqlite3MallocSize(void*);
12155 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12156 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12157 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12158 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
12159 SQLITE_PRIVATE void sqlite3PageFree(void*);
12160 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
12161 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
12162 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
12165 ** On systems with ample stack space and that support alloca(), make
12166 ** use of alloca() to obtain space for large automatic objects. By default,
12167 ** obtain space from malloc().
12169 ** The alloca() routine never returns NULL. This will cause code paths
12170 ** that deal with sqlite3StackAlloc() failures to be unreachable.
12172 #ifdef SQLITE_USE_ALLOCA
12173 # define sqlite3StackAllocRaw(D,N) alloca(N)
12174 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
12175 # define sqlite3StackFree(D,P)
12176 #else
12177 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
12178 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
12179 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
12180 #endif
12182 #ifdef SQLITE_ENABLE_MEMSYS3
12183 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12184 #endif
12185 #ifdef SQLITE_ENABLE_MEMSYS5
12186 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12187 #endif
12190 #ifndef SQLITE_MUTEX_OMIT
12191 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12192 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12193 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
12194 SQLITE_PRIVATE int sqlite3MutexInit(void);
12195 SQLITE_PRIVATE int sqlite3MutexEnd(void);
12196 #endif
12198 SQLITE_PRIVATE int sqlite3StatusValue(int);
12199 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
12200 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12202 #ifndef SQLITE_OMIT_FLOATING_POINT
12203 SQLITE_PRIVATE int sqlite3IsNaN(double);
12204 #else
12205 # define sqlite3IsNaN(X) 0
12206 #endif
12209 ** An instance of the following structure holds information about SQL
12210 ** functions arguments that are the parameters to the printf() function.
12212 struct PrintfArguments {
12213 int nArg; /* Total number of arguments */
12214 int nUsed; /* Number of arguments used so far */
12215 sqlite3_value **apArg; /* The argument values */
12218 #define SQLITE_PRINTF_INTERNAL 0x01
12219 #define SQLITE_PRINTF_SQLFUNC 0x02
12220 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
12221 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
12222 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12223 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12224 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12225 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12226 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
12227 #endif
12228 #if defined(SQLITE_TEST)
12229 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
12230 #endif
12232 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
12233 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
12234 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
12235 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
12236 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
12237 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
12238 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
12239 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
12240 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
12241 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
12242 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
12243 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
12244 #else
12245 # define sqlite3ExplainBegin(X)
12246 # define sqlite3ExplainSelect(A,B)
12247 # define sqlite3ExplainExpr(A,B)
12248 # define sqlite3ExplainExprList(A,B)
12249 # define sqlite3ExplainFinish(X)
12250 # define sqlite3VdbeExplanation(X) 0
12251 #endif
12254 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
12255 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
12256 SQLITE_PRIVATE int sqlite3Dequote(char*);
12257 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
12258 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
12259 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
12260 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
12261 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
12262 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
12263 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
12264 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
12265 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
12266 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
12267 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
12268 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
12269 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
12270 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
12271 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
12272 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
12273 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
12274 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
12275 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
12276 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
12277 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
12278 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
12279 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
12280 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
12281 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
12282 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
12283 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
12284 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
12285 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
12286 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
12287 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
12288 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
12289 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
12290 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
12291 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
12292 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
12293 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
12294 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
12295 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
12296 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
12297 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
12298 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
12299 sqlite3_vfs**,char**,char **);
12300 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
12301 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
12303 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
12304 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12305 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12306 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12307 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12308 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12309 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12311 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12312 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12313 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12314 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
12315 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12317 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12319 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12320 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
12321 #else
12322 # define sqlite3ViewGetColumnNames(A,B) 0
12323 #endif
12325 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12326 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12327 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12328 #ifndef SQLITE_OMIT_AUTOINCREMENT
12329 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
12330 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
12331 #else
12332 # define sqlite3AutoincrementBegin(X)
12333 # define sqlite3AutoincrementEnd(X)
12334 #endif
12335 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
12336 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
12337 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12338 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12339 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12340 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12341 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12342 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12343 Token*, Select*, Expr*, IdList*);
12344 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12345 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12346 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12347 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12348 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12349 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12350 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
12351 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12352 Expr*, int, int);
12353 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12354 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12355 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12356 Expr*,ExprList*,u16,Expr*,Expr*);
12357 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12358 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12359 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12360 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12361 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12362 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12363 #endif
12364 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12365 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12366 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12367 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12368 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
12369 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
12370 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
12371 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
12372 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
12373 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
12374 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12375 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12376 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12377 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12378 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12379 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
12380 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12381 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12382 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12383 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
12384 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
12385 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12386 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12387 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12388 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
12389 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
12390 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
12391 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12392 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12393 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12394 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12395 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12396 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12397 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12398 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12399 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12400 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12401 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12402 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
12403 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
12404 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
12405 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12406 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12407 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12408 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12409 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12410 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12411 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12412 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12413 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12414 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12415 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12416 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12417 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12418 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12419 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12420 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12421 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12422 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
12423 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12424 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12425 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
12426 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12427 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12428 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
12429 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
12430 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
12431 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
12432 u8,u8,int,int*);
12433 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
12434 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
12435 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12436 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12437 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12438 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
12439 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
12440 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
12441 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12442 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12443 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12444 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12445 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12446 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12447 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12448 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12449 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12450 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12451 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12452 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12453 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12455 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12456 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12457 #endif
12459 #ifndef SQLITE_OMIT_TRIGGER
12460 SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12461 Expr*,int, int);
12462 SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12463 SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
12464 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
12465 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12466 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
12467 SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12468 int, int, int);
12469 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12470 void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12471 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12472 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12473 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12474 Select*,u8);
12475 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12476 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12477 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12478 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12479 SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12480 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12481 #else
12482 # define sqlite3TriggersExist(B,C,D,E,F) 0
12483 # define sqlite3DeleteTrigger(A,B)
12484 # define sqlite3DropTriggerPtr(A,B)
12485 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12486 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12487 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12488 # define sqlite3TriggerList(X, Y) 0
12489 # define sqlite3ParseToplevel(p) p
12490 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12491 #endif
12493 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12494 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12495 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12496 #ifndef SQLITE_OMIT_AUTHORIZATION
12497 SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12498 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12499 SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12500 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
12501 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12502 #else
12503 # define sqlite3AuthRead(a,b,c,d)
12504 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
12505 # define sqlite3AuthContextPush(a,b,c)
12506 # define sqlite3AuthContextPop(a) ((void)(a))
12507 #endif
12508 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12509 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12510 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12511 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12512 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12513 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12514 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12515 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12516 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12517 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12518 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12519 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12520 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12521 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12522 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
12523 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
12524 #ifndef SQLITE_OMIT_VIRTUALTABLE
12525 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
12526 #endif
12527 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
12530 ** Routines to read and write variable-length integers. These used to
12531 ** be defined locally, but now we use the varint routines in the util.c
12532 ** file. Code should use the MACRO forms below, as the Varint32 versions
12533 ** are coded to assume the single byte case is already handled (which
12534 ** the MACRO form does).
12536 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12537 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12538 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12539 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12540 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12543 ** The header of a record consists of a sequence variable-length integers.
12544 ** These integers are almost always small and are encoded as a single byte.
12545 ** The following macros take advantage this fact to provide a fast encode
12546 ** and decode of the integers in a record header. It is faster for the common
12547 ** case where the integer is a single byte. It is a little slower when the
12548 ** integer is two or more bytes. But overall it is faster.
12550 ** The following expressions are equivalent:
12552 ** x = sqlite3GetVarint32( A, &B );
12553 ** x = sqlite3PutVarint32( A, B );
12555 ** x = getVarint32( A, B );
12556 ** x = putVarint32( A, B );
12559 #define getVarint32(A,B) \
12560 (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12561 #define putVarint32(A,B) \
12562 (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12563 sqlite3PutVarint32((A),(B)))
12564 #define getVarint sqlite3GetVarint
12565 #define putVarint sqlite3PutVarint
12568 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12569 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12570 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12571 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12572 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12573 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12574 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12575 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12576 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12577 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12579 #if defined(SQLITE_TEST)
12580 SQLITE_PRIVATE const char *sqlite3ErrName(int);
12581 #endif
12583 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12584 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12585 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12586 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12587 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12588 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12589 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12590 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12591 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12592 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12593 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12594 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12595 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12596 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12597 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12598 #ifdef SQLITE_ENABLE_8_3_NAMES
12599 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12600 #else
12601 # define sqlite3FileSuffix3(X,Y)
12602 #endif
12603 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12605 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12606 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12607 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
12608 void(*)(void*));
12609 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
12610 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12611 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12612 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12613 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12614 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12615 #ifndef SQLITE_AMALGAMATION
12616 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12617 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12618 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12619 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12620 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12621 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12622 #ifndef SQLITE_OMIT_WSD
12623 SQLITE_PRIVATE int sqlite3PendingByte;
12624 #endif
12625 #endif
12626 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12627 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12628 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12629 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12630 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12631 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12632 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12633 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12634 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12635 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12636 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12637 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12638 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
12639 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12640 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12641 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12642 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12643 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12644 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
12645 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12646 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12647 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12648 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12649 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12650 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12651 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12652 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12653 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12654 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12655 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12656 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12657 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12658 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
12659 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
12660 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
12661 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
12662 #ifdef SQLITE_DEBUG
12663 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
12664 #endif
12665 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
12666 void (*)(sqlite3_context*,int,sqlite3_value **),
12667 void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12668 FuncDestructor *pDestructor
12670 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12671 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12673 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12674 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12675 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
12676 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12677 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12678 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12679 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12680 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12682 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12683 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12685 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
12686 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
12687 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
12688 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
12689 #endif
12692 ** The interface to the LEMON-generated parser
12694 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12695 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12696 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12697 #ifdef YYTRACKMAXSTACKDEPTH
12698 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
12699 #endif
12701 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12702 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12703 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
12704 #else
12705 # define sqlite3CloseExtensions(X)
12706 #endif
12708 #ifndef SQLITE_OMIT_SHARED_CACHE
12709 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
12710 #else
12711 #define sqlite3TableLock(v,w,x,y,z)
12712 #endif
12714 #ifdef SQLITE_TEST
12715 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
12716 #endif
12718 #ifdef SQLITE_OMIT_VIRTUALTABLE
12719 # define sqlite3VtabClear(Y)
12720 # define sqlite3VtabSync(X,Y) SQLITE_OK
12721 # define sqlite3VtabRollback(X)
12722 # define sqlite3VtabCommit(X)
12723 # define sqlite3VtabInSync(db) 0
12724 # define sqlite3VtabLock(X)
12725 # define sqlite3VtabUnlock(X)
12726 # define sqlite3VtabUnlockList(X)
12727 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12728 # define sqlite3GetVTable(X,Y) ((VTable*)0)
12729 #else
12730 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
12731 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12732 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
12733 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
12734 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
12735 SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
12736 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
12737 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
12738 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
12739 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
12740 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
12741 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12742 #endif
12743 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12744 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12745 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12746 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12747 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12748 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12749 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12750 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12751 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12752 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12753 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12754 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
12755 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12756 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12757 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
12758 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12759 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12760 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12761 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12762 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12763 #ifndef SQLITE_OMIT_WAL
12764 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12765 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12766 #endif
12767 #ifndef SQLITE_OMIT_CTE
12768 SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
12769 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
12770 SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
12771 #else
12772 #define sqlite3WithPush(x,y,z)
12773 #define sqlite3WithDelete(x,y)
12774 #endif
12776 /* Declarations for functions in fkey.c. All of these are replaced by
12777 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12778 ** key functionality is available. If OMIT_TRIGGER is defined but
12779 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12780 ** this case foreign keys are parsed, but no other functionality is
12781 ** provided (enforcement of FK constraints requires the triggers sub-system).
12783 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12784 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
12785 SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12786 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
12787 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
12788 SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
12789 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
12790 #else
12791 #define sqlite3FkActions(a,b,c,d,e,f)
12792 #define sqlite3FkCheck(a,b,c,d,e,f)
12793 #define sqlite3FkDropTable(a,b,c)
12794 #define sqlite3FkOldmask(a,b) 0
12795 #define sqlite3FkRequired(a,b,c,d) 0
12796 #endif
12797 #ifndef SQLITE_OMIT_FOREIGN_KEY
12798 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
12799 SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12800 #else
12801 #define sqlite3FkDelete(a,b)
12802 #define sqlite3FkLocateIndex(a,b,c,d,e)
12803 #endif
12807 ** Available fault injectors. Should be numbered beginning with 0.
12809 #define SQLITE_FAULTINJECTOR_MALLOC 0
12810 #define SQLITE_FAULTINJECTOR_COUNT 1
12813 ** The interface to the code in fault.c used for identifying "benign"
12814 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12815 ** is not defined.
12817 #ifndef SQLITE_OMIT_BUILTIN_TEST
12818 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
12819 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
12820 #else
12821 #define sqlite3BeginBenignMalloc()
12822 #define sqlite3EndBenignMalloc()
12823 #endif
12825 #define IN_INDEX_ROWID 1
12826 #define IN_INDEX_EPH 2
12827 #define IN_INDEX_INDEX_ASC 3
12828 #define IN_INDEX_INDEX_DESC 4
12829 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12831 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12832 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12833 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
12834 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
12835 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
12836 #else
12837 #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12838 #define sqlite3JournalExists(p) 1
12839 #endif
12841 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12842 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12843 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12845 #if SQLITE_MAX_EXPR_DEPTH>0
12846 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12847 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
12848 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
12849 #else
12850 #define sqlite3ExprSetHeight(x,y)
12851 #define sqlite3SelectExprHeight(x) 0
12852 #define sqlite3ExprCheckHeight(x,y)
12853 #endif
12855 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12856 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12858 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12859 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12860 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
12861 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
12862 #else
12863 #define sqlite3ConnectionBlocked(x,y)
12864 #define sqlite3ConnectionUnlocked(x)
12865 #define sqlite3ConnectionClosed(x)
12866 #endif
12868 #ifdef SQLITE_DEBUG
12869 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
12870 #endif
12873 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12874 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12875 ** print I/O tracing messages.
12877 #ifdef SQLITE_ENABLE_IOTRACE
12878 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12879 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
12880 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12881 #else
12882 # define IOTRACE(A)
12883 # define sqlite3VdbeIOTraceSql(X)
12884 #endif
12887 ** These routines are available for the mem2.c debugging memory allocator
12888 ** only. They are used to verify that different "types" of memory
12889 ** allocations are properly tracked by the system.
12891 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12892 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
12893 ** a single bit set.
12895 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12896 ** argument match the type set by the previous sqlite3MemdebugSetType().
12897 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12899 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12900 ** argument match the type set by the previous sqlite3MemdebugSetType().
12902 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12903 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
12904 ** it might have been allocated by lookaside, except the allocation was
12905 ** too large or lookaside was already full. It is important to verify
12906 ** that allocations that might have been satisfied by lookaside are not
12907 ** passed back to non-lookaside free() routines. Asserts such as the
12908 ** example above are placed on the non-lookaside free() routines to verify
12909 ** this constraint.
12911 ** All of this is no-op for a production build. It only comes into
12912 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12914 #ifdef SQLITE_MEMDEBUG
12915 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
12916 SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
12917 SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
12918 #else
12919 # define sqlite3MemdebugSetType(X,Y) /* no-op */
12920 # define sqlite3MemdebugHasType(X,Y) 1
12921 # define sqlite3MemdebugNoType(X,Y) 1
12922 #endif
12923 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
12924 #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
12925 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
12926 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
12927 #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
12929 #endif /* _SQLITEINT_H_ */
12931 /************** End of sqliteInt.h *******************************************/
12932 /************** Begin file global.c ******************************************/
12934 ** 2008 June 13
12936 ** The author disclaims copyright to this source code. In place of
12937 ** a legal notice, here is a blessing:
12939 ** May you do good and not evil.
12940 ** May you find forgiveness for yourself and forgive others.
12941 ** May you share freely, never taking more than you give.
12943 *************************************************************************
12945 ** This file contains definitions of global variables and contants.
12948 /* An array to map all upper-case characters into their corresponding
12949 ** lower-case character.
12951 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
12952 ** handle case conversions for the UTF character set since the tables
12953 ** involved are nearly as big or bigger than SQLite itself.
12955 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12956 #ifdef SQLITE_ASCII
12957 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
12958 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12959 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12960 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12961 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12962 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12963 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12964 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12965 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12966 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12967 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12968 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12969 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12970 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12971 252,253,254,255
12972 #endif
12973 #ifdef SQLITE_EBCDIC
12974 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
12975 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12976 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12977 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12978 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12979 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12980 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12981 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12982 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12983 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12984 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12985 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12986 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12987 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12988 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12989 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12990 #endif
12994 ** The following 256 byte lookup table is used to support SQLites built-in
12995 ** equivalents to the following standard library functions:
12997 ** isspace() 0x01
12998 ** isalpha() 0x02
12999 ** isdigit() 0x04
13000 ** isalnum() 0x06
13001 ** isxdigit() 0x08
13002 ** toupper() 0x20
13003 ** SQLite identifier character 0x40
13005 ** Bit 0x20 is set if the mapped character requires translation to upper
13006 ** case. i.e. if the character is a lower-case ASCII character.
13007 ** If x is a lower-case ASCII character, then its upper-case equivalent
13008 ** is (x - 0x20). Therefore toupper() can be implemented as:
13010 ** (x & ~(map[x]&0x20))
13012 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13013 ** array. tolower() is used more often than toupper() by SQLite.
13015 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
13016 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
13017 ** non-ASCII UTF character. Hence the test for whether or not a character is
13018 ** part of an identifier is 0x46.
13020 ** SQLite's versions are identical to the standard versions assuming a
13021 ** locale of "C". They are implemented as macros in sqliteInt.h.
13023 #ifdef SQLITE_ASCII
13024 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13025 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
13026 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
13027 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
13028 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
13029 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
13030 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
13031 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
13032 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
13034 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
13035 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
13036 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
13037 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
13038 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
13039 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
13040 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
13041 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
13043 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
13044 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
13045 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
13046 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
13047 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
13048 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
13049 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
13050 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
13052 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
13053 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
13054 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
13055 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
13056 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
13057 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
13058 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
13059 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
13061 #endif
13063 #ifndef SQLITE_USE_URI
13064 # define SQLITE_USE_URI 0
13065 #endif
13067 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13068 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13069 #endif
13072 ** The following singleton contains the global configuration for
13073 ** the SQLite library.
13075 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13076 SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
13077 1, /* bCoreMutex */
13078 SQLITE_THREADSAFE==1, /* bFullMutex */
13079 SQLITE_USE_URI, /* bOpenUri */
13080 SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
13081 0x7ffffffe, /* mxStrlen */
13082 0, /* neverCorrupt */
13083 128, /* szLookaside */
13084 500, /* nLookaside */
13085 {0,0,0,0,0,0,0,0}, /* m */
13086 {0,0,0,0,0,0,0,0,0}, /* mutex */
13087 {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13088 (void*)0, /* pHeap */
13089 0, /* nHeap */
13090 0, 0, /* mnHeap, mxHeap */
13091 SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
13092 SQLITE_MAX_MMAP_SIZE, /* mxMmap */
13093 (void*)0, /* pScratch */
13094 0, /* szScratch */
13095 0, /* nScratch */
13096 (void*)0, /* pPage */
13097 0, /* szPage */
13098 0, /* nPage */
13099 0, /* mxParserStack */
13100 0, /* sharedCacheEnabled */
13101 /* All the rest should always be initialized to zero */
13102 0, /* isInit */
13103 0, /* inProgress */
13104 0, /* isMutexInit */
13105 0, /* isMallocInit */
13106 0, /* isPCacheInit */
13107 0, /* pInitMutex */
13108 0, /* nRefInitMutex */
13109 0, /* xLog */
13110 0, /* pLogArg */
13111 0, /* bLocaltimeFault */
13112 #ifdef SQLITE_ENABLE_SQLLOG
13113 0, /* xSqllog */
13114 0 /* pSqllogArg */
13115 #endif
13119 ** Hash table for global functions - functions common to all
13120 ** database connections. After initialization, this table is
13121 ** read-only.
13123 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13126 ** Constant tokens for values 0 and 1.
13128 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
13129 { "0", 1 },
13130 { "1", 1 }
13135 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
13136 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
13137 ** the database page that contains the pending byte. It never attempts
13138 ** to read or write that page. The pending byte page is set assign
13139 ** for use by the VFS layers as space for managing file locks.
13141 ** During testing, it is often desirable to move the pending byte to
13142 ** a different position in the file. This allows code that has to
13143 ** deal with the pending byte to run on files that are much smaller
13144 ** than 1 GiB. The sqlite3_test_control() interface can be used to
13145 ** move the pending byte.
13147 ** IMPORTANT: Changing the pending byte to any value other than
13148 ** 0x40000000 results in an incompatible database file format!
13149 ** Changing the pending byte during operating results in undefined
13150 ** and dileterious behavior.
13152 #ifndef SQLITE_OMIT_WSD
13153 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
13154 #endif
13157 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
13158 ** created by mkopcodeh.awk during compilation. Data is obtained
13159 ** from the comments following the "case OP_xxxx:" statements in
13160 ** the vdbe.c file.
13162 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
13164 /************** End of global.c **********************************************/
13165 /************** Begin file ctime.c *******************************************/
13167 ** 2010 February 23
13169 ** The author disclaims copyright to this source code. In place of
13170 ** a legal notice, here is a blessing:
13172 ** May you do good and not evil.
13173 ** May you find forgiveness for yourself and forgive others.
13174 ** May you share freely, never taking more than you give.
13176 *************************************************************************
13178 ** This file implements routines used to report what compile-time options
13179 ** SQLite was built with.
13182 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13186 ** An array of names of all compile-time options. This array should
13187 ** be sorted A-Z.
13189 ** This array looks large, but in a typical installation actually uses
13190 ** only a handful of compile-time options, so most times this array is usually
13191 ** rather short and uses little memory space.
13193 static const char * const azCompileOpt[] = {
13195 /* These macros are provided to "stringify" the value of the define
13196 ** for those options in which the value is meaningful. */
13197 #define CTIMEOPT_VAL_(opt) #opt
13198 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
13200 #ifdef SQLITE_32BIT_ROWID
13201 "32BIT_ROWID",
13202 #endif
13203 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
13204 "4_BYTE_ALIGNED_MALLOC",
13205 #endif
13206 #ifdef SQLITE_CASE_SENSITIVE_LIKE
13207 "CASE_SENSITIVE_LIKE",
13208 #endif
13209 #ifdef SQLITE_CHECK_PAGES
13210 "CHECK_PAGES",
13211 #endif
13212 #ifdef SQLITE_COVERAGE_TEST
13213 "COVERAGE_TEST",
13214 #endif
13215 #ifdef SQLITE_DEBUG
13216 "DEBUG",
13217 #endif
13218 #ifdef SQLITE_DEFAULT_LOCKING_MODE
13219 "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
13220 #endif
13221 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
13222 "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
13223 #endif
13224 #ifdef SQLITE_DISABLE_DIRSYNC
13225 "DISABLE_DIRSYNC",
13226 #endif
13227 #ifdef SQLITE_DISABLE_LFS
13228 "DISABLE_LFS",
13229 #endif
13230 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13231 "ENABLE_ATOMIC_WRITE",
13232 #endif
13233 #ifdef SQLITE_ENABLE_CEROD
13234 "ENABLE_CEROD",
13235 #endif
13236 #ifdef SQLITE_ENABLE_COLUMN_METADATA
13237 "ENABLE_COLUMN_METADATA",
13238 #endif
13239 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
13240 "ENABLE_EXPENSIVE_ASSERT",
13241 #endif
13242 #ifdef SQLITE_ENABLE_FTS1
13243 "ENABLE_FTS1",
13244 #endif
13245 #ifdef SQLITE_ENABLE_FTS2
13246 "ENABLE_FTS2",
13247 #endif
13248 #ifdef SQLITE_ENABLE_FTS3
13249 "ENABLE_FTS3",
13250 #endif
13251 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
13252 "ENABLE_FTS3_PARENTHESIS",
13253 #endif
13254 #ifdef SQLITE_ENABLE_FTS4
13255 "ENABLE_FTS4",
13256 #endif
13257 #ifdef SQLITE_ENABLE_ICU
13258 "ENABLE_ICU",
13259 #endif
13260 #ifdef SQLITE_ENABLE_IOTRACE
13261 "ENABLE_IOTRACE",
13262 #endif
13263 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
13264 "ENABLE_LOAD_EXTENSION",
13265 #endif
13266 #ifdef SQLITE_ENABLE_LOCKING_STYLE
13267 "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
13268 #endif
13269 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13270 "ENABLE_MEMORY_MANAGEMENT",
13271 #endif
13272 #ifdef SQLITE_ENABLE_MEMSYS3
13273 "ENABLE_MEMSYS3",
13274 #endif
13275 #ifdef SQLITE_ENABLE_MEMSYS5
13276 "ENABLE_MEMSYS5",
13277 #endif
13278 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
13279 "ENABLE_OVERSIZE_CELL_CHECK",
13280 #endif
13281 #ifdef SQLITE_ENABLE_RTREE
13282 "ENABLE_RTREE",
13283 #endif
13284 #if defined(SQLITE_ENABLE_STAT4)
13285 "ENABLE_STAT4",
13286 #elif defined(SQLITE_ENABLE_STAT3)
13287 "ENABLE_STAT3",
13288 #endif
13289 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13290 "ENABLE_UNLOCK_NOTIFY",
13291 #endif
13292 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
13293 "ENABLE_UPDATE_DELETE_LIMIT",
13294 #endif
13295 #ifdef SQLITE_HAS_CODEC
13296 "HAS_CODEC",
13297 #endif
13298 #ifdef SQLITE_HAVE_ISNAN
13299 "HAVE_ISNAN",
13300 #endif
13301 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
13302 "HOMEGROWN_RECURSIVE_MUTEX",
13303 #endif
13304 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
13305 "IGNORE_AFP_LOCK_ERRORS",
13306 #endif
13307 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
13308 "IGNORE_FLOCK_LOCK_ERRORS",
13309 #endif
13310 #ifdef SQLITE_INT64_TYPE
13311 "INT64_TYPE",
13312 #endif
13313 #ifdef SQLITE_LOCK_TRACE
13314 "LOCK_TRACE",
13315 #endif
13316 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
13317 "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
13318 #endif
13319 #ifdef SQLITE_MAX_SCHEMA_RETRY
13320 "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
13321 #endif
13322 #ifdef SQLITE_MEMDEBUG
13323 "MEMDEBUG",
13324 #endif
13325 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
13326 "MIXED_ENDIAN_64BIT_FLOAT",
13327 #endif
13328 #ifdef SQLITE_NO_SYNC
13329 "NO_SYNC",
13330 #endif
13331 #ifdef SQLITE_OMIT_ALTERTABLE
13332 "OMIT_ALTERTABLE",
13333 #endif
13334 #ifdef SQLITE_OMIT_ANALYZE
13335 "OMIT_ANALYZE",
13336 #endif
13337 #ifdef SQLITE_OMIT_ATTACH
13338 "OMIT_ATTACH",
13339 #endif
13340 #ifdef SQLITE_OMIT_AUTHORIZATION
13341 "OMIT_AUTHORIZATION",
13342 #endif
13343 #ifdef SQLITE_OMIT_AUTOINCREMENT
13344 "OMIT_AUTOINCREMENT",
13345 #endif
13346 #ifdef SQLITE_OMIT_AUTOINIT
13347 "OMIT_AUTOINIT",
13348 #endif
13349 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13350 "OMIT_AUTOMATIC_INDEX",
13351 #endif
13352 #ifdef SQLITE_OMIT_AUTORESET
13353 "OMIT_AUTORESET",
13354 #endif
13355 #ifdef SQLITE_OMIT_AUTOVACUUM
13356 "OMIT_AUTOVACUUM",
13357 #endif
13358 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13359 "OMIT_BETWEEN_OPTIMIZATION",
13360 #endif
13361 #ifdef SQLITE_OMIT_BLOB_LITERAL
13362 "OMIT_BLOB_LITERAL",
13363 #endif
13364 #ifdef SQLITE_OMIT_BTREECOUNT
13365 "OMIT_BTREECOUNT",
13366 #endif
13367 #ifdef SQLITE_OMIT_BUILTIN_TEST
13368 "OMIT_BUILTIN_TEST",
13369 #endif
13370 #ifdef SQLITE_OMIT_CAST
13371 "OMIT_CAST",
13372 #endif
13373 #ifdef SQLITE_OMIT_CHECK
13374 "OMIT_CHECK",
13375 #endif
13376 #ifdef SQLITE_OMIT_COMPLETE
13377 "OMIT_COMPLETE",
13378 #endif
13379 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13380 "OMIT_COMPOUND_SELECT",
13381 #endif
13382 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13383 "OMIT_DATETIME_FUNCS",
13384 #endif
13385 #ifdef SQLITE_OMIT_DECLTYPE
13386 "OMIT_DECLTYPE",
13387 #endif
13388 #ifdef SQLITE_OMIT_DEPRECATED
13389 "OMIT_DEPRECATED",
13390 #endif
13391 #ifdef SQLITE_OMIT_DISKIO
13392 "OMIT_DISKIO",
13393 #endif
13394 #ifdef SQLITE_OMIT_EXPLAIN
13395 "OMIT_EXPLAIN",
13396 #endif
13397 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13398 "OMIT_FLAG_PRAGMAS",
13399 #endif
13400 #ifdef SQLITE_OMIT_FLOATING_POINT
13401 "OMIT_FLOATING_POINT",
13402 #endif
13403 #ifdef SQLITE_OMIT_FOREIGN_KEY
13404 "OMIT_FOREIGN_KEY",
13405 #endif
13406 #ifdef SQLITE_OMIT_GET_TABLE
13407 "OMIT_GET_TABLE",
13408 #endif
13409 #ifdef SQLITE_OMIT_INCRBLOB
13410 "OMIT_INCRBLOB",
13411 #endif
13412 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13413 "OMIT_INTEGRITY_CHECK",
13414 #endif
13415 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13416 "OMIT_LIKE_OPTIMIZATION",
13417 #endif
13418 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13419 "OMIT_LOAD_EXTENSION",
13420 #endif
13421 #ifdef SQLITE_OMIT_LOCALTIME
13422 "OMIT_LOCALTIME",
13423 #endif
13424 #ifdef SQLITE_OMIT_LOOKASIDE
13425 "OMIT_LOOKASIDE",
13426 #endif
13427 #ifdef SQLITE_OMIT_MEMORYDB
13428 "OMIT_MEMORYDB",
13429 #endif
13430 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13431 "OMIT_OR_OPTIMIZATION",
13432 #endif
13433 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13434 "OMIT_PAGER_PRAGMAS",
13435 #endif
13436 #ifdef SQLITE_OMIT_PRAGMA
13437 "OMIT_PRAGMA",
13438 #endif
13439 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13440 "OMIT_PROGRESS_CALLBACK",
13441 #endif
13442 #ifdef SQLITE_OMIT_QUICKBALANCE
13443 "OMIT_QUICKBALANCE",
13444 #endif
13445 #ifdef SQLITE_OMIT_REINDEX
13446 "OMIT_REINDEX",
13447 #endif
13448 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13449 "OMIT_SCHEMA_PRAGMAS",
13450 #endif
13451 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13452 "OMIT_SCHEMA_VERSION_PRAGMAS",
13453 #endif
13454 #ifdef SQLITE_OMIT_SHARED_CACHE
13455 "OMIT_SHARED_CACHE",
13456 #endif
13457 #ifdef SQLITE_OMIT_SUBQUERY
13458 "OMIT_SUBQUERY",
13459 #endif
13460 #ifdef SQLITE_OMIT_TCL_VARIABLE
13461 "OMIT_TCL_VARIABLE",
13462 #endif
13463 #ifdef SQLITE_OMIT_TEMPDB
13464 "OMIT_TEMPDB",
13465 #endif
13466 #ifdef SQLITE_OMIT_TRACE
13467 "OMIT_TRACE",
13468 #endif
13469 #ifdef SQLITE_OMIT_TRIGGER
13470 "OMIT_TRIGGER",
13471 #endif
13472 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13473 "OMIT_TRUNCATE_OPTIMIZATION",
13474 #endif
13475 #ifdef SQLITE_OMIT_UTF16
13476 "OMIT_UTF16",
13477 #endif
13478 #ifdef SQLITE_OMIT_VACUUM
13479 "OMIT_VACUUM",
13480 #endif
13481 #ifdef SQLITE_OMIT_VIEW
13482 "OMIT_VIEW",
13483 #endif
13484 #ifdef SQLITE_OMIT_VIRTUALTABLE
13485 "OMIT_VIRTUALTABLE",
13486 #endif
13487 #ifdef SQLITE_OMIT_WAL
13488 "OMIT_WAL",
13489 #endif
13490 #ifdef SQLITE_OMIT_WSD
13491 "OMIT_WSD",
13492 #endif
13493 #ifdef SQLITE_OMIT_XFER_OPT
13494 "OMIT_XFER_OPT",
13495 #endif
13496 #ifdef SQLITE_PERFORMANCE_TRACE
13497 "PERFORMANCE_TRACE",
13498 #endif
13499 #ifdef SQLITE_PROXY_DEBUG
13500 "PROXY_DEBUG",
13501 #endif
13502 #ifdef SQLITE_RTREE_INT_ONLY
13503 "RTREE_INT_ONLY",
13504 #endif
13505 #ifdef SQLITE_SECURE_DELETE
13506 "SECURE_DELETE",
13507 #endif
13508 #ifdef SQLITE_SMALL_STACK
13509 "SMALL_STACK",
13510 #endif
13511 #ifdef SQLITE_SOUNDEX
13512 "SOUNDEX",
13513 #endif
13514 #ifdef SQLITE_SYSTEM_MALLOC
13515 "SYSTEM_MALLOC",
13516 #endif
13517 #ifdef SQLITE_TCL
13518 "TCL",
13519 #endif
13520 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13521 "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13522 #endif
13523 #ifdef SQLITE_TEST
13524 "TEST",
13525 #endif
13526 #if defined(SQLITE_THREADSAFE)
13527 "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13528 #endif
13529 #ifdef SQLITE_USE_ALLOCA
13530 "USE_ALLOCA",
13531 #endif
13532 #ifdef SQLITE_WIN32_MALLOC
13533 "WIN32_MALLOC",
13534 #endif
13535 #ifdef SQLITE_ZERO_MALLOC
13536 "ZERO_MALLOC"
13537 #endif
13541 ** Given the name of a compile-time option, return true if that option
13542 ** was used and false if not.
13544 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13545 ** is not required for a match.
13547 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13548 int i, n;
13549 if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13550 n = sqlite3Strlen30(zOptName);
13552 /* Since ArraySize(azCompileOpt) is normally in single digits, a
13553 ** linear search is adequate. No need for a binary search. */
13554 for(i=0; i<ArraySize(azCompileOpt); i++){
13555 if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13556 && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
13558 return 1;
13561 return 0;
13565 ** Return the N-th compile-time option string. If N is out of range,
13566 ** return a NULL pointer.
13568 SQLITE_API const char *sqlite3_compileoption_get(int N){
13569 if( N>=0 && N<ArraySize(azCompileOpt) ){
13570 return azCompileOpt[N];
13572 return 0;
13575 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13577 /************** End of ctime.c ***********************************************/
13578 /************** Begin file status.c ******************************************/
13580 ** 2008 June 18
13582 ** The author disclaims copyright to this source code. In place of
13583 ** a legal notice, here is a blessing:
13585 ** May you do good and not evil.
13586 ** May you find forgiveness for yourself and forgive others.
13587 ** May you share freely, never taking more than you give.
13589 *************************************************************************
13591 ** This module implements the sqlite3_status() interface and related
13592 ** functionality.
13594 /************** Include vdbeInt.h in the middle of status.c ******************/
13595 /************** Begin file vdbeInt.h *****************************************/
13597 ** 2003 September 6
13599 ** The author disclaims copyright to this source code. In place of
13600 ** a legal notice, here is a blessing:
13602 ** May you do good and not evil.
13603 ** May you find forgiveness for yourself and forgive others.
13604 ** May you share freely, never taking more than you give.
13606 *************************************************************************
13607 ** This is the header file for information that is private to the
13608 ** VDBE. This information used to all be at the top of the single
13609 ** source code file "vdbe.c". When that file became too big (over
13610 ** 6000 lines long) it was split up into several smaller files and
13611 ** this header information was factored out.
13613 #ifndef _VDBEINT_H_
13614 #define _VDBEINT_H_
13617 ** The maximum number of times that a statement will try to reparse
13618 ** itself before giving up and returning SQLITE_SCHEMA.
13620 #ifndef SQLITE_MAX_SCHEMA_RETRY
13621 # define SQLITE_MAX_SCHEMA_RETRY 50
13622 #endif
13625 ** SQL is translated into a sequence of instructions to be
13626 ** executed by a virtual machine. Each instruction is an instance
13627 ** of the following structure.
13629 typedef struct VdbeOp Op;
13632 ** Boolean values
13634 typedef unsigned Bool;
13636 /* Opaque type used by code in vdbesort.c */
13637 typedef struct VdbeSorter VdbeSorter;
13639 /* Opaque type used by the explainer */
13640 typedef struct Explain Explain;
13642 /* Elements of the linked list at Vdbe.pAuxData */
13643 typedef struct AuxData AuxData;
13646 ** A cursor is a pointer into a single BTree within a database file.
13647 ** The cursor can seek to a BTree entry with a particular key, or
13648 ** loop over all entries of the Btree. You can also insert new BTree
13649 ** entries or retrieve the key or data from the entry that the cursor
13650 ** is currently pointing to.
13652 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
13653 ** A pseudo-table is a single-row table implemented by registers.
13655 ** Every cursor that the virtual machine has open is represented by an
13656 ** instance of the following structure.
13658 struct VdbeCursor {
13659 BtCursor *pCursor; /* The cursor structure of the backend */
13660 Btree *pBt; /* Separate file holding temporary table */
13661 KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
13662 int seekResult; /* Result of previous sqlite3BtreeMoveto() */
13663 int pseudoTableReg; /* Register holding pseudotable content. */
13664 i16 nField; /* Number of fields in the header */
13665 u16 nHdrParsed; /* Number of header fields parsed so far */
13666 i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
13667 u8 nullRow; /* True if pointing to a row with no data */
13668 u8 rowidIsValid; /* True if lastRowid is valid */
13669 u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
13670 Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
13671 Bool isTable:1; /* True if a table requiring integer keys */
13672 Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
13673 Bool multiPseudo:1; /* Multi-register pseudo-cursor */
13674 sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
13675 i64 seqCount; /* Sequence counter */
13676 i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
13677 i64 lastRowid; /* Rowid being deleted by OP_Delete */
13678 VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
13680 /* Cached information about the header for the data record that the
13681 ** cursor is currently pointing to. Only valid if cacheStatus matches
13682 ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
13683 ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13684 ** the cache is out of date.
13686 ** aRow might point to (ephemeral) data for the current row, or it might
13687 ** be NULL.
13689 u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
13690 u32 payloadSize; /* Total number of bytes in the record */
13691 u32 szRow; /* Byte available in aRow */
13692 u32 iHdrOffset; /* Offset to next unparsed byte of the header */
13693 const u8 *aRow; /* Data for the current row, if all on one page */
13694 u32 aType[1]; /* Type values for all entries in the record */
13695 /* 2*nField extra array elements allocated for aType[], beyond the one
13696 ** static element declared in the structure. nField total array slots for
13697 ** aType[] and nField+1 array slots for aOffset[] */
13699 typedef struct VdbeCursor VdbeCursor;
13702 ** When a sub-program is executed (OP_Program), a structure of this type
13703 ** is allocated to store the current value of the program counter, as
13704 ** well as the current memory cell array and various other frame specific
13705 ** values stored in the Vdbe struct. When the sub-program is finished,
13706 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13707 ** restoring the state of the VM to as it was before the sub-program
13708 ** began executing.
13710 ** The memory for a VdbeFrame object is allocated and managed by a memory
13711 ** cell in the parent (calling) frame. When the memory cell is deleted or
13712 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13713 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13714 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13715 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13716 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13717 ** child frame are released.
13719 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13720 ** set to NULL if the currently executing frame is the main program.
13722 typedef struct VdbeFrame VdbeFrame;
13723 struct VdbeFrame {
13724 Vdbe *v; /* VM this frame belongs to */
13725 VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
13726 Op *aOp; /* Program instructions for parent frame */
13727 Mem *aMem; /* Array of memory cells for parent frame */
13728 u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
13729 VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
13730 void *token; /* Copy of SubProgram.token */
13731 i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
13732 int nCursor; /* Number of entries in apCsr */
13733 int pc; /* Program Counter in parent (calling) frame */
13734 int nOp; /* Size of aOp array */
13735 int nMem; /* Number of entries in aMem */
13736 int nOnceFlag; /* Number of entries in aOnceFlag */
13737 int nChildMem; /* Number of memory cells for child frame */
13738 int nChildCsr; /* Number of cursors for child frame */
13739 int nChange; /* Statement changes (Vdbe.nChanges) */
13742 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13745 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13747 #define CACHE_STALE 0
13750 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13751 ** structures. Each Mem struct may cache multiple representations (string,
13752 ** integer etc.) of the same value.
13754 struct Mem {
13755 sqlite3 *db; /* The associated database connection */
13756 char *z; /* String or BLOB value */
13757 double r; /* Real value */
13758 union {
13759 i64 i; /* Integer value used when MEM_Int is set in flags */
13760 int nZero; /* Used when bit MEM_Zero is set in flags */
13761 FuncDef *pDef; /* Used only when flags==MEM_Agg */
13762 RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
13763 VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
13764 } u;
13765 int n; /* Number of characters in string value, excluding '\0' */
13766 u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13767 u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13768 u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13769 #ifdef SQLITE_DEBUG
13770 Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
13771 void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
13772 #endif
13773 void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
13774 char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
13777 /* One or more of the following flags are set to indicate the validOK
13778 ** representations of the value stored in the Mem struct.
13780 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13781 ** No other flags may be set in this case.
13783 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13784 ** Usually this is encoded in the same unicode encoding as the main
13785 ** database (see below for exceptions). If the MEM_Term flag is also
13786 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
13787 ** flags may coexist with the MEM_Str flag.
13789 #define MEM_Null 0x0001 /* Value is NULL */
13790 #define MEM_Str 0x0002 /* Value is a string */
13791 #define MEM_Int 0x0004 /* Value is an integer */
13792 #define MEM_Real 0x0008 /* Value is a real number */
13793 #define MEM_Blob 0x0010 /* Value is a BLOB */
13794 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
13795 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
13796 #define MEM_Invalid 0x0080 /* Value is undefined */
13797 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
13798 #define MEM_TypeMask 0x01ff /* Mask of type bits */
13801 /* Whenever Mem contains a valid string or blob representation, one of
13802 ** the following flags must be set to determine the memory management
13803 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
13804 ** string is \000 or \u0000 terminated
13806 #define MEM_Term 0x0200 /* String rep is nul terminated */
13807 #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
13808 #define MEM_Static 0x0800 /* Mem.z points to a static string */
13809 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
13810 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
13811 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
13812 #ifdef SQLITE_OMIT_INCRBLOB
13813 #undef MEM_Zero
13814 #define MEM_Zero 0x0000
13815 #endif
13818 ** Clear any existing type flags from a Mem and replace them with f
13820 #define MemSetTypeFlag(p, f) \
13821 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13824 ** Return true if a memory cell is not marked as invalid. This macro
13825 ** is for use inside assert() statements only.
13827 #ifdef SQLITE_DEBUG
13828 #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
13829 #endif
13832 ** Each auxilliary data pointer stored by a user defined function
13833 ** implementation calling sqlite3_set_auxdata() is stored in an instance
13834 ** of this structure. All such structures associated with a single VM
13835 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
13836 ** when the VM is halted (if not before).
13838 struct AuxData {
13839 int iOp; /* Instruction number of OP_Function opcode */
13840 int iArg; /* Index of function argument. */
13841 void *pAux; /* Aux data pointer */
13842 void (*xDelete)(void *); /* Destructor for the aux data */
13843 AuxData *pNext; /* Next element in list */
13847 ** The "context" argument for a installable function. A pointer to an
13848 ** instance of this structure is the first argument to the routines used
13849 ** implement the SQL functions.
13851 ** There is a typedef for this structure in sqlite.h. So all routines,
13852 ** even the public interface to SQLite, can use a pointer to this structure.
13853 ** But this file is the only place where the internal details of this
13854 ** structure are known.
13856 ** This structure is defined inside of vdbeInt.h because it uses substructures
13857 ** (Mem) which are only defined there.
13859 struct sqlite3_context {
13860 FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
13861 Mem s; /* The return value is stored here */
13862 Mem *pMem; /* Memory cell used to store aggregate context */
13863 CollSeq *pColl; /* Collating sequence */
13864 Vdbe *pVdbe; /* The VM that owns this context */
13865 int iOp; /* Instruction number of OP_Function */
13866 int isError; /* Error code returned by the function. */
13867 u8 skipFlag; /* Skip skip accumulator loading if true */
13868 u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
13872 ** An Explain object accumulates indented output which is helpful
13873 ** in describing recursive data structures.
13875 struct Explain {
13876 Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
13877 StrAccum str; /* The string being accumulated */
13878 int nIndent; /* Number of elements in aIndent */
13879 u16 aIndent[100]; /* Levels of indentation */
13880 char zBase[100]; /* Initial space */
13883 /* A bitfield type for use inside of structures. Always follow with :N where
13884 ** N is the number of bits.
13886 typedef unsigned bft; /* Bit Field Type */
13889 ** An instance of the virtual machine. This structure contains the complete
13890 ** state of the virtual machine.
13892 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13893 ** is really a pointer to an instance of this structure.
13895 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13896 ** any virtual table method invocations made by the vdbe program. It is
13897 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13898 ** variable is used for two purposes: to allow xDestroy methods to execute
13899 ** "DROP TABLE" statements and to prevent some nasty side effects of
13900 ** malloc failure when SQLite is invoked recursively by a virtual table
13901 ** method function.
13903 struct Vdbe {
13904 sqlite3 *db; /* The database connection that owns this statement */
13905 Op *aOp; /* Space to hold the virtual machine's program */
13906 Mem *aMem; /* The memory locations */
13907 Mem **apArg; /* Arguments to currently executing user function */
13908 Mem *aColName; /* Column names to return */
13909 Mem *pResultSet; /* Pointer to an array of results */
13910 Parse *pParse; /* Parsing context used to create this Vdbe */
13911 int nMem; /* Number of memory locations currently allocated */
13912 int nOp; /* Number of instructions in the program */
13913 int nCursor; /* Number of slots in apCsr[] */
13914 u32 magic; /* Magic number for sanity checking */
13915 char *zErrMsg; /* Error message written here */
13916 Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
13917 VdbeCursor **apCsr; /* One element of this array for each open cursor */
13918 Mem *aVar; /* Values for the OP_Variable opcode. */
13919 char **azVar; /* Name of variables */
13920 ynVar nVar; /* Number of entries in aVar[] */
13921 ynVar nzVar; /* Number of entries in azVar[] */
13922 u32 cacheCtr; /* VdbeCursor row cache generation counter */
13923 int pc; /* The program counter */
13924 int rc; /* Value to return */
13925 u16 nResColumn; /* Number of columns in one row of the result set */
13926 u8 errorAction; /* Recovery action to do in case of an error */
13927 u8 minWriteFileFormat; /* Minimum file format for writable database files */
13928 bft explain:2; /* True if EXPLAIN present on SQL command */
13929 bft inVtabMethod:2; /* See comments above */
13930 bft changeCntOn:1; /* True to update the change-counter */
13931 bft expired:1; /* True if the VM needs to be recompiled */
13932 bft runOnlyOnce:1; /* Automatically expire on reset */
13933 bft usesStmtJournal:1; /* True if uses a statement journal */
13934 bft readOnly:1; /* True for statements that do not write */
13935 bft bIsReader:1; /* True for statements that read */
13936 bft isPrepareV2:1; /* True if prepared with prepare_v2() */
13937 bft doingRerun:1; /* True if rerunning after an auto-reprepare */
13938 int nChange; /* Number of db changes made since last reset */
13939 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
13940 yDbMask lockMask; /* Subset of btreeMask that requires a lock */
13941 int iStatement; /* Statement number (or 0 if has not opened stmt) */
13942 u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
13943 #ifndef SQLITE_OMIT_TRACE
13944 i64 startTime; /* Time when query started - used for profiling */
13945 #endif
13946 i64 iCurrentTime; /* Value of julianday('now') for this statement */
13947 i64 nFkConstraint; /* Number of imm. FK constraints this VM */
13948 i64 nStmtDefCons; /* Number of def. constraints when stmt started */
13949 i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
13950 char *zSql; /* Text of the SQL statement that generated this */
13951 void *pFree; /* Free this when deleting the vdbe */
13952 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13953 Explain *pExplain; /* The explainer */
13954 char *zExplain; /* Explanation of data structures */
13955 #endif
13956 VdbeFrame *pFrame; /* Parent frame */
13957 VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
13958 int nFrame; /* Number of frames in pFrame list */
13959 u32 expmask; /* Binding to these vars invalidates VM */
13960 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
13961 int nOnceFlag; /* Size of array aOnceFlag[] */
13962 u8 *aOnceFlag; /* Flags for OP_Once */
13963 AuxData *pAuxData; /* Linked list of auxdata allocations */
13967 ** The following are allowed values for Vdbe.magic
13969 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
13970 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
13971 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
13972 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
13975 ** Function prototypes
13977 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13978 void sqliteVdbePopStack(Vdbe*,int);
13979 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13980 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13981 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13982 #endif
13983 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13984 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13985 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
13986 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13987 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
13989 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13990 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13991 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13992 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13993 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13994 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13995 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13996 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13997 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13998 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13999 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14000 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14001 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14002 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14003 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14004 #ifdef SQLITE_OMIT_FLOATING_POINT
14005 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14006 #else
14007 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
14008 #endif
14009 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14010 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14011 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14012 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14013 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
14014 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14015 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14016 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14017 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14018 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14019 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14020 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14021 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14022 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
14023 #define VdbeMemRelease(X) \
14024 if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
14025 sqlite3VdbeMemReleaseExternal(X);
14026 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14027 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14028 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14029 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14030 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14031 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14032 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
14033 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14035 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
14036 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14037 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14038 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14039 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
14040 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
14041 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14043 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14044 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
14045 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
14046 #else
14047 # define sqlite3VdbeEnter(X)
14048 # define sqlite3VdbeLeave(X)
14049 #endif
14051 #ifdef SQLITE_DEBUG
14052 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14053 #endif
14055 #ifndef SQLITE_OMIT_FOREIGN_KEY
14056 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14057 #else
14058 # define sqlite3VdbeCheckFk(p,i) 0
14059 #endif
14061 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14062 #ifdef SQLITE_DEBUG
14063 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
14064 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14065 #endif
14066 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14068 #ifndef SQLITE_OMIT_INCRBLOB
14069 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
14070 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14071 #else
14072 #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14073 #define ExpandBlob(P) SQLITE_OK
14074 #endif
14076 #endif /* !defined(_VDBEINT_H_) */
14078 /************** End of vdbeInt.h *********************************************/
14079 /************** Continuing where we left off in status.c *********************/
14082 ** Variables in which to record status information.
14084 typedef struct sqlite3StatType sqlite3StatType;
14085 static SQLITE_WSD struct sqlite3StatType {
14086 int nowValue[10]; /* Current value */
14087 int mxValue[10]; /* Maximum value */
14088 } sqlite3Stat = { {0,}, {0,} };
14091 /* The "wsdStat" macro will resolve to the status information
14092 ** state vector. If writable static data is unsupported on the target,
14093 ** we have to locate the state vector at run-time. In the more common
14094 ** case where writable static data is supported, wsdStat can refer directly
14095 ** to the "sqlite3Stat" state vector declared above.
14097 #ifdef SQLITE_OMIT_WSD
14098 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
14099 # define wsdStat x[0]
14100 #else
14101 # define wsdStatInit
14102 # define wsdStat sqlite3Stat
14103 #endif
14106 ** Return the current value of a status parameter.
14108 SQLITE_PRIVATE int sqlite3StatusValue(int op){
14109 wsdStatInit;
14110 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14111 return wsdStat.nowValue[op];
14115 ** Add N to the value of a status record. It is assumed that the
14116 ** caller holds appropriate locks.
14118 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
14119 wsdStatInit;
14120 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14121 wsdStat.nowValue[op] += N;
14122 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14123 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14128 ** Set the value of a status to X.
14130 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
14131 wsdStatInit;
14132 assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14133 wsdStat.nowValue[op] = X;
14134 if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14135 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14140 ** Query status information.
14142 ** This implementation assumes that reading or writing an aligned
14143 ** 32-bit integer is an atomic operation. If that assumption is not true,
14144 ** then this routine is not threadsafe.
14146 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
14147 wsdStatInit;
14148 if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
14149 return SQLITE_MISUSE_BKPT;
14151 *pCurrent = wsdStat.nowValue[op];
14152 *pHighwater = wsdStat.mxValue[op];
14153 if( resetFlag ){
14154 wsdStat.mxValue[op] = wsdStat.nowValue[op];
14156 return SQLITE_OK;
14160 ** Query status information for a single database connection
14162 SQLITE_API int sqlite3_db_status(
14163 sqlite3 *db, /* The database connection whose status is desired */
14164 int op, /* Status verb */
14165 int *pCurrent, /* Write current value here */
14166 int *pHighwater, /* Write high-water mark here */
14167 int resetFlag /* Reset high-water mark if true */
14169 int rc = SQLITE_OK; /* Return code */
14170 sqlite3_mutex_enter(db->mutex);
14171 switch( op ){
14172 case SQLITE_DBSTATUS_LOOKASIDE_USED: {
14173 *pCurrent = db->lookaside.nOut;
14174 *pHighwater = db->lookaside.mxOut;
14175 if( resetFlag ){
14176 db->lookaside.mxOut = db->lookaside.nOut;
14178 break;
14181 case SQLITE_DBSTATUS_LOOKASIDE_HIT:
14182 case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
14183 case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
14184 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
14185 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
14186 testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
14187 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
14188 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
14189 *pCurrent = 0;
14190 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
14191 if( resetFlag ){
14192 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
14194 break;
14198 ** Return an approximation for the amount of memory currently used
14199 ** by all pagers associated with the given database connection. The
14200 ** highwater mark is meaningless and is returned as zero.
14202 case SQLITE_DBSTATUS_CACHE_USED: {
14203 int totalUsed = 0;
14204 int i;
14205 sqlite3BtreeEnterAll(db);
14206 for(i=0; i<db->nDb; i++){
14207 Btree *pBt = db->aDb[i].pBt;
14208 if( pBt ){
14209 Pager *pPager = sqlite3BtreePager(pBt);
14210 totalUsed += sqlite3PagerMemUsed(pPager);
14213 sqlite3BtreeLeaveAll(db);
14214 *pCurrent = totalUsed;
14215 *pHighwater = 0;
14216 break;
14220 ** *pCurrent gets an accurate estimate of the amount of memory used
14221 ** to store the schema for all databases (main, temp, and any ATTACHed
14222 ** databases. *pHighwater is set to zero.
14224 case SQLITE_DBSTATUS_SCHEMA_USED: {
14225 int i; /* Used to iterate through schemas */
14226 int nByte = 0; /* Used to accumulate return value */
14228 sqlite3BtreeEnterAll(db);
14229 db->pnBytesFreed = &nByte;
14230 for(i=0; i<db->nDb; i++){
14231 Schema *pSchema = db->aDb[i].pSchema;
14232 if( ALWAYS(pSchema!=0) ){
14233 HashElem *p;
14235 nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
14236 pSchema->tblHash.count
14237 + pSchema->trigHash.count
14238 + pSchema->idxHash.count
14239 + pSchema->fkeyHash.count
14241 nByte += sqlite3MallocSize(pSchema->tblHash.ht);
14242 nByte += sqlite3MallocSize(pSchema->trigHash.ht);
14243 nByte += sqlite3MallocSize(pSchema->idxHash.ht);
14244 nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
14246 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
14247 sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
14249 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
14250 sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
14254 db->pnBytesFreed = 0;
14255 sqlite3BtreeLeaveAll(db);
14257 *pHighwater = 0;
14258 *pCurrent = nByte;
14259 break;
14263 ** *pCurrent gets an accurate estimate of the amount of memory used
14264 ** to store all prepared statements.
14265 ** *pHighwater is set to zero.
14267 case SQLITE_DBSTATUS_STMT_USED: {
14268 struct Vdbe *pVdbe; /* Used to iterate through VMs */
14269 int nByte = 0; /* Used to accumulate return value */
14271 db->pnBytesFreed = &nByte;
14272 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
14273 sqlite3VdbeClearObject(db, pVdbe);
14274 sqlite3DbFree(db, pVdbe);
14276 db->pnBytesFreed = 0;
14278 *pHighwater = 0;
14279 *pCurrent = nByte;
14281 break;
14285 ** Set *pCurrent to the total cache hits or misses encountered by all
14286 ** pagers the database handle is connected to. *pHighwater is always set
14287 ** to zero.
14289 case SQLITE_DBSTATUS_CACHE_HIT:
14290 case SQLITE_DBSTATUS_CACHE_MISS:
14291 case SQLITE_DBSTATUS_CACHE_WRITE:{
14292 int i;
14293 int nRet = 0;
14294 assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
14295 assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
14297 for(i=0; i<db->nDb; i++){
14298 if( db->aDb[i].pBt ){
14299 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
14300 sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
14303 *pHighwater = 0;
14304 *pCurrent = nRet;
14305 break;
14308 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
14309 ** key constraints. Set *pCurrent to zero if all foreign key constraints
14310 ** have been satisfied. The *pHighwater is always set to zero.
14312 case SQLITE_DBSTATUS_DEFERRED_FKS: {
14313 *pHighwater = 0;
14314 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
14315 break;
14318 default: {
14319 rc = SQLITE_ERROR;
14322 sqlite3_mutex_leave(db->mutex);
14323 return rc;
14326 /************** End of status.c **********************************************/
14327 /************** Begin file date.c ********************************************/
14329 ** 2003 October 31
14331 ** The author disclaims copyright to this source code. In place of
14332 ** a legal notice, here is a blessing:
14334 ** May you do good and not evil.
14335 ** May you find forgiveness for yourself and forgive others.
14336 ** May you share freely, never taking more than you give.
14338 *************************************************************************
14339 ** This file contains the C functions that implement date and time
14340 ** functions for SQLite.
14342 ** There is only one exported symbol in this file - the function
14343 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
14344 ** All other code has file scope.
14346 ** SQLite processes all times and dates as Julian Day numbers. The
14347 ** dates and times are stored as the number of days since noon
14348 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
14349 ** calendar system.
14351 ** 1970-01-01 00:00:00 is JD 2440587.5
14352 ** 2000-01-01 00:00:00 is JD 2451544.5
14354 ** This implemention requires years to be expressed as a 4-digit number
14355 ** which means that only dates between 0000-01-01 and 9999-12-31 can
14356 ** be represented, even though julian day numbers allow a much wider
14357 ** range of dates.
14359 ** The Gregorian calendar system is used for all dates and times,
14360 ** even those that predate the Gregorian calendar. Historians usually
14361 ** use the Julian calendar for dates prior to 1582-10-15 and for some
14362 ** dates afterwards, depending on locale. Beware of this difference.
14364 ** The conversion algorithms are implemented based on descriptions
14365 ** in the following text:
14367 ** Jean Meeus
14368 ** Astronomical Algorithms, 2nd Edition, 1998
14369 ** ISBM 0-943396-61-1
14370 ** Willmann-Bell, Inc
14371 ** Richmond, Virginia (USA)
14373 /* #include <stdlib.h> */
14374 /* #include <assert.h> */
14375 #include <time.h>
14377 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14381 ** A structure for holding a single date and time.
14383 typedef struct DateTime DateTime;
14384 struct DateTime {
14385 sqlite3_int64 iJD; /* The julian day number times 86400000 */
14386 int Y, M, D; /* Year, month, and day */
14387 int h, m; /* Hour and minutes */
14388 int tz; /* Timezone offset in minutes */
14389 double s; /* Seconds */
14390 char validYMD; /* True (1) if Y,M,D are valid */
14391 char validHMS; /* True (1) if h,m,s are valid */
14392 char validJD; /* True (1) if iJD is valid */
14393 char validTZ; /* True (1) if tz is valid */
14398 ** Convert zDate into one or more integers. Additional arguments
14399 ** come in groups of 5 as follows:
14401 ** N number of digits in the integer
14402 ** min minimum allowed value of the integer
14403 ** max maximum allowed value of the integer
14404 ** nextC first character after the integer
14405 ** pVal where to write the integers value.
14407 ** Conversions continue until one with nextC==0 is encountered.
14408 ** The function returns the number of successful conversions.
14410 static int getDigits(const char *zDate, ...){
14411 va_list ap;
14412 int val;
14413 int N;
14414 int min;
14415 int max;
14416 int nextC;
14417 int *pVal;
14418 int cnt = 0;
14419 va_start(ap, zDate);
14421 N = va_arg(ap, int);
14422 min = va_arg(ap, int);
14423 max = va_arg(ap, int);
14424 nextC = va_arg(ap, int);
14425 pVal = va_arg(ap, int*);
14426 val = 0;
14427 while( N-- ){
14428 if( !sqlite3Isdigit(*zDate) ){
14429 goto end_getDigits;
14431 val = val*10 + *zDate - '0';
14432 zDate++;
14434 if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14435 goto end_getDigits;
14437 *pVal = val;
14438 zDate++;
14439 cnt++;
14440 }while( nextC );
14441 end_getDigits:
14442 va_end(ap);
14443 return cnt;
14447 ** Parse a timezone extension on the end of a date-time.
14448 ** The extension is of the form:
14450 ** (+/-)HH:MM
14452 ** Or the "zulu" notation:
14454 ** Z
14456 ** If the parse is successful, write the number of minutes
14457 ** of change in p->tz and return 0. If a parser error occurs,
14458 ** return non-zero.
14460 ** A missing specifier is not considered an error.
14462 static int parseTimezone(const char *zDate, DateTime *p){
14463 int sgn = 0;
14464 int nHr, nMn;
14465 int c;
14466 while( sqlite3Isspace(*zDate) ){ zDate++; }
14467 p->tz = 0;
14468 c = *zDate;
14469 if( c=='-' ){
14470 sgn = -1;
14471 }else if( c=='+' ){
14472 sgn = +1;
14473 }else if( c=='Z' || c=='z' ){
14474 zDate++;
14475 goto zulu_time;
14476 }else{
14477 return c!=0;
14479 zDate++;
14480 if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14481 return 1;
14483 zDate += 5;
14484 p->tz = sgn*(nMn + nHr*60);
14485 zulu_time:
14486 while( sqlite3Isspace(*zDate) ){ zDate++; }
14487 return *zDate!=0;
14491 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14492 ** The HH, MM, and SS must each be exactly 2 digits. The
14493 ** fractional seconds FFFF can be one or more digits.
14495 ** Return 1 if there is a parsing error and 0 on success.
14497 static int parseHhMmSs(const char *zDate, DateTime *p){
14498 int h, m, s;
14499 double ms = 0.0;
14500 if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14501 return 1;
14503 zDate += 5;
14504 if( *zDate==':' ){
14505 zDate++;
14506 if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14507 return 1;
14509 zDate += 2;
14510 if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14511 double rScale = 1.0;
14512 zDate++;
14513 while( sqlite3Isdigit(*zDate) ){
14514 ms = ms*10.0 + *zDate - '0';
14515 rScale *= 10.0;
14516 zDate++;
14518 ms /= rScale;
14520 }else{
14521 s = 0;
14523 p->validJD = 0;
14524 p->validHMS = 1;
14525 p->h = h;
14526 p->m = m;
14527 p->s = s + ms;
14528 if( parseTimezone(zDate, p) ) return 1;
14529 p->validTZ = (p->tz!=0)?1:0;
14530 return 0;
14534 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
14535 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14537 ** Reference: Meeus page 61
14539 static void computeJD(DateTime *p){
14540 int Y, M, D, A, B, X1, X2;
14542 if( p->validJD ) return;
14543 if( p->validYMD ){
14544 Y = p->Y;
14545 M = p->M;
14546 D = p->D;
14547 }else{
14548 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
14549 M = 1;
14550 D = 1;
14552 if( M<=2 ){
14553 Y--;
14554 M += 12;
14556 A = Y/100;
14557 B = 2 - A + (A/4);
14558 X1 = 36525*(Y+4716)/100;
14559 X2 = 306001*(M+1)/10000;
14560 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14561 p->validJD = 1;
14562 if( p->validHMS ){
14563 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14564 if( p->validTZ ){
14565 p->iJD -= p->tz*60000;
14566 p->validYMD = 0;
14567 p->validHMS = 0;
14568 p->validTZ = 0;
14574 ** Parse dates of the form
14576 ** YYYY-MM-DD HH:MM:SS.FFF
14577 ** YYYY-MM-DD HH:MM:SS
14578 ** YYYY-MM-DD HH:MM
14579 ** YYYY-MM-DD
14581 ** Write the result into the DateTime structure and return 0
14582 ** on success and 1 if the input string is not a well-formed
14583 ** date.
14585 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14586 int Y, M, D, neg;
14588 if( zDate[0]=='-' ){
14589 zDate++;
14590 neg = 1;
14591 }else{
14592 neg = 0;
14594 if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14595 return 1;
14597 zDate += 10;
14598 while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14599 if( parseHhMmSs(zDate, p)==0 ){
14600 /* We got the time */
14601 }else if( *zDate==0 ){
14602 p->validHMS = 0;
14603 }else{
14604 return 1;
14606 p->validJD = 0;
14607 p->validYMD = 1;
14608 p->Y = neg ? -Y : Y;
14609 p->M = M;
14610 p->D = D;
14611 if( p->validTZ ){
14612 computeJD(p);
14614 return 0;
14618 ** Set the time to the current time reported by the VFS.
14620 ** Return the number of errors.
14622 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14623 p->iJD = sqlite3StmtCurrentTime(context);
14624 if( p->iJD>0 ){
14625 p->validJD = 1;
14626 return 0;
14627 }else{
14628 return 1;
14633 ** Attempt to parse the given string into a Julian Day Number. Return
14634 ** the number of errors.
14636 ** The following are acceptable forms for the input string:
14638 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
14639 ** DDDD.DD
14640 ** now
14642 ** In the first form, the +/-HH:MM is always optional. The fractional
14643 ** seconds extension (the ".FFF") is optional. The seconds portion
14644 ** (":SS.FFF") is option. The year and date can be omitted as long
14645 ** as there is a time string. The time string can be omitted as long
14646 ** as there is a year and date.
14648 static int parseDateOrTime(
14649 sqlite3_context *context,
14650 const char *zDate,
14651 DateTime *p
14653 double r;
14654 if( parseYyyyMmDd(zDate,p)==0 ){
14655 return 0;
14656 }else if( parseHhMmSs(zDate, p)==0 ){
14657 return 0;
14658 }else if( sqlite3StrICmp(zDate,"now")==0){
14659 return setDateTimeToCurrent(context, p);
14660 }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14661 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14662 p->validJD = 1;
14663 return 0;
14665 return 1;
14669 ** Compute the Year, Month, and Day from the julian day number.
14671 static void computeYMD(DateTime *p){
14672 int Z, A, B, C, D, E, X1;
14673 if( p->validYMD ) return;
14674 if( !p->validJD ){
14675 p->Y = 2000;
14676 p->M = 1;
14677 p->D = 1;
14678 }else{
14679 Z = (int)((p->iJD + 43200000)/86400000);
14680 A = (int)((Z - 1867216.25)/36524.25);
14681 A = Z + 1 + A - (A/4);
14682 B = A + 1524;
14683 C = (int)((B - 122.1)/365.25);
14684 D = (36525*C)/100;
14685 E = (int)((B-D)/30.6001);
14686 X1 = (int)(30.6001*E);
14687 p->D = B - D - X1;
14688 p->M = E<14 ? E-1 : E-13;
14689 p->Y = p->M>2 ? C - 4716 : C - 4715;
14691 p->validYMD = 1;
14695 ** Compute the Hour, Minute, and Seconds from the julian day number.
14697 static void computeHMS(DateTime *p){
14698 int s;
14699 if( p->validHMS ) return;
14700 computeJD(p);
14701 s = (int)((p->iJD + 43200000) % 86400000);
14702 p->s = s/1000.0;
14703 s = (int)p->s;
14704 p->s -= s;
14705 p->h = s/3600;
14706 s -= p->h*3600;
14707 p->m = s/60;
14708 p->s += s - p->m*60;
14709 p->validHMS = 1;
14713 ** Compute both YMD and HMS
14715 static void computeYMD_HMS(DateTime *p){
14716 computeYMD(p);
14717 computeHMS(p);
14721 ** Clear the YMD and HMS and the TZ
14723 static void clearYMD_HMS_TZ(DateTime *p){
14724 p->validYMD = 0;
14725 p->validHMS = 0;
14726 p->validTZ = 0;
14730 ** On recent Windows platforms, the localtime_s() function is available
14731 ** as part of the "Secure CRT". It is essentially equivalent to
14732 ** localtime_r() available under most POSIX platforms, except that the
14733 ** order of the parameters is reversed.
14735 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14737 ** If the user has not indicated to use localtime_r() or localtime_s()
14738 ** already, check for an MSVC build environment that provides
14739 ** localtime_s().
14741 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14742 defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14743 #define HAVE_LOCALTIME_S 1
14744 #endif
14746 #ifndef SQLITE_OMIT_LOCALTIME
14748 ** The following routine implements the rough equivalent of localtime_r()
14749 ** using whatever operating-system specific localtime facility that
14750 ** is available. This routine returns 0 on success and
14751 ** non-zero on any kind of error.
14753 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14754 ** routine will always fail.
14756 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
14757 ** library function localtime_r() is used to assist in the calculation of
14758 ** local time.
14760 static int osLocaltime(time_t *t, struct tm *pTm){
14761 int rc;
14762 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14763 && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14764 struct tm *pX;
14765 #if SQLITE_THREADSAFE>0
14766 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14767 #endif
14768 sqlite3_mutex_enter(mutex);
14769 pX = localtime(t);
14770 #ifndef SQLITE_OMIT_BUILTIN_TEST
14771 if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14772 #endif
14773 if( pX ) *pTm = *pX;
14774 sqlite3_mutex_leave(mutex);
14775 rc = pX==0;
14776 #else
14777 #ifndef SQLITE_OMIT_BUILTIN_TEST
14778 if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14779 #endif
14780 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14781 rc = localtime_r(t, pTm)==0;
14782 #else
14783 rc = localtime_s(pTm, t);
14784 #endif /* HAVE_LOCALTIME_R */
14785 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14786 return rc;
14788 #endif /* SQLITE_OMIT_LOCALTIME */
14791 #ifndef SQLITE_OMIT_LOCALTIME
14793 ** Compute the difference (in milliseconds) between localtime and UTC
14794 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14795 ** return this value and set *pRc to SQLITE_OK.
14797 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14798 ** is undefined in this case.
14800 static sqlite3_int64 localtimeOffset(
14801 DateTime *p, /* Date at which to calculate offset */
14802 sqlite3_context *pCtx, /* Write error here if one occurs */
14803 int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
14805 DateTime x, y;
14806 time_t t;
14807 struct tm sLocal;
14809 /* Initialize the contents of sLocal to avoid a compiler warning. */
14810 memset(&sLocal, 0, sizeof(sLocal));
14812 x = *p;
14813 computeYMD_HMS(&x);
14814 if( x.Y<1971 || x.Y>=2038 ){
14815 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
14816 ** works for years between 1970 and 2037. For dates outside this range,
14817 ** SQLite attempts to map the year into an equivalent year within this
14818 ** range, do the calculation, then map the year back.
14820 x.Y = 2000;
14821 x.M = 1;
14822 x.D = 1;
14823 x.h = 0;
14824 x.m = 0;
14825 x.s = 0.0;
14826 } else {
14827 int s = (int)(x.s + 0.5);
14828 x.s = s;
14830 x.tz = 0;
14831 x.validJD = 0;
14832 computeJD(&x);
14833 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14834 if( osLocaltime(&t, &sLocal) ){
14835 sqlite3_result_error(pCtx, "local time unavailable", -1);
14836 *pRc = SQLITE_ERROR;
14837 return 0;
14839 y.Y = sLocal.tm_year + 1900;
14840 y.M = sLocal.tm_mon + 1;
14841 y.D = sLocal.tm_mday;
14842 y.h = sLocal.tm_hour;
14843 y.m = sLocal.tm_min;
14844 y.s = sLocal.tm_sec;
14845 y.validYMD = 1;
14846 y.validHMS = 1;
14847 y.validJD = 0;
14848 y.validTZ = 0;
14849 computeJD(&y);
14850 *pRc = SQLITE_OK;
14851 return y.iJD - x.iJD;
14853 #endif /* SQLITE_OMIT_LOCALTIME */
14856 ** Process a modifier to a date-time stamp. The modifiers are
14857 ** as follows:
14859 ** NNN days
14860 ** NNN hours
14861 ** NNN minutes
14862 ** NNN.NNNN seconds
14863 ** NNN months
14864 ** NNN years
14865 ** start of month
14866 ** start of year
14867 ** start of week
14868 ** start of day
14869 ** weekday N
14870 ** unixepoch
14871 ** localtime
14872 ** utc
14874 ** Return 0 on success and 1 if there is any kind of error. If the error
14875 ** is in a system call (i.e. localtime()), then an error message is written
14876 ** to context pCtx. If the error is an unrecognized modifier, no error is
14877 ** written to pCtx.
14879 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14880 int rc = 1;
14881 int n;
14882 double r;
14883 char *z, zBuf[30];
14884 z = zBuf;
14885 for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14886 z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14888 z[n] = 0;
14889 switch( z[0] ){
14890 #ifndef SQLITE_OMIT_LOCALTIME
14891 case 'l': {
14892 /* localtime
14894 ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14895 ** show local time.
14897 if( strcmp(z, "localtime")==0 ){
14898 computeJD(p);
14899 p->iJD += localtimeOffset(p, pCtx, &rc);
14900 clearYMD_HMS_TZ(p);
14902 break;
14904 #endif
14905 case 'u': {
14907 ** unixepoch
14909 ** Treat the current value of p->iJD as the number of
14910 ** seconds since 1970. Convert to a real julian day number.
14912 if( strcmp(z, "unixepoch")==0 && p->validJD ){
14913 p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14914 clearYMD_HMS_TZ(p);
14915 rc = 0;
14917 #ifndef SQLITE_OMIT_LOCALTIME
14918 else if( strcmp(z, "utc")==0 ){
14919 sqlite3_int64 c1;
14920 computeJD(p);
14921 c1 = localtimeOffset(p, pCtx, &rc);
14922 if( rc==SQLITE_OK ){
14923 p->iJD -= c1;
14924 clearYMD_HMS_TZ(p);
14925 p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14928 #endif
14929 break;
14931 case 'w': {
14933 ** weekday N
14935 ** Move the date to the same time on the next occurrence of
14936 ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
14937 ** date is already on the appropriate weekday, this is a no-op.
14939 if( strncmp(z, "weekday ", 8)==0
14940 && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14941 && (n=(int)r)==r && n>=0 && r<7 ){
14942 sqlite3_int64 Z;
14943 computeYMD_HMS(p);
14944 p->validTZ = 0;
14945 p->validJD = 0;
14946 computeJD(p);
14947 Z = ((p->iJD + 129600000)/86400000) % 7;
14948 if( Z>n ) Z -= 7;
14949 p->iJD += (n - Z)*86400000;
14950 clearYMD_HMS_TZ(p);
14951 rc = 0;
14953 break;
14955 case 's': {
14957 ** start of TTTTT
14959 ** Move the date backwards to the beginning of the current day,
14960 ** or month or year.
14962 if( strncmp(z, "start of ", 9)!=0 ) break;
14963 z += 9;
14964 computeYMD(p);
14965 p->validHMS = 1;
14966 p->h = p->m = 0;
14967 p->s = 0.0;
14968 p->validTZ = 0;
14969 p->validJD = 0;
14970 if( strcmp(z,"month")==0 ){
14971 p->D = 1;
14972 rc = 0;
14973 }else if( strcmp(z,"year")==0 ){
14974 computeYMD(p);
14975 p->M = 1;
14976 p->D = 1;
14977 rc = 0;
14978 }else if( strcmp(z,"day")==0 ){
14979 rc = 0;
14981 break;
14983 case '+':
14984 case '-':
14985 case '0':
14986 case '1':
14987 case '2':
14988 case '3':
14989 case '4':
14990 case '5':
14991 case '6':
14992 case '7':
14993 case '8':
14994 case '9': {
14995 double rRounder;
14996 for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14997 if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14998 rc = 1;
14999 break;
15001 if( z[n]==':' ){
15002 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15003 ** specified number of hours, minutes, seconds, and fractional seconds
15004 ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
15005 ** omitted.
15007 const char *z2 = z;
15008 DateTime tx;
15009 sqlite3_int64 day;
15010 if( !sqlite3Isdigit(*z2) ) z2++;
15011 memset(&tx, 0, sizeof(tx));
15012 if( parseHhMmSs(z2, &tx) ) break;
15013 computeJD(&tx);
15014 tx.iJD -= 43200000;
15015 day = tx.iJD/86400000;
15016 tx.iJD -= day*86400000;
15017 if( z[0]=='-' ) tx.iJD = -tx.iJD;
15018 computeJD(p);
15019 clearYMD_HMS_TZ(p);
15020 p->iJD += tx.iJD;
15021 rc = 0;
15022 break;
15024 z += n;
15025 while( sqlite3Isspace(*z) ) z++;
15026 n = sqlite3Strlen30(z);
15027 if( n>10 || n<3 ) break;
15028 if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15029 computeJD(p);
15030 rc = 0;
15031 rRounder = r<0 ? -0.5 : +0.5;
15032 if( n==3 && strcmp(z,"day")==0 ){
15033 p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
15034 }else if( n==4 && strcmp(z,"hour")==0 ){
15035 p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
15036 }else if( n==6 && strcmp(z,"minute")==0 ){
15037 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
15038 }else if( n==6 && strcmp(z,"second")==0 ){
15039 p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
15040 }else if( n==5 && strcmp(z,"month")==0 ){
15041 int x, y;
15042 computeYMD_HMS(p);
15043 p->M += (int)r;
15044 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
15045 p->Y += x;
15046 p->M -= x*12;
15047 p->validJD = 0;
15048 computeJD(p);
15049 y = (int)r;
15050 if( y!=r ){
15051 p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
15053 }else if( n==4 && strcmp(z,"year")==0 ){
15054 int y = (int)r;
15055 computeYMD_HMS(p);
15056 p->Y += y;
15057 p->validJD = 0;
15058 computeJD(p);
15059 if( y!=r ){
15060 p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
15062 }else{
15063 rc = 1;
15065 clearYMD_HMS_TZ(p);
15066 break;
15068 default: {
15069 break;
15072 return rc;
15076 ** Process time function arguments. argv[0] is a date-time stamp.
15077 ** argv[1] and following are modifiers. Parse them all and write
15078 ** the resulting time into the DateTime structure p. Return 0
15079 ** on success and 1 if there are any errors.
15081 ** If there are zero parameters (if even argv[0] is undefined)
15082 ** then assume a default value of "now" for argv[0].
15084 static int isDate(
15085 sqlite3_context *context,
15086 int argc,
15087 sqlite3_value **argv,
15088 DateTime *p
15090 int i;
15091 const unsigned char *z;
15092 int eType;
15093 memset(p, 0, sizeof(*p));
15094 if( argc==0 ){
15095 return setDateTimeToCurrent(context, p);
15097 if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
15098 || eType==SQLITE_INTEGER ){
15099 p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
15100 p->validJD = 1;
15101 }else{
15102 z = sqlite3_value_text(argv[0]);
15103 if( !z || parseDateOrTime(context, (char*)z, p) ){
15104 return 1;
15107 for(i=1; i<argc; i++){
15108 z = sqlite3_value_text(argv[i]);
15109 if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
15111 return 0;
15116 ** The following routines implement the various date and time functions
15117 ** of SQLite.
15121 ** julianday( TIMESTRING, MOD, MOD, ...)
15123 ** Return the julian day number of the date specified in the arguments
15125 static void juliandayFunc(
15126 sqlite3_context *context,
15127 int argc,
15128 sqlite3_value **argv
15130 DateTime x;
15131 if( isDate(context, argc, argv, &x)==0 ){
15132 computeJD(&x);
15133 sqlite3_result_double(context, x.iJD/86400000.0);
15138 ** datetime( TIMESTRING, MOD, MOD, ...)
15140 ** Return YYYY-MM-DD HH:MM:SS
15142 static void datetimeFunc(
15143 sqlite3_context *context,
15144 int argc,
15145 sqlite3_value **argv
15147 DateTime x;
15148 if( isDate(context, argc, argv, &x)==0 ){
15149 char zBuf[100];
15150 computeYMD_HMS(&x);
15151 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
15152 x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
15153 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15158 ** time( TIMESTRING, MOD, MOD, ...)
15160 ** Return HH:MM:SS
15162 static void timeFunc(
15163 sqlite3_context *context,
15164 int argc,
15165 sqlite3_value **argv
15167 DateTime x;
15168 if( isDate(context, argc, argv, &x)==0 ){
15169 char zBuf[100];
15170 computeHMS(&x);
15171 sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
15172 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15177 ** date( TIMESTRING, MOD, MOD, ...)
15179 ** Return YYYY-MM-DD
15181 static void dateFunc(
15182 sqlite3_context *context,
15183 int argc,
15184 sqlite3_value **argv
15186 DateTime x;
15187 if( isDate(context, argc, argv, &x)==0 ){
15188 char zBuf[100];
15189 computeYMD(&x);
15190 sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
15191 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15196 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
15198 ** Return a string described by FORMAT. Conversions as follows:
15200 ** %d day of month
15201 ** %f ** fractional seconds SS.SSS
15202 ** %H hour 00-24
15203 ** %j day of year 000-366
15204 ** %J ** Julian day number
15205 ** %m month 01-12
15206 ** %M minute 00-59
15207 ** %s seconds since 1970-01-01
15208 ** %S seconds 00-59
15209 ** %w day of week 0-6 sunday==0
15210 ** %W week of year 00-53
15211 ** %Y year 0000-9999
15212 ** %% %
15214 static void strftimeFunc(
15215 sqlite3_context *context,
15216 int argc,
15217 sqlite3_value **argv
15219 DateTime x;
15220 u64 n;
15221 size_t i,j;
15222 char *z;
15223 sqlite3 *db;
15224 const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
15225 char zBuf[100];
15226 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
15227 db = sqlite3_context_db_handle(context);
15228 for(i=0, n=1; zFmt[i]; i++, n++){
15229 if( zFmt[i]=='%' ){
15230 switch( zFmt[i+1] ){
15231 case 'd':
15232 case 'H':
15233 case 'm':
15234 case 'M':
15235 case 'S':
15236 case 'W':
15237 n++;
15238 /* fall thru */
15239 case 'w':
15240 case '%':
15241 break;
15242 case 'f':
15243 n += 8;
15244 break;
15245 case 'j':
15246 n += 3;
15247 break;
15248 case 'Y':
15249 n += 8;
15250 break;
15251 case 's':
15252 case 'J':
15253 n += 50;
15254 break;
15255 default:
15256 return; /* ERROR. return a NULL */
15258 i++;
15261 testcase( n==sizeof(zBuf)-1 );
15262 testcase( n==sizeof(zBuf) );
15263 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
15264 testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
15265 if( n<sizeof(zBuf) ){
15266 z = zBuf;
15267 }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
15268 sqlite3_result_error_toobig(context);
15269 return;
15270 }else{
15271 z = sqlite3DbMallocRaw(db, (int)n);
15272 if( z==0 ){
15273 sqlite3_result_error_nomem(context);
15274 return;
15277 computeJD(&x);
15278 computeYMD_HMS(&x);
15279 for(i=j=0; zFmt[i]; i++){
15280 if( zFmt[i]!='%' ){
15281 z[j++] = zFmt[i];
15282 }else{
15283 i++;
15284 switch( zFmt[i] ){
15285 case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
15286 case 'f': {
15287 double s = x.s;
15288 if( s>59.999 ) s = 59.999;
15289 sqlite3_snprintf(7, &z[j],"%06.3f", s);
15290 j += sqlite3Strlen30(&z[j]);
15291 break;
15293 case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
15294 case 'W': /* Fall thru */
15295 case 'j': {
15296 int nDay; /* Number of days since 1st day of year */
15297 DateTime y = x;
15298 y.validJD = 0;
15299 y.M = 1;
15300 y.D = 1;
15301 computeJD(&y);
15302 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
15303 if( zFmt[i]=='W' ){
15304 int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
15305 wd = (int)(((x.iJD+43200000)/86400000)%7);
15306 sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
15307 j += 2;
15308 }else{
15309 sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
15310 j += 3;
15312 break;
15314 case 'J': {
15315 sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
15316 j+=sqlite3Strlen30(&z[j]);
15317 break;
15319 case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
15320 case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
15321 case 's': {
15322 sqlite3_snprintf(30,&z[j],"%lld",
15323 (i64)(x.iJD/1000 - 21086676*(i64)10000));
15324 j += sqlite3Strlen30(&z[j]);
15325 break;
15327 case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
15328 case 'w': {
15329 z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
15330 break;
15332 case 'Y': {
15333 sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
15334 break;
15336 default: z[j++] = '%'; break;
15340 z[j] = 0;
15341 sqlite3_result_text(context, z, -1,
15342 z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
15346 ** current_time()
15348 ** This function returns the same value as time('now').
15350 static void ctimeFunc(
15351 sqlite3_context *context,
15352 int NotUsed,
15353 sqlite3_value **NotUsed2
15355 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15356 timeFunc(context, 0, 0);
15360 ** current_date()
15362 ** This function returns the same value as date('now').
15364 static void cdateFunc(
15365 sqlite3_context *context,
15366 int NotUsed,
15367 sqlite3_value **NotUsed2
15369 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15370 dateFunc(context, 0, 0);
15374 ** current_timestamp()
15376 ** This function returns the same value as datetime('now').
15378 static void ctimestampFunc(
15379 sqlite3_context *context,
15380 int NotUsed,
15381 sqlite3_value **NotUsed2
15383 UNUSED_PARAMETER2(NotUsed, NotUsed2);
15384 datetimeFunc(context, 0, 0);
15386 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15388 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15390 ** If the library is compiled to omit the full-scale date and time
15391 ** handling (to get a smaller binary), the following minimal version
15392 ** of the functions current_time(), current_date() and current_timestamp()
15393 ** are included instead. This is to support column declarations that
15394 ** include "DEFAULT CURRENT_TIME" etc.
15396 ** This function uses the C-library functions time(), gmtime()
15397 ** and strftime(). The format string to pass to strftime() is supplied
15398 ** as the user-data for the function.
15400 static void currentTimeFunc(
15401 sqlite3_context *context,
15402 int argc,
15403 sqlite3_value **argv
15405 time_t t;
15406 char *zFormat = (char *)sqlite3_user_data(context);
15407 sqlite3 *db;
15408 sqlite3_int64 iT;
15409 struct tm *pTm;
15410 struct tm sNow;
15411 char zBuf[20];
15413 UNUSED_PARAMETER(argc);
15414 UNUSED_PARAMETER(argv);
15416 iT = sqlite3StmtCurrentTime(context);
15417 if( iT<=0 ) return;
15418 t = iT/1000 - 10000*(sqlite3_int64)21086676;
15419 #ifdef HAVE_GMTIME_R
15420 pTm = gmtime_r(&t, &sNow);
15421 #else
15422 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15423 pTm = gmtime(&t);
15424 if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15425 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15426 #endif
15427 if( pTm ){
15428 strftime(zBuf, 20, zFormat, &sNow);
15429 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15432 #endif
15435 ** This function registered all of the above C functions as SQL
15436 ** functions. This should be the only routine in this file with
15437 ** external linkage.
15439 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15440 static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15441 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15442 FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
15443 FUNCTION(date, -1, 0, 0, dateFunc ),
15444 FUNCTION(time, -1, 0, 0, timeFunc ),
15445 FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
15446 FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
15447 FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
15448 FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15449 FUNCTION(current_date, 0, 0, 0, cdateFunc ),
15450 #else
15451 STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
15452 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
15453 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15454 #endif
15456 int i;
15457 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15458 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15460 for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15461 sqlite3FuncDefInsert(pHash, &aFunc[i]);
15465 /************** End of date.c ************************************************/
15466 /************** Begin file os.c **********************************************/
15468 ** 2005 November 29
15470 ** The author disclaims copyright to this source code. In place of
15471 ** a legal notice, here is a blessing:
15473 ** May you do good and not evil.
15474 ** May you find forgiveness for yourself and forgive others.
15475 ** May you share freely, never taking more than you give.
15477 ******************************************************************************
15479 ** This file contains OS interface code that is common to all
15480 ** architectures.
15482 #define _SQLITE_OS_C_ 1
15483 #undef _SQLITE_OS_C_
15486 ** The default SQLite sqlite3_vfs implementations do not allocate
15487 ** memory (actually, os_unix.c allocates a small amount of memory
15488 ** from within OsOpen()), but some third-party implementations may.
15489 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15490 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15492 ** The following functions are instrumented for malloc() failure
15493 ** testing:
15495 ** sqlite3OsRead()
15496 ** sqlite3OsWrite()
15497 ** sqlite3OsSync()
15498 ** sqlite3OsFileSize()
15499 ** sqlite3OsLock()
15500 ** sqlite3OsCheckReservedLock()
15501 ** sqlite3OsFileControl()
15502 ** sqlite3OsShmMap()
15503 ** sqlite3OsOpen()
15504 ** sqlite3OsDelete()
15505 ** sqlite3OsAccess()
15506 ** sqlite3OsFullPathname()
15509 #if defined(SQLITE_TEST)
15510 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15511 #define DO_OS_MALLOC_TEST(x) \
15512 if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
15513 void *pTstAlloc = sqlite3Malloc(10); \
15514 if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
15515 sqlite3_free(pTstAlloc); \
15517 #else
15518 #define DO_OS_MALLOC_TEST(x)
15519 #endif
15522 ** The following routines are convenience wrappers around methods
15523 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
15524 ** of this would be completely automatic if SQLite were coded using
15525 ** C++ instead of plain old C.
15527 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15528 int rc = SQLITE_OK;
15529 if( pId->pMethods ){
15530 rc = pId->pMethods->xClose(pId);
15531 pId->pMethods = 0;
15533 return rc;
15535 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15536 DO_OS_MALLOC_TEST(id);
15537 return id->pMethods->xRead(id, pBuf, amt, offset);
15539 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15540 DO_OS_MALLOC_TEST(id);
15541 return id->pMethods->xWrite(id, pBuf, amt, offset);
15543 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15544 return id->pMethods->xTruncate(id, size);
15546 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15547 DO_OS_MALLOC_TEST(id);
15548 return id->pMethods->xSync(id, flags);
15550 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15551 DO_OS_MALLOC_TEST(id);
15552 return id->pMethods->xFileSize(id, pSize);
15554 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15555 DO_OS_MALLOC_TEST(id);
15556 return id->pMethods->xLock(id, lockType);
15558 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15559 return id->pMethods->xUnlock(id, lockType);
15561 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15562 DO_OS_MALLOC_TEST(id);
15563 return id->pMethods->xCheckReservedLock(id, pResOut);
15567 ** Use sqlite3OsFileControl() when we are doing something that might fail
15568 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
15569 ** when simply tossing information over the wall to the VFS and we do not
15570 ** really care if the VFS receives and understands the information since it
15571 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
15572 ** routine has no return value since the return value would be meaningless.
15574 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15575 #ifdef SQLITE_TEST
15576 if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
15577 /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
15578 ** is using a regular VFS, it is called after the corresponding
15579 ** transaction has been committed. Injecting a fault at this point
15580 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
15581 ** but the transaction is committed anyway.
15583 ** The core must call OsFileControl() though, not OsFileControlHint(),
15584 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
15585 ** means the commit really has failed and an error should be returned
15586 ** to the user. */
15587 DO_OS_MALLOC_TEST(id);
15589 #endif
15590 return id->pMethods->xFileControl(id, op, pArg);
15592 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15593 (void)id->pMethods->xFileControl(id, op, pArg);
15596 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15597 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15598 return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15600 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15601 return id->pMethods->xDeviceCharacteristics(id);
15603 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15604 return id->pMethods->xShmLock(id, offset, n, flags);
15606 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15607 id->pMethods->xShmBarrier(id);
15609 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15610 return id->pMethods->xShmUnmap(id, deleteFlag);
15612 SQLITE_PRIVATE int sqlite3OsShmMap(
15613 sqlite3_file *id, /* Database file handle */
15614 int iPage,
15615 int pgsz,
15616 int bExtend, /* True to extend file if necessary */
15617 void volatile **pp /* OUT: Pointer to mapping */
15619 DO_OS_MALLOC_TEST(id);
15620 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15623 #if SQLITE_MAX_MMAP_SIZE>0
15624 /* The real implementation of xFetch and xUnfetch */
15625 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15626 DO_OS_MALLOC_TEST(id);
15627 return id->pMethods->xFetch(id, iOff, iAmt, pp);
15629 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15630 return id->pMethods->xUnfetch(id, iOff, p);
15632 #else
15633 /* No-op stubs to use when memory-mapped I/O is disabled */
15634 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15635 *pp = 0;
15636 return SQLITE_OK;
15638 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15639 return SQLITE_OK;
15641 #endif
15644 ** The next group of routines are convenience wrappers around the
15645 ** VFS methods.
15647 SQLITE_PRIVATE int sqlite3OsOpen(
15648 sqlite3_vfs *pVfs,
15649 const char *zPath,
15650 sqlite3_file *pFile,
15651 int flags,
15652 int *pFlagsOut
15654 int rc;
15655 DO_OS_MALLOC_TEST(0);
15656 /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15657 ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
15658 ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15659 ** reaching the VFS. */
15660 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15661 assert( rc==SQLITE_OK || pFile->pMethods==0 );
15662 return rc;
15664 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15665 DO_OS_MALLOC_TEST(0);
15666 assert( dirSync==0 || dirSync==1 );
15667 return pVfs->xDelete(pVfs, zPath, dirSync);
15669 SQLITE_PRIVATE int sqlite3OsAccess(
15670 sqlite3_vfs *pVfs,
15671 const char *zPath,
15672 int flags,
15673 int *pResOut
15675 DO_OS_MALLOC_TEST(0);
15676 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15678 SQLITE_PRIVATE int sqlite3OsFullPathname(
15679 sqlite3_vfs *pVfs,
15680 const char *zPath,
15681 int nPathOut,
15682 char *zPathOut
15684 DO_OS_MALLOC_TEST(0);
15685 zPathOut[0] = 0;
15686 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15688 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15689 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15690 return pVfs->xDlOpen(pVfs, zPath);
15692 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15693 pVfs->xDlError(pVfs, nByte, zBufOut);
15695 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15696 return pVfs->xDlSym(pVfs, pHdle, zSym);
15698 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15699 pVfs->xDlClose(pVfs, pHandle);
15701 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15702 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15703 return pVfs->xRandomness(pVfs, nByte, zBufOut);
15705 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15706 return pVfs->xSleep(pVfs, nMicro);
15708 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15709 int rc;
15710 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15711 ** method to get the current date and time if that method is available
15712 ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15713 ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15714 ** unavailable.
15716 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15717 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15718 }else{
15719 double r;
15720 rc = pVfs->xCurrentTime(pVfs, &r);
15721 *pTimeOut = (sqlite3_int64)(r*86400000.0);
15723 return rc;
15726 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15727 sqlite3_vfs *pVfs,
15728 const char *zFile,
15729 sqlite3_file **ppFile,
15730 int flags,
15731 int *pOutFlags
15733 int rc = SQLITE_NOMEM;
15734 sqlite3_file *pFile;
15735 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15736 if( pFile ){
15737 rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15738 if( rc!=SQLITE_OK ){
15739 sqlite3_free(pFile);
15740 }else{
15741 *ppFile = pFile;
15744 return rc;
15746 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15747 int rc = SQLITE_OK;
15748 assert( pFile );
15749 rc = sqlite3OsClose(pFile);
15750 sqlite3_free(pFile);
15751 return rc;
15755 ** This function is a wrapper around the OS specific implementation of
15756 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15757 ** ability to simulate a malloc failure, so that the handling of an
15758 ** error in sqlite3_os_init() by the upper layers can be tested.
15760 SQLITE_PRIVATE int sqlite3OsInit(void){
15761 void *p = sqlite3_malloc(10);
15762 if( p==0 ) return SQLITE_NOMEM;
15763 sqlite3_free(p);
15764 return sqlite3_os_init();
15768 ** The list of all registered VFS implementations.
15770 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15771 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15774 ** Locate a VFS by name. If no name is given, simply return the
15775 ** first VFS on the list.
15777 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15778 sqlite3_vfs *pVfs = 0;
15779 #if SQLITE_THREADSAFE
15780 sqlite3_mutex *mutex;
15781 #endif
15782 #ifndef SQLITE_OMIT_AUTOINIT
15783 int rc = sqlite3_initialize();
15784 if( rc ) return 0;
15785 #endif
15786 #if SQLITE_THREADSAFE
15787 mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15788 #endif
15789 sqlite3_mutex_enter(mutex);
15790 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15791 if( zVfs==0 ) break;
15792 if( strcmp(zVfs, pVfs->zName)==0 ) break;
15794 sqlite3_mutex_leave(mutex);
15795 return pVfs;
15799 ** Unlink a VFS from the linked list
15801 static void vfsUnlink(sqlite3_vfs *pVfs){
15802 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15803 if( pVfs==0 ){
15804 /* No-op */
15805 }else if( vfsList==pVfs ){
15806 vfsList = pVfs->pNext;
15807 }else if( vfsList ){
15808 sqlite3_vfs *p = vfsList;
15809 while( p->pNext && p->pNext!=pVfs ){
15810 p = p->pNext;
15812 if( p->pNext==pVfs ){
15813 p->pNext = pVfs->pNext;
15819 ** Register a VFS with the system. It is harmless to register the same
15820 ** VFS multiple times. The new VFS becomes the default if makeDflt is
15821 ** true.
15823 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15824 MUTEX_LOGIC(sqlite3_mutex *mutex;)
15825 #ifndef SQLITE_OMIT_AUTOINIT
15826 int rc = sqlite3_initialize();
15827 if( rc ) return rc;
15828 #endif
15829 MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15830 sqlite3_mutex_enter(mutex);
15831 vfsUnlink(pVfs);
15832 if( makeDflt || vfsList==0 ){
15833 pVfs->pNext = vfsList;
15834 vfsList = pVfs;
15835 }else{
15836 pVfs->pNext = vfsList->pNext;
15837 vfsList->pNext = pVfs;
15839 assert(vfsList);
15840 sqlite3_mutex_leave(mutex);
15841 return SQLITE_OK;
15845 ** Unregister a VFS so that it is no longer accessible.
15847 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15848 #if SQLITE_THREADSAFE
15849 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15850 #endif
15851 sqlite3_mutex_enter(mutex);
15852 vfsUnlink(pVfs);
15853 sqlite3_mutex_leave(mutex);
15854 return SQLITE_OK;
15857 /************** End of os.c **************************************************/
15858 /************** Begin file fault.c *******************************************/
15860 ** 2008 Jan 22
15862 ** The author disclaims copyright to this source code. In place of
15863 ** a legal notice, here is a blessing:
15865 ** May you do good and not evil.
15866 ** May you find forgiveness for yourself and forgive others.
15867 ** May you share freely, never taking more than you give.
15869 *************************************************************************
15871 ** This file contains code to support the concept of "benign"
15872 ** malloc failures (when the xMalloc() or xRealloc() method of the
15873 ** sqlite3_mem_methods structure fails to allocate a block of memory
15874 ** and returns 0).
15876 ** Most malloc failures are non-benign. After they occur, SQLite
15877 ** abandons the current operation and returns an error code (usually
15878 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15879 ** fatal. For example, if a malloc fails while resizing a hash table, this
15880 ** is completely recoverable simply by not carrying out the resize. The
15881 ** hash table will continue to function normally. So a malloc failure
15882 ** during a hash table resize is a benign fault.
15886 #ifndef SQLITE_OMIT_BUILTIN_TEST
15889 ** Global variables.
15891 typedef struct BenignMallocHooks BenignMallocHooks;
15892 static SQLITE_WSD struct BenignMallocHooks {
15893 void (*xBenignBegin)(void);
15894 void (*xBenignEnd)(void);
15895 } sqlite3Hooks = { 0, 0 };
15897 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15898 ** structure. If writable static data is unsupported on the target,
15899 ** we have to locate the state vector at run-time. In the more common
15900 ** case where writable static data is supported, wsdHooks can refer directly
15901 ** to the "sqlite3Hooks" state vector declared above.
15903 #ifdef SQLITE_OMIT_WSD
15904 # define wsdHooksInit \
15905 BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15906 # define wsdHooks x[0]
15907 #else
15908 # define wsdHooksInit
15909 # define wsdHooks sqlite3Hooks
15910 #endif
15914 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15915 ** sqlite3EndBenignMalloc() are called, respectively.
15917 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15918 void (*xBenignBegin)(void),
15919 void (*xBenignEnd)(void)
15921 wsdHooksInit;
15922 wsdHooks.xBenignBegin = xBenignBegin;
15923 wsdHooks.xBenignEnd = xBenignEnd;
15927 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15928 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15929 ** indicates that subsequent malloc failures are non-benign.
15931 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15932 wsdHooksInit;
15933 if( wsdHooks.xBenignBegin ){
15934 wsdHooks.xBenignBegin();
15937 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15938 wsdHooksInit;
15939 if( wsdHooks.xBenignEnd ){
15940 wsdHooks.xBenignEnd();
15944 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15946 /************** End of fault.c ***********************************************/
15947 /************** Begin file mem0.c ********************************************/
15949 ** 2008 October 28
15951 ** The author disclaims copyright to this source code. In place of
15952 ** a legal notice, here is a blessing:
15954 ** May you do good and not evil.
15955 ** May you find forgiveness for yourself and forgive others.
15956 ** May you share freely, never taking more than you give.
15958 *************************************************************************
15960 ** This file contains a no-op memory allocation drivers for use when
15961 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
15962 ** here always fail. SQLite will not operate with these drivers. These
15963 ** are merely placeholders. Real drivers must be substituted using
15964 ** sqlite3_config() before SQLite will operate.
15968 ** This version of the memory allocator is the default. It is
15969 ** used when no other memory allocator is specified using compile-time
15970 ** macros.
15972 #ifdef SQLITE_ZERO_MALLOC
15975 ** No-op versions of all memory allocation routines
15977 static void *sqlite3MemMalloc(int nByte){ return 0; }
15978 static void sqlite3MemFree(void *pPrior){ return; }
15979 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15980 static int sqlite3MemSize(void *pPrior){ return 0; }
15981 static int sqlite3MemRoundup(int n){ return n; }
15982 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15983 static void sqlite3MemShutdown(void *NotUsed){ return; }
15986 ** This routine is the only routine in this file with external linkage.
15988 ** Populate the low-level memory allocation function pointers in
15989 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15991 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15992 static const sqlite3_mem_methods defaultMethods = {
15993 sqlite3MemMalloc,
15994 sqlite3MemFree,
15995 sqlite3MemRealloc,
15996 sqlite3MemSize,
15997 sqlite3MemRoundup,
15998 sqlite3MemInit,
15999 sqlite3MemShutdown,
16002 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16005 #endif /* SQLITE_ZERO_MALLOC */
16007 /************** End of mem0.c ************************************************/
16008 /************** Begin file mem1.c ********************************************/
16010 ** 2007 August 14
16012 ** The author disclaims copyright to this source code. In place of
16013 ** a legal notice, here is a blessing:
16015 ** May you do good and not evil.
16016 ** May you find forgiveness for yourself and forgive others.
16017 ** May you share freely, never taking more than you give.
16019 *************************************************************************
16021 ** This file contains low-level memory allocation drivers for when
16022 ** SQLite will use the standard C-library malloc/realloc/free interface
16023 ** to obtain the memory it needs.
16025 ** This file contains implementations of the low-level memory allocation
16026 ** routines specified in the sqlite3_mem_methods object. The content of
16027 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
16028 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
16029 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
16030 ** default configuration is to use memory allocation routines in this
16031 ** file.
16033 ** C-preprocessor macro summary:
16035 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
16036 ** the malloc_usable_size() interface exists
16037 ** on the target platform. Or, this symbol
16038 ** can be set manually, if desired.
16039 ** If an equivalent interface exists by
16040 ** a different name, using a separate -D
16041 ** option to rename it.
16043 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
16044 ** memory allocator. Set this symbol to enable
16045 ** building on older macs.
16047 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
16048 ** _msize() on windows systems. This might
16049 ** be necessary when compiling for Delphi,
16050 ** for example.
16054 ** This version of the memory allocator is the default. It is
16055 ** used when no other memory allocator is specified using compile-time
16056 ** macros.
16058 #ifdef SQLITE_SYSTEM_MALLOC
16059 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16062 ** Use the zone allocator available on apple products unless the
16063 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
16065 #include <sys/sysctl.h>
16066 #include <malloc/malloc.h>
16067 #include <libkern/OSAtomic.h>
16068 static malloc_zone_t* _sqliteZone_;
16069 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
16070 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
16071 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
16072 #define SQLITE_MALLOCSIZE(x) \
16073 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
16075 #else /* if not __APPLE__ */
16078 ** Use standard C library malloc and free on non-Apple systems.
16079 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
16081 #define SQLITE_MALLOC(x) malloc(x)
16082 #define SQLITE_FREE(x) free(x)
16083 #define SQLITE_REALLOC(x,y) realloc((x),(y))
16086 ** The malloc.h header file is needed for malloc_usable_size() function
16087 ** on some systems (e.g. Linux).
16089 #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
16090 # define SQLITE_USE_MALLOC_H
16091 # define SQLITE_USE_MALLOC_USABLE_SIZE
16093 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
16094 ** use of _msize() is automatic, but can be disabled by compiling with
16095 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
16096 ** the malloc.h header file.
16098 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
16099 # define SQLITE_USE_MALLOC_H
16100 # define SQLITE_USE_MSIZE
16101 #endif
16104 ** Include the malloc.h header file, if necessary. Also set define macro
16105 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
16106 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
16107 ** The memory size function can always be overridden manually by defining
16108 ** the macro SQLITE_MALLOCSIZE to the desired function name.
16110 #if defined(SQLITE_USE_MALLOC_H)
16111 # include <malloc.h>
16112 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
16113 # if !defined(SQLITE_MALLOCSIZE)
16114 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
16115 # endif
16116 # elif defined(SQLITE_USE_MSIZE)
16117 # if !defined(SQLITE_MALLOCSIZE)
16118 # define SQLITE_MALLOCSIZE _msize
16119 # endif
16120 # endif
16121 #endif /* defined(SQLITE_USE_MALLOC_H) */
16123 #endif /* __APPLE__ or not __APPLE__ */
16126 ** Like malloc(), but remember the size of the allocation
16127 ** so that we can find it later using sqlite3MemSize().
16129 ** For this low-level routine, we are guaranteed that nByte>0 because
16130 ** cases of nByte<=0 will be intercepted and dealt with by higher level
16131 ** routines.
16133 static void *sqlite3MemMalloc(int nByte){
16134 #ifdef SQLITE_MALLOCSIZE
16135 void *p = SQLITE_MALLOC( nByte );
16136 if( p==0 ){
16137 testcase( sqlite3GlobalConfig.xLog!=0 );
16138 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16140 return p;
16141 #else
16142 sqlite3_int64 *p;
16143 assert( nByte>0 );
16144 nByte = ROUND8(nByte);
16145 p = SQLITE_MALLOC( nByte+8 );
16146 if( p ){
16147 p[0] = nByte;
16148 p++;
16149 }else{
16150 testcase( sqlite3GlobalConfig.xLog!=0 );
16151 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
16153 return (void *)p;
16154 #endif
16158 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
16159 ** or sqlite3MemRealloc().
16161 ** For this low-level routine, we already know that pPrior!=0 since
16162 ** cases where pPrior==0 will have been intecepted and dealt with
16163 ** by higher-level routines.
16165 static void sqlite3MemFree(void *pPrior){
16166 #ifdef SQLITE_MALLOCSIZE
16167 SQLITE_FREE(pPrior);
16168 #else
16169 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16170 assert( pPrior!=0 );
16171 p--;
16172 SQLITE_FREE(p);
16173 #endif
16177 ** Report the allocated size of a prior return from xMalloc()
16178 ** or xRealloc().
16180 static int sqlite3MemSize(void *pPrior){
16181 #ifdef SQLITE_MALLOCSIZE
16182 return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
16183 #else
16184 sqlite3_int64 *p;
16185 if( pPrior==0 ) return 0;
16186 p = (sqlite3_int64*)pPrior;
16187 p--;
16188 return (int)p[0];
16189 #endif
16193 ** Like realloc(). Resize an allocation previously obtained from
16194 ** sqlite3MemMalloc().
16196 ** For this low-level interface, we know that pPrior!=0. Cases where
16197 ** pPrior==0 while have been intercepted by higher-level routine and
16198 ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
16199 ** cases where nByte<=0 will have been intercepted by higher-level
16200 ** routines and redirected to xFree.
16202 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16203 #ifdef SQLITE_MALLOCSIZE
16204 void *p = SQLITE_REALLOC(pPrior, nByte);
16205 if( p==0 ){
16206 testcase( sqlite3GlobalConfig.xLog!=0 );
16207 sqlite3_log(SQLITE_NOMEM,
16208 "failed memory resize %u to %u bytes",
16209 SQLITE_MALLOCSIZE(pPrior), nByte);
16211 return p;
16212 #else
16213 sqlite3_int64 *p = (sqlite3_int64*)pPrior;
16214 assert( pPrior!=0 && nByte>0 );
16215 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
16216 p--;
16217 p = SQLITE_REALLOC(p, nByte+8 );
16218 if( p ){
16219 p[0] = nByte;
16220 p++;
16221 }else{
16222 testcase( sqlite3GlobalConfig.xLog!=0 );
16223 sqlite3_log(SQLITE_NOMEM,
16224 "failed memory resize %u to %u bytes",
16225 sqlite3MemSize(pPrior), nByte);
16227 return (void*)p;
16228 #endif
16232 ** Round up a request size to the next valid allocation size.
16234 static int sqlite3MemRoundup(int n){
16235 return ROUND8(n);
16239 ** Initialize this module.
16241 static int sqlite3MemInit(void *NotUsed){
16242 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16243 int cpuCount;
16244 size_t len;
16245 if( _sqliteZone_ ){
16246 return SQLITE_OK;
16248 len = sizeof(cpuCount);
16249 /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
16250 sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
16251 if( cpuCount>1 ){
16252 /* defer MT decisions to system malloc */
16253 _sqliteZone_ = malloc_default_zone();
16254 }else{
16255 /* only 1 core, use our own zone to contention over global locks,
16256 ** e.g. we have our own dedicated locks */
16257 bool success;
16258 malloc_zone_t* newzone = malloc_create_zone(4096, 0);
16259 malloc_set_zone_name(newzone, "Sqlite_Heap");
16261 success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
16262 (void * volatile *)&_sqliteZone_);
16263 }while(!_sqliteZone_);
16264 if( !success ){
16265 /* somebody registered a zone first */
16266 malloc_destroy_zone(newzone);
16269 #endif
16270 UNUSED_PARAMETER(NotUsed);
16271 return SQLITE_OK;
16275 ** Deinitialize this module.
16277 static void sqlite3MemShutdown(void *NotUsed){
16278 UNUSED_PARAMETER(NotUsed);
16279 return;
16283 ** This routine is the only routine in this file with external linkage.
16285 ** Populate the low-level memory allocation function pointers in
16286 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16288 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16289 static const sqlite3_mem_methods defaultMethods = {
16290 sqlite3MemMalloc,
16291 sqlite3MemFree,
16292 sqlite3MemRealloc,
16293 sqlite3MemSize,
16294 sqlite3MemRoundup,
16295 sqlite3MemInit,
16296 sqlite3MemShutdown,
16299 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16302 #endif /* SQLITE_SYSTEM_MALLOC */
16304 /************** End of mem1.c ************************************************/
16305 /************** Begin file mem2.c ********************************************/
16307 ** 2007 August 15
16309 ** The author disclaims copyright to this source code. In place of
16310 ** a legal notice, here is a blessing:
16312 ** May you do good and not evil.
16313 ** May you find forgiveness for yourself and forgive others.
16314 ** May you share freely, never taking more than you give.
16316 *************************************************************************
16318 ** This file contains low-level memory allocation drivers for when
16319 ** SQLite will use the standard C-library malloc/realloc/free interface
16320 ** to obtain the memory it needs while adding lots of additional debugging
16321 ** information to each allocation in order to help detect and fix memory
16322 ** leaks and memory usage errors.
16324 ** This file contains implementations of the low-level memory allocation
16325 ** routines specified in the sqlite3_mem_methods object.
16329 ** This version of the memory allocator is used only if the
16330 ** SQLITE_MEMDEBUG macro is defined
16332 #ifdef SQLITE_MEMDEBUG
16335 ** The backtrace functionality is only available with GLIBC
16337 #ifdef __GLIBC__
16338 extern int backtrace(void**,int);
16339 extern void backtrace_symbols_fd(void*const*,int,int);
16340 #else
16341 # define backtrace(A,B) 1
16342 # define backtrace_symbols_fd(A,B,C)
16343 #endif
16344 /* #include <stdio.h> */
16347 ** Each memory allocation looks like this:
16349 ** ------------------------------------------------------------------------
16350 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
16351 ** ------------------------------------------------------------------------
16353 ** The application code sees only a pointer to the allocation. We have
16354 ** to back up from the allocation pointer to find the MemBlockHdr. The
16355 ** MemBlockHdr tells us the size of the allocation and the number of
16356 ** backtrace pointers. There is also a guard word at the end of the
16357 ** MemBlockHdr.
16359 struct MemBlockHdr {
16360 i64 iSize; /* Size of this allocation */
16361 struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
16362 char nBacktrace; /* Number of backtraces on this alloc */
16363 char nBacktraceSlots; /* Available backtrace slots */
16364 u8 nTitle; /* Bytes of title; includes '\0' */
16365 u8 eType; /* Allocation type code */
16366 int iForeGuard; /* Guard word for sanity */
16370 ** Guard words
16372 #define FOREGUARD 0x80F5E153
16373 #define REARGUARD 0xE4676B53
16376 ** Number of malloc size increments to track.
16378 #define NCSIZE 1000
16381 ** All of the static variables used by this module are collected
16382 ** into a single structure named "mem". This is to keep the
16383 ** static variables organized and to reduce namespace pollution
16384 ** when this module is combined with other in the amalgamation.
16386 static struct {
16389 ** Mutex to control access to the memory allocation subsystem.
16391 sqlite3_mutex *mutex;
16394 ** Head and tail of a linked list of all outstanding allocations
16396 struct MemBlockHdr *pFirst;
16397 struct MemBlockHdr *pLast;
16400 ** The number of levels of backtrace to save in new allocations.
16402 int nBacktrace;
16403 void (*xBacktrace)(int, int, void **);
16406 ** Title text to insert in front of each block
16408 int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
16409 char zTitle[100]; /* The title text */
16412 ** sqlite3MallocDisallow() increments the following counter.
16413 ** sqlite3MallocAllow() decrements it.
16415 int disallow; /* Do not allow memory allocation */
16418 ** Gather statistics on the sizes of memory allocations.
16419 ** nAlloc[i] is the number of allocation attempts of i*8
16420 ** bytes. i==NCSIZE is the number of allocation attempts for
16421 ** sizes more than NCSIZE*8 bytes.
16423 int nAlloc[NCSIZE]; /* Total number of allocations */
16424 int nCurrent[NCSIZE]; /* Current number of allocations */
16425 int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
16427 } mem;
16431 ** Adjust memory usage statistics
16433 static void adjustStats(int iSize, int increment){
16434 int i = ROUND8(iSize)/8;
16435 if( i>NCSIZE-1 ){
16436 i = NCSIZE - 1;
16438 if( increment>0 ){
16439 mem.nAlloc[i]++;
16440 mem.nCurrent[i]++;
16441 if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16442 mem.mxCurrent[i] = mem.nCurrent[i];
16444 }else{
16445 mem.nCurrent[i]--;
16446 assert( mem.nCurrent[i]>=0 );
16451 ** Given an allocation, find the MemBlockHdr for that allocation.
16453 ** This routine checks the guards at either end of the allocation and
16454 ** if they are incorrect it asserts.
16456 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16457 struct MemBlockHdr *p;
16458 int *pInt;
16459 u8 *pU8;
16460 int nReserve;
16462 p = (struct MemBlockHdr*)pAllocation;
16463 p--;
16464 assert( p->iForeGuard==(int)FOREGUARD );
16465 nReserve = ROUND8(p->iSize);
16466 pInt = (int*)pAllocation;
16467 pU8 = (u8*)pAllocation;
16468 assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16469 /* This checks any of the "extra" bytes allocated due
16470 ** to rounding up to an 8 byte boundary to ensure
16471 ** they haven't been overwritten.
16473 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16474 return p;
16478 ** Return the number of bytes currently allocated at address p.
16480 static int sqlite3MemSize(void *p){
16481 struct MemBlockHdr *pHdr;
16482 if( !p ){
16483 return 0;
16485 pHdr = sqlite3MemsysGetHeader(p);
16486 return (int)pHdr->iSize;
16490 ** Initialize the memory allocation subsystem.
16492 static int sqlite3MemInit(void *NotUsed){
16493 UNUSED_PARAMETER(NotUsed);
16494 assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16495 if( !sqlite3GlobalConfig.bMemstat ){
16496 /* If memory status is enabled, then the malloc.c wrapper will already
16497 ** hold the STATIC_MEM mutex when the routines here are invoked. */
16498 mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16500 return SQLITE_OK;
16504 ** Deinitialize the memory allocation subsystem.
16506 static void sqlite3MemShutdown(void *NotUsed){
16507 UNUSED_PARAMETER(NotUsed);
16508 mem.mutex = 0;
16512 ** Round up a request size to the next valid allocation size.
16514 static int sqlite3MemRoundup(int n){
16515 return ROUND8(n);
16519 ** Fill a buffer with pseudo-random bytes. This is used to preset
16520 ** the content of a new memory allocation to unpredictable values and
16521 ** to clear the content of a freed allocation to unpredictable values.
16523 static void randomFill(char *pBuf, int nByte){
16524 unsigned int x, y, r;
16525 x = SQLITE_PTR_TO_INT(pBuf);
16526 y = nByte | 1;
16527 while( nByte >= 4 ){
16528 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16529 y = y*1103515245 + 12345;
16530 r = x ^ y;
16531 *(int*)pBuf = r;
16532 pBuf += 4;
16533 nByte -= 4;
16535 while( nByte-- > 0 ){
16536 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
16537 y = y*1103515245 + 12345;
16538 r = x ^ y;
16539 *(pBuf++) = r & 0xff;
16544 ** Allocate nByte bytes of memory.
16546 static void *sqlite3MemMalloc(int nByte){
16547 struct MemBlockHdr *pHdr;
16548 void **pBt;
16549 char *z;
16550 int *pInt;
16551 void *p = 0;
16552 int totalSize;
16553 int nReserve;
16554 sqlite3_mutex_enter(mem.mutex);
16555 assert( mem.disallow==0 );
16556 nReserve = ROUND8(nByte);
16557 totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16558 mem.nBacktrace*sizeof(void*) + mem.nTitle;
16559 p = malloc(totalSize);
16560 if( p ){
16561 z = p;
16562 pBt = (void**)&z[mem.nTitle];
16563 pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16564 pHdr->pNext = 0;
16565 pHdr->pPrev = mem.pLast;
16566 if( mem.pLast ){
16567 mem.pLast->pNext = pHdr;
16568 }else{
16569 mem.pFirst = pHdr;
16571 mem.pLast = pHdr;
16572 pHdr->iForeGuard = FOREGUARD;
16573 pHdr->eType = MEMTYPE_HEAP;
16574 pHdr->nBacktraceSlots = mem.nBacktrace;
16575 pHdr->nTitle = mem.nTitle;
16576 if( mem.nBacktrace ){
16577 void *aAddr[40];
16578 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16579 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16580 assert(pBt[0]);
16581 if( mem.xBacktrace ){
16582 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16584 }else{
16585 pHdr->nBacktrace = 0;
16587 if( mem.nTitle ){
16588 memcpy(z, mem.zTitle, mem.nTitle);
16590 pHdr->iSize = nByte;
16591 adjustStats(nByte, +1);
16592 pInt = (int*)&pHdr[1];
16593 pInt[nReserve/sizeof(int)] = REARGUARD;
16594 randomFill((char*)pInt, nByte);
16595 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16596 p = (void*)pInt;
16598 sqlite3_mutex_leave(mem.mutex);
16599 return p;
16603 ** Free memory.
16605 static void sqlite3MemFree(void *pPrior){
16606 struct MemBlockHdr *pHdr;
16607 void **pBt;
16608 char *z;
16609 assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
16610 || mem.mutex!=0 );
16611 pHdr = sqlite3MemsysGetHeader(pPrior);
16612 pBt = (void**)pHdr;
16613 pBt -= pHdr->nBacktraceSlots;
16614 sqlite3_mutex_enter(mem.mutex);
16615 if( pHdr->pPrev ){
16616 assert( pHdr->pPrev->pNext==pHdr );
16617 pHdr->pPrev->pNext = pHdr->pNext;
16618 }else{
16619 assert( mem.pFirst==pHdr );
16620 mem.pFirst = pHdr->pNext;
16622 if( pHdr->pNext ){
16623 assert( pHdr->pNext->pPrev==pHdr );
16624 pHdr->pNext->pPrev = pHdr->pPrev;
16625 }else{
16626 assert( mem.pLast==pHdr );
16627 mem.pLast = pHdr->pPrev;
16629 z = (char*)pBt;
16630 z -= pHdr->nTitle;
16631 adjustStats((int)pHdr->iSize, -1);
16632 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16633 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
16634 free(z);
16635 sqlite3_mutex_leave(mem.mutex);
16639 ** Change the size of an existing memory allocation.
16641 ** For this debugging implementation, we *always* make a copy of the
16642 ** allocation into a new place in memory. In this way, if the
16643 ** higher level code is using pointer to the old allocation, it is
16644 ** much more likely to break and we are much more liking to find
16645 ** the error.
16647 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16648 struct MemBlockHdr *pOldHdr;
16649 void *pNew;
16650 assert( mem.disallow==0 );
16651 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
16652 pOldHdr = sqlite3MemsysGetHeader(pPrior);
16653 pNew = sqlite3MemMalloc(nByte);
16654 if( pNew ){
16655 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
16656 if( nByte>pOldHdr->iSize ){
16657 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
16659 sqlite3MemFree(pPrior);
16661 return pNew;
16665 ** Populate the low-level memory allocation function pointers in
16666 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16668 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16669 static const sqlite3_mem_methods defaultMethods = {
16670 sqlite3MemMalloc,
16671 sqlite3MemFree,
16672 sqlite3MemRealloc,
16673 sqlite3MemSize,
16674 sqlite3MemRoundup,
16675 sqlite3MemInit,
16676 sqlite3MemShutdown,
16679 sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16683 ** Set the "type" of an allocation.
16685 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16686 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16687 struct MemBlockHdr *pHdr;
16688 pHdr = sqlite3MemsysGetHeader(p);
16689 assert( pHdr->iForeGuard==FOREGUARD );
16690 pHdr->eType = eType;
16695 ** Return TRUE if the mask of type in eType matches the type of the
16696 ** allocation p. Also return true if p==NULL.
16698 ** This routine is designed for use within an assert() statement, to
16699 ** verify the type of an allocation. For example:
16701 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16703 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16704 int rc = 1;
16705 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16706 struct MemBlockHdr *pHdr;
16707 pHdr = sqlite3MemsysGetHeader(p);
16708 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
16709 if( (pHdr->eType&eType)==0 ){
16710 rc = 0;
16713 return rc;
16717 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16718 ** allocation p. Also return true if p==NULL.
16720 ** This routine is designed for use within an assert() statement, to
16721 ** verify the type of an allocation. For example:
16723 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16725 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16726 int rc = 1;
16727 if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16728 struct MemBlockHdr *pHdr;
16729 pHdr = sqlite3MemsysGetHeader(p);
16730 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
16731 if( (pHdr->eType&eType)!=0 ){
16732 rc = 0;
16735 return rc;
16739 ** Set the number of backtrace levels kept for each allocation.
16740 ** A value of zero turns off backtracing. The number is always rounded
16741 ** up to a multiple of 2.
16743 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16744 if( depth<0 ){ depth = 0; }
16745 if( depth>20 ){ depth = 20; }
16746 depth = (depth+1)&0xfe;
16747 mem.nBacktrace = depth;
16750 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16751 mem.xBacktrace = xBacktrace;
16755 ** Set the title string for subsequent allocations.
16757 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16758 unsigned int n = sqlite3Strlen30(zTitle) + 1;
16759 sqlite3_mutex_enter(mem.mutex);
16760 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16761 memcpy(mem.zTitle, zTitle, n);
16762 mem.zTitle[n] = 0;
16763 mem.nTitle = ROUND8(n);
16764 sqlite3_mutex_leave(mem.mutex);
16767 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16768 struct MemBlockHdr *pHdr;
16769 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16770 void **pBt = (void**)pHdr;
16771 pBt -= pHdr->nBacktraceSlots;
16772 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16777 ** Open the file indicated and write a log of all unfreed memory
16778 ** allocations into that log.
16780 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16781 FILE *out;
16782 struct MemBlockHdr *pHdr;
16783 void **pBt;
16784 int i;
16785 out = fopen(zFilename, "w");
16786 if( out==0 ){
16787 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16788 zFilename);
16789 return;
16791 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16792 char *z = (char*)pHdr;
16793 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16794 fprintf(out, "**** %lld bytes at %p from %s ****\n",
16795 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16796 if( pHdr->nBacktrace ){
16797 fflush(out);
16798 pBt = (void**)pHdr;
16799 pBt -= pHdr->nBacktraceSlots;
16800 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16801 fprintf(out, "\n");
16804 fprintf(out, "COUNTS:\n");
16805 for(i=0; i<NCSIZE-1; i++){
16806 if( mem.nAlloc[i] ){
16807 fprintf(out, " %5d: %10d %10d %10d\n",
16808 i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16811 if( mem.nAlloc[NCSIZE-1] ){
16812 fprintf(out, " %5d: %10d %10d %10d\n",
16813 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16814 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16816 fclose(out);
16820 ** Return the number of times sqlite3MemMalloc() has been called.
16822 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16823 int i;
16824 int nTotal = 0;
16825 for(i=0; i<NCSIZE; i++){
16826 nTotal += mem.nAlloc[i];
16828 return nTotal;
16832 #endif /* SQLITE_MEMDEBUG */
16834 /************** End of mem2.c ************************************************/
16835 /************** Begin file mem3.c ********************************************/
16837 ** 2007 October 14
16839 ** The author disclaims copyright to this source code. In place of
16840 ** a legal notice, here is a blessing:
16842 ** May you do good and not evil.
16843 ** May you find forgiveness for yourself and forgive others.
16844 ** May you share freely, never taking more than you give.
16846 *************************************************************************
16847 ** This file contains the C functions that implement a memory
16848 ** allocation subsystem for use by SQLite.
16850 ** This version of the memory allocation subsystem omits all
16851 ** use of malloc(). The SQLite user supplies a block of memory
16852 ** before calling sqlite3_initialize() from which allocations
16853 ** are made and returned by the xMalloc() and xRealloc()
16854 ** implementations. Once sqlite3_initialize() has been called,
16855 ** the amount of memory available to SQLite is fixed and cannot
16856 ** be changed.
16858 ** This version of the memory allocation subsystem is included
16859 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16863 ** This version of the memory allocator is only built into the library
16864 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16865 ** mean that the library will use a memory-pool by default, just that
16866 ** it is available. The mempool allocator is activated by calling
16867 ** sqlite3_config().
16869 #ifdef SQLITE_ENABLE_MEMSYS3
16872 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16874 #define MX_SMALL 10
16878 ** Number of freelist hash slots
16880 #define N_HASH 61
16883 ** A memory allocation (also called a "chunk") consists of two or
16884 ** more blocks where each block is 8 bytes. The first 8 bytes are
16885 ** a header that is not returned to the user.
16887 ** A chunk is two or more blocks that is either checked out or
16888 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
16889 ** size of the allocation in blocks if the allocation is free.
16890 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16891 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
16892 ** is true if the previous chunk is checked out and false if the
16893 ** previous chunk is free. The u.hdr.prevSize field is the size of
16894 ** the previous chunk in blocks if the previous chunk is on the
16895 ** freelist. If the previous chunk is checked out, then
16896 ** u.hdr.prevSize can be part of the data for that chunk and should
16897 ** not be read or written.
16899 ** We often identify a chunk by its index in mem3.aPool[]. When
16900 ** this is done, the chunk index refers to the second block of
16901 ** the chunk. In this way, the first chunk has an index of 1.
16902 ** A chunk index of 0 means "no such chunk" and is the equivalent
16903 ** of a NULL pointer.
16905 ** The second block of free chunks is of the form u.list. The
16906 ** two fields form a double-linked list of chunks of related sizes.
16907 ** Pointers to the head of the list are stored in mem3.aiSmall[]
16908 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16910 ** The second block of a chunk is user data if the chunk is checked
16911 ** out. If a chunk is checked out, the user data may extend into
16912 ** the u.hdr.prevSize value of the following chunk.
16914 typedef struct Mem3Block Mem3Block;
16915 struct Mem3Block {
16916 union {
16917 struct {
16918 u32 prevSize; /* Size of previous chunk in Mem3Block elements */
16919 u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
16920 } hdr;
16921 struct {
16922 u32 next; /* Index in mem3.aPool[] of next free chunk */
16923 u32 prev; /* Index in mem3.aPool[] of previous free chunk */
16924 } list;
16925 } u;
16929 ** All of the static variables used by this module are collected
16930 ** into a single structure named "mem3". This is to keep the
16931 ** static variables organized and to reduce namespace pollution
16932 ** when this module is combined with other in the amalgamation.
16934 static SQLITE_WSD struct Mem3Global {
16936 ** Memory available for allocation. nPool is the size of the array
16937 ** (in Mem3Blocks) pointed to by aPool less 2.
16939 u32 nPool;
16940 Mem3Block *aPool;
16943 ** True if we are evaluating an out-of-memory callback.
16945 int alarmBusy;
16948 ** Mutex to control access to the memory allocation subsystem.
16950 sqlite3_mutex *mutex;
16953 ** The minimum amount of free space that we have seen.
16955 u32 mnMaster;
16958 ** iMaster is the index of the master chunk. Most new allocations
16959 ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
16960 ** of the current master. iMaster is 0 if there is not master chunk.
16961 ** The master chunk is not in either the aiHash[] or aiSmall[].
16963 u32 iMaster;
16964 u32 szMaster;
16967 ** Array of lists of free blocks according to the block size
16968 ** for smaller chunks, or a hash on the block size for larger
16969 ** chunks.
16971 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
16972 u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
16973 } mem3 = { 97535575 };
16975 #define mem3 GLOBAL(struct Mem3Global, mem3)
16978 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16979 ** on. *pRoot is the list that i is a member of.
16981 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16982 u32 next = mem3.aPool[i].u.list.next;
16983 u32 prev = mem3.aPool[i].u.list.prev;
16984 assert( sqlite3_mutex_held(mem3.mutex) );
16985 if( prev==0 ){
16986 *pRoot = next;
16987 }else{
16988 mem3.aPool[prev].u.list.next = next;
16990 if( next ){
16991 mem3.aPool[next].u.list.prev = prev;
16993 mem3.aPool[i].u.list.next = 0;
16994 mem3.aPool[i].u.list.prev = 0;
16998 ** Unlink the chunk at index i from
16999 ** whatever list is currently a member of.
17001 static void memsys3Unlink(u32 i){
17002 u32 size, hash;
17003 assert( sqlite3_mutex_held(mem3.mutex) );
17004 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17005 assert( i>=1 );
17006 size = mem3.aPool[i-1].u.hdr.size4x/4;
17007 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17008 assert( size>=2 );
17009 if( size <= MX_SMALL ){
17010 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17011 }else{
17012 hash = size % N_HASH;
17013 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17018 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17019 ** at *pRoot.
17021 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17022 assert( sqlite3_mutex_held(mem3.mutex) );
17023 mem3.aPool[i].u.list.next = *pRoot;
17024 mem3.aPool[i].u.list.prev = 0;
17025 if( *pRoot ){
17026 mem3.aPool[*pRoot].u.list.prev = i;
17028 *pRoot = i;
17032 ** Link the chunk at index i into either the appropriate
17033 ** small chunk list, or into the large chunk hash table.
17035 static void memsys3Link(u32 i){
17036 u32 size, hash;
17037 assert( sqlite3_mutex_held(mem3.mutex) );
17038 assert( i>=1 );
17039 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17040 size = mem3.aPool[i-1].u.hdr.size4x/4;
17041 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17042 assert( size>=2 );
17043 if( size <= MX_SMALL ){
17044 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17045 }else{
17046 hash = size % N_HASH;
17047 memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17052 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17053 ** will already be held (obtained by code in malloc.c) if
17054 ** sqlite3GlobalConfig.bMemStat is true.
17056 static void memsys3Enter(void){
17057 if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17058 mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17060 sqlite3_mutex_enter(mem3.mutex);
17062 static void memsys3Leave(void){
17063 sqlite3_mutex_leave(mem3.mutex);
17067 ** Called when we are unable to satisfy an allocation of nBytes.
17069 static void memsys3OutOfMemory(int nByte){
17070 if( !mem3.alarmBusy ){
17071 mem3.alarmBusy = 1;
17072 assert( sqlite3_mutex_held(mem3.mutex) );
17073 sqlite3_mutex_leave(mem3.mutex);
17074 sqlite3_release_memory(nByte);
17075 sqlite3_mutex_enter(mem3.mutex);
17076 mem3.alarmBusy = 0;
17082 ** Chunk i is a free chunk that has been unlinked. Adjust its
17083 ** size parameters for check-out and return a pointer to the
17084 ** user portion of the chunk.
17086 static void *memsys3Checkout(u32 i, u32 nBlock){
17087 u32 x;
17088 assert( sqlite3_mutex_held(mem3.mutex) );
17089 assert( i>=1 );
17090 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
17091 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
17092 x = mem3.aPool[i-1].u.hdr.size4x;
17093 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
17094 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
17095 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
17096 return &mem3.aPool[i];
17100 ** Carve a piece off of the end of the mem3.iMaster free chunk.
17101 ** Return a pointer to the new allocation. Or, if the master chunk
17102 ** is not large enough, return 0.
17104 static void *memsys3FromMaster(u32 nBlock){
17105 assert( sqlite3_mutex_held(mem3.mutex) );
17106 assert( mem3.szMaster>=nBlock );
17107 if( nBlock>=mem3.szMaster-1 ){
17108 /* Use the entire master */
17109 void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
17110 mem3.iMaster = 0;
17111 mem3.szMaster = 0;
17112 mem3.mnMaster = 0;
17113 return p;
17114 }else{
17115 /* Split the master block. Return the tail. */
17116 u32 newi, x;
17117 newi = mem3.iMaster + mem3.szMaster - nBlock;
17118 assert( newi > mem3.iMaster+1 );
17119 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
17120 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
17121 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
17122 mem3.szMaster -= nBlock;
17123 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
17124 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17125 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17126 if( mem3.szMaster < mem3.mnMaster ){
17127 mem3.mnMaster = mem3.szMaster;
17129 return (void*)&mem3.aPool[newi];
17134 ** *pRoot is the head of a list of free chunks of the same size
17135 ** or same size hash. In other words, *pRoot is an entry in either
17136 ** mem3.aiSmall[] or mem3.aiHash[].
17138 ** This routine examines all entries on the given list and tries
17139 ** to coalesce each entries with adjacent free chunks.
17141 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
17142 ** the current mem3.iMaster with the new larger chunk. In order for
17143 ** this mem3.iMaster replacement to work, the master chunk must be
17144 ** linked into the hash tables. That is not the normal state of
17145 ** affairs, of course. The calling routine must link the master
17146 ** chunk before invoking this routine, then must unlink the (possibly
17147 ** changed) master chunk once this routine has finished.
17149 static void memsys3Merge(u32 *pRoot){
17150 u32 iNext, prev, size, i, x;
17152 assert( sqlite3_mutex_held(mem3.mutex) );
17153 for(i=*pRoot; i>0; i=iNext){
17154 iNext = mem3.aPool[i].u.list.next;
17155 size = mem3.aPool[i-1].u.hdr.size4x;
17156 assert( (size&1)==0 );
17157 if( (size&2)==0 ){
17158 memsys3UnlinkFromList(i, pRoot);
17159 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
17160 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
17161 if( prev==iNext ){
17162 iNext = mem3.aPool[prev].u.list.next;
17164 memsys3Unlink(prev);
17165 size = i + size/4 - prev;
17166 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
17167 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
17168 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
17169 memsys3Link(prev);
17170 i = prev;
17171 }else{
17172 size /= 4;
17174 if( size>mem3.szMaster ){
17175 mem3.iMaster = i;
17176 mem3.szMaster = size;
17182 ** Return a block of memory of at least nBytes in size.
17183 ** Return NULL if unable.
17185 ** This function assumes that the necessary mutexes, if any, are
17186 ** already held by the caller. Hence "Unsafe".
17188 static void *memsys3MallocUnsafe(int nByte){
17189 u32 i;
17190 u32 nBlock;
17191 u32 toFree;
17193 assert( sqlite3_mutex_held(mem3.mutex) );
17194 assert( sizeof(Mem3Block)==8 );
17195 if( nByte<=12 ){
17196 nBlock = 2;
17197 }else{
17198 nBlock = (nByte + 11)/8;
17200 assert( nBlock>=2 );
17202 /* STEP 1:
17203 ** Look for an entry of the correct size in either the small
17204 ** chunk table or in the large chunk hash table. This is
17205 ** successful most of the time (about 9 times out of 10).
17207 if( nBlock <= MX_SMALL ){
17208 i = mem3.aiSmall[nBlock-2];
17209 if( i>0 ){
17210 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
17211 return memsys3Checkout(i, nBlock);
17213 }else{
17214 int hash = nBlock % N_HASH;
17215 for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
17216 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
17217 memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17218 return memsys3Checkout(i, nBlock);
17223 /* STEP 2:
17224 ** Try to satisfy the allocation by carving a piece off of the end
17225 ** of the master chunk. This step usually works if step 1 fails.
17227 if( mem3.szMaster>=nBlock ){
17228 return memsys3FromMaster(nBlock);
17232 /* STEP 3:
17233 ** Loop through the entire memory pool. Coalesce adjacent free
17234 ** chunks. Recompute the master chunk as the largest free chunk.
17235 ** Then try again to satisfy the allocation by carving a piece off
17236 ** of the end of the master chunk. This step happens very
17237 ** rarely (we hope!)
17239 for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
17240 memsys3OutOfMemory(toFree);
17241 if( mem3.iMaster ){
17242 memsys3Link(mem3.iMaster);
17243 mem3.iMaster = 0;
17244 mem3.szMaster = 0;
17246 for(i=0; i<N_HASH; i++){
17247 memsys3Merge(&mem3.aiHash[i]);
17249 for(i=0; i<MX_SMALL-1; i++){
17250 memsys3Merge(&mem3.aiSmall[i]);
17252 if( mem3.szMaster ){
17253 memsys3Unlink(mem3.iMaster);
17254 if( mem3.szMaster>=nBlock ){
17255 return memsys3FromMaster(nBlock);
17260 /* If none of the above worked, then we fail. */
17261 return 0;
17265 ** Free an outstanding memory allocation.
17267 ** This function assumes that the necessary mutexes, if any, are
17268 ** already held by the caller. Hence "Unsafe".
17270 static void memsys3FreeUnsafe(void *pOld){
17271 Mem3Block *p = (Mem3Block*)pOld;
17272 int i;
17273 u32 size, x;
17274 assert( sqlite3_mutex_held(mem3.mutex) );
17275 assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
17276 i = p - mem3.aPool;
17277 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
17278 size = mem3.aPool[i-1].u.hdr.size4x/4;
17279 assert( i+size<=mem3.nPool+1 );
17280 mem3.aPool[i-1].u.hdr.size4x &= ~1;
17281 mem3.aPool[i+size-1].u.hdr.prevSize = size;
17282 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
17283 memsys3Link(i);
17285 /* Try to expand the master using the newly freed chunk */
17286 if( mem3.iMaster ){
17287 while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
17288 size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
17289 mem3.iMaster -= size;
17290 mem3.szMaster += size;
17291 memsys3Unlink(mem3.iMaster);
17292 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17293 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17294 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17296 x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
17297 while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
17298 memsys3Unlink(mem3.iMaster+mem3.szMaster);
17299 mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
17300 mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
17301 mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
17307 ** Return the size of an outstanding allocation, in bytes. The
17308 ** size returned omits the 8-byte header overhead. This only
17309 ** works for chunks that are currently checked out.
17311 static int memsys3Size(void *p){
17312 Mem3Block *pBlock;
17313 if( p==0 ) return 0;
17314 pBlock = (Mem3Block*)p;
17315 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
17316 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
17320 ** Round up a request size to the next valid allocation size.
17322 static int memsys3Roundup(int n){
17323 if( n<=12 ){
17324 return 12;
17325 }else{
17326 return ((n+11)&~7) - 4;
17331 ** Allocate nBytes of memory.
17333 static void *memsys3Malloc(int nBytes){
17334 sqlite3_int64 *p;
17335 assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
17336 memsys3Enter();
17337 p = memsys3MallocUnsafe(nBytes);
17338 memsys3Leave();
17339 return (void*)p;
17343 ** Free memory.
17345 static void memsys3Free(void *pPrior){
17346 assert( pPrior );
17347 memsys3Enter();
17348 memsys3FreeUnsafe(pPrior);
17349 memsys3Leave();
17353 ** Change the size of an existing memory allocation
17355 static void *memsys3Realloc(void *pPrior, int nBytes){
17356 int nOld;
17357 void *p;
17358 if( pPrior==0 ){
17359 return sqlite3_malloc(nBytes);
17361 if( nBytes<=0 ){
17362 sqlite3_free(pPrior);
17363 return 0;
17365 nOld = memsys3Size(pPrior);
17366 if( nBytes<=nOld && nBytes>=nOld-128 ){
17367 return pPrior;
17369 memsys3Enter();
17370 p = memsys3MallocUnsafe(nBytes);
17371 if( p ){
17372 if( nOld<nBytes ){
17373 memcpy(p, pPrior, nOld);
17374 }else{
17375 memcpy(p, pPrior, nBytes);
17377 memsys3FreeUnsafe(pPrior);
17379 memsys3Leave();
17380 return p;
17384 ** Initialize this module.
17386 static int memsys3Init(void *NotUsed){
17387 UNUSED_PARAMETER(NotUsed);
17388 if( !sqlite3GlobalConfig.pHeap ){
17389 return SQLITE_ERROR;
17392 /* Store a pointer to the memory block in global structure mem3. */
17393 assert( sizeof(Mem3Block)==8 );
17394 mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
17395 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
17397 /* Initialize the master block. */
17398 mem3.szMaster = mem3.nPool;
17399 mem3.mnMaster = mem3.szMaster;
17400 mem3.iMaster = 1;
17401 mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17402 mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17403 mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17405 return SQLITE_OK;
17409 ** Deinitialize this module.
17411 static void memsys3Shutdown(void *NotUsed){
17412 UNUSED_PARAMETER(NotUsed);
17413 mem3.mutex = 0;
17414 return;
17420 ** Open the file indicated and write a log of all unfreed memory
17421 ** allocations into that log.
17423 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17424 #ifdef SQLITE_DEBUG
17425 FILE *out;
17426 u32 i, j;
17427 u32 size;
17428 if( zFilename==0 || zFilename[0]==0 ){
17429 out = stdout;
17430 }else{
17431 out = fopen(zFilename, "w");
17432 if( out==0 ){
17433 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17434 zFilename);
17435 return;
17438 memsys3Enter();
17439 fprintf(out, "CHUNKS:\n");
17440 for(i=1; i<=mem3.nPool; i+=size/4){
17441 size = mem3.aPool[i-1].u.hdr.size4x;
17442 if( size/4<=1 ){
17443 fprintf(out, "%p size error\n", &mem3.aPool[i]);
17444 assert( 0 );
17445 break;
17447 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17448 fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17449 assert( 0 );
17450 break;
17452 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17453 fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17454 assert( 0 );
17455 break;
17457 if( size&1 ){
17458 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17459 }else{
17460 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17461 i==mem3.iMaster ? " **master**" : "");
17464 for(i=0; i<MX_SMALL-1; i++){
17465 if( mem3.aiSmall[i]==0 ) continue;
17466 fprintf(out, "small(%2d):", i);
17467 for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17468 fprintf(out, " %p(%d)", &mem3.aPool[j],
17469 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17471 fprintf(out, "\n");
17473 for(i=0; i<N_HASH; i++){
17474 if( mem3.aiHash[i]==0 ) continue;
17475 fprintf(out, "hash(%2d):", i);
17476 for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17477 fprintf(out, " %p(%d)", &mem3.aPool[j],
17478 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17480 fprintf(out, "\n");
17482 fprintf(out, "master=%d\n", mem3.iMaster);
17483 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17484 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17485 sqlite3_mutex_leave(mem3.mutex);
17486 if( out==stdout ){
17487 fflush(stdout);
17488 }else{
17489 fclose(out);
17491 #else
17492 UNUSED_PARAMETER(zFilename);
17493 #endif
17497 ** This routine is the only routine in this file with external
17498 ** linkage.
17500 ** Populate the low-level memory allocation function pointers in
17501 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17502 ** arguments specify the block of memory to manage.
17504 ** This routine is only called by sqlite3_config(), and therefore
17505 ** is not required to be threadsafe (it is not).
17507 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17508 static const sqlite3_mem_methods mempoolMethods = {
17509 memsys3Malloc,
17510 memsys3Free,
17511 memsys3Realloc,
17512 memsys3Size,
17513 memsys3Roundup,
17514 memsys3Init,
17515 memsys3Shutdown,
17518 return &mempoolMethods;
17521 #endif /* SQLITE_ENABLE_MEMSYS3 */
17523 /************** End of mem3.c ************************************************/
17524 /************** Begin file mem5.c ********************************************/
17526 ** 2007 October 14
17528 ** The author disclaims copyright to this source code. In place of
17529 ** a legal notice, here is a blessing:
17531 ** May you do good and not evil.
17532 ** May you find forgiveness for yourself and forgive others.
17533 ** May you share freely, never taking more than you give.
17535 *************************************************************************
17536 ** This file contains the C functions that implement a memory
17537 ** allocation subsystem for use by SQLite.
17539 ** This version of the memory allocation subsystem omits all
17540 ** use of malloc(). The application gives SQLite a block of memory
17541 ** before calling sqlite3_initialize() from which allocations
17542 ** are made and returned by the xMalloc() and xRealloc()
17543 ** implementations. Once sqlite3_initialize() has been called,
17544 ** the amount of memory available to SQLite is fixed and cannot
17545 ** be changed.
17547 ** This version of the memory allocation subsystem is included
17548 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17550 ** This memory allocator uses the following algorithm:
17552 ** 1. All memory allocations sizes are rounded up to a power of 2.
17554 ** 2. If two adjacent free blocks are the halves of a larger block,
17555 ** then the two blocks are coalesed into the single larger block.
17557 ** 3. New memory is allocated from the first available free block.
17559 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17560 ** Concerning Dynamic Storage Allocation". Journal of the Association for
17561 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17563 ** Let n be the size of the largest allocation divided by the minimum
17564 ** allocation size (after rounding all sizes up to a power of 2.) Let M
17565 ** be the maximum amount of memory ever outstanding at one time. Let
17566 ** N be the total amount of memory available for allocation. Robson
17567 ** proved that this memory allocator will never breakdown due to
17568 ** fragmentation as long as the following constraint holds:
17570 ** N >= M*(1 + log2(n)/2) - n + 1
17572 ** The sqlite3_status() logic tracks the maximum values of n and M so
17573 ** that an application can, at any time, verify this constraint.
17577 ** This version of the memory allocator is used only when
17578 ** SQLITE_ENABLE_MEMSYS5 is defined.
17580 #ifdef SQLITE_ENABLE_MEMSYS5
17583 ** A minimum allocation is an instance of the following structure.
17584 ** Larger allocations are an array of these structures where the
17585 ** size of the array is a power of 2.
17587 ** The size of this object must be a power of two. That fact is
17588 ** verified in memsys5Init().
17590 typedef struct Mem5Link Mem5Link;
17591 struct Mem5Link {
17592 int next; /* Index of next free chunk */
17593 int prev; /* Index of previous free chunk */
17597 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17598 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17599 ** it is not actually possible to reach this limit.
17601 #define LOGMAX 30
17604 ** Masks used for mem5.aCtrl[] elements.
17606 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
17607 #define CTRL_FREE 0x20 /* True if not checked out */
17610 ** All of the static variables used by this module are collected
17611 ** into a single structure named "mem5". This is to keep the
17612 ** static variables organized and to reduce namespace pollution
17613 ** when this module is combined with other in the amalgamation.
17615 static SQLITE_WSD struct Mem5Global {
17617 ** Memory available for allocation
17619 int szAtom; /* Smallest possible allocation in bytes */
17620 int nBlock; /* Number of szAtom sized blocks in zPool */
17621 u8 *zPool; /* Memory available to be allocated */
17624 ** Mutex to control access to the memory allocation subsystem.
17626 sqlite3_mutex *mutex;
17629 ** Performance statistics
17631 u64 nAlloc; /* Total number of calls to malloc */
17632 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
17633 u64 totalExcess; /* Total internal fragmentation */
17634 u32 currentOut; /* Current checkout, including internal fragmentation */
17635 u32 currentCount; /* Current number of distinct checkouts */
17636 u32 maxOut; /* Maximum instantaneous currentOut */
17637 u32 maxCount; /* Maximum instantaneous currentCount */
17638 u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
17641 ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
17642 ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
17643 ** and so forth.
17645 int aiFreelist[LOGMAX+1];
17648 ** Space for tracking which blocks are checked out and the size
17649 ** of each block. One byte per block.
17651 u8 *aCtrl;
17653 } mem5;
17656 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
17658 #define mem5 GLOBAL(struct Mem5Global, mem5)
17661 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17662 ** structures, return a pointer to the idx-th such link.
17664 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17667 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17668 ** on. It should be found on mem5.aiFreelist[iLogsize].
17670 static void memsys5Unlink(int i, int iLogsize){
17671 int next, prev;
17672 assert( i>=0 && i<mem5.nBlock );
17673 assert( iLogsize>=0 && iLogsize<=LOGMAX );
17674 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17676 next = MEM5LINK(i)->next;
17677 prev = MEM5LINK(i)->prev;
17678 if( prev<0 ){
17679 mem5.aiFreelist[iLogsize] = next;
17680 }else{
17681 MEM5LINK(prev)->next = next;
17683 if( next>=0 ){
17684 MEM5LINK(next)->prev = prev;
17689 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17690 ** free list.
17692 static void memsys5Link(int i, int iLogsize){
17693 int x;
17694 assert( sqlite3_mutex_held(mem5.mutex) );
17695 assert( i>=0 && i<mem5.nBlock );
17696 assert( iLogsize>=0 && iLogsize<=LOGMAX );
17697 assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17699 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17700 MEM5LINK(i)->prev = -1;
17701 if( x>=0 ){
17702 assert( x<mem5.nBlock );
17703 MEM5LINK(x)->prev = i;
17705 mem5.aiFreelist[iLogsize] = i;
17709 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17710 ** will already be held (obtained by code in malloc.c) if
17711 ** sqlite3GlobalConfig.bMemStat is true.
17713 static void memsys5Enter(void){
17714 sqlite3_mutex_enter(mem5.mutex);
17716 static void memsys5Leave(void){
17717 sqlite3_mutex_leave(mem5.mutex);
17721 ** Return the size of an outstanding allocation, in bytes. The
17722 ** size returned omits the 8-byte header overhead. This only
17723 ** works for chunks that are currently checked out.
17725 static int memsys5Size(void *p){
17726 int iSize = 0;
17727 if( p ){
17728 int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
17729 assert( i>=0 && i<mem5.nBlock );
17730 iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17732 return iSize;
17736 ** Return a block of memory of at least nBytes in size.
17737 ** Return NULL if unable. Return NULL if nBytes==0.
17739 ** The caller guarantees that nByte is positive.
17741 ** The caller has obtained a mutex prior to invoking this
17742 ** routine so there is never any chance that two or more
17743 ** threads can be in this routine at the same time.
17745 static void *memsys5MallocUnsafe(int nByte){
17746 int i; /* Index of a mem5.aPool[] slot */
17747 int iBin; /* Index into mem5.aiFreelist[] */
17748 int iFullSz; /* Size of allocation rounded up to power of 2 */
17749 int iLogsize; /* Log2 of iFullSz/POW2_MIN */
17751 /* nByte must be a positive */
17752 assert( nByte>0 );
17754 /* Keep track of the maximum allocation request. Even unfulfilled
17755 ** requests are counted */
17756 if( (u32)nByte>mem5.maxRequest ){
17757 mem5.maxRequest = nByte;
17760 /* Abort if the requested allocation size is larger than the largest
17761 ** power of two that we can represent using 32-bit signed integers.
17763 if( nByte > 0x40000000 ){
17764 return 0;
17767 /* Round nByte up to the next valid power of two */
17768 for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17770 /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17771 ** block. If not, then split a block of the next larger power of
17772 ** two in order to create a new free block of size iLogsize.
17774 for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17775 if( iBin>LOGMAX ){
17776 testcase( sqlite3GlobalConfig.xLog!=0 );
17777 sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17778 return 0;
17780 i = mem5.aiFreelist[iBin];
17781 memsys5Unlink(i, iBin);
17782 while( iBin>iLogsize ){
17783 int newSize;
17785 iBin--;
17786 newSize = 1 << iBin;
17787 mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17788 memsys5Link(i+newSize, iBin);
17790 mem5.aCtrl[i] = iLogsize;
17792 /* Update allocator performance statistics. */
17793 mem5.nAlloc++;
17794 mem5.totalAlloc += iFullSz;
17795 mem5.totalExcess += iFullSz - nByte;
17796 mem5.currentCount++;
17797 mem5.currentOut += iFullSz;
17798 if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17799 if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17801 /* Return a pointer to the allocated memory. */
17802 return (void*)&mem5.zPool[i*mem5.szAtom];
17806 ** Free an outstanding memory allocation.
17808 static void memsys5FreeUnsafe(void *pOld){
17809 u32 size, iLogsize;
17810 int iBlock;
17812 /* Set iBlock to the index of the block pointed to by pOld in
17813 ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17815 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
17817 /* Check that the pointer pOld points to a valid, non-free block. */
17818 assert( iBlock>=0 && iBlock<mem5.nBlock );
17819 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17820 assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17822 iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17823 size = 1<<iLogsize;
17824 assert( iBlock+size-1<(u32)mem5.nBlock );
17826 mem5.aCtrl[iBlock] |= CTRL_FREE;
17827 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17828 assert( mem5.currentCount>0 );
17829 assert( mem5.currentOut>=(size*mem5.szAtom) );
17830 mem5.currentCount--;
17831 mem5.currentOut -= size*mem5.szAtom;
17832 assert( mem5.currentOut>0 || mem5.currentCount==0 );
17833 assert( mem5.currentCount>0 || mem5.currentOut==0 );
17835 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17836 while( ALWAYS(iLogsize<LOGMAX) ){
17837 int iBuddy;
17838 if( (iBlock>>iLogsize) & 1 ){
17839 iBuddy = iBlock - size;
17840 }else{
17841 iBuddy = iBlock + size;
17843 assert( iBuddy>=0 );
17844 if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17845 if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17846 memsys5Unlink(iBuddy, iLogsize);
17847 iLogsize++;
17848 if( iBuddy<iBlock ){
17849 mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17850 mem5.aCtrl[iBlock] = 0;
17851 iBlock = iBuddy;
17852 }else{
17853 mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17854 mem5.aCtrl[iBuddy] = 0;
17856 size *= 2;
17858 memsys5Link(iBlock, iLogsize);
17862 ** Allocate nBytes of memory.
17864 static void *memsys5Malloc(int nBytes){
17865 sqlite3_int64 *p = 0;
17866 if( nBytes>0 ){
17867 memsys5Enter();
17868 p = memsys5MallocUnsafe(nBytes);
17869 memsys5Leave();
17871 return (void*)p;
17875 ** Free memory.
17877 ** The outer layer memory allocator prevents this routine from
17878 ** being called with pPrior==0.
17880 static void memsys5Free(void *pPrior){
17881 assert( pPrior!=0 );
17882 memsys5Enter();
17883 memsys5FreeUnsafe(pPrior);
17884 memsys5Leave();
17888 ** Change the size of an existing memory allocation.
17890 ** The outer layer memory allocator prevents this routine from
17891 ** being called with pPrior==0.
17893 ** nBytes is always a value obtained from a prior call to
17894 ** memsys5Round(). Hence nBytes is always a non-negative power
17895 ** of two. If nBytes==0 that means that an oversize allocation
17896 ** (an allocation larger than 0x40000000) was requested and this
17897 ** routine should return 0 without freeing pPrior.
17899 static void *memsys5Realloc(void *pPrior, int nBytes){
17900 int nOld;
17901 void *p;
17902 assert( pPrior!=0 );
17903 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
17904 assert( nBytes>=0 );
17905 if( nBytes==0 ){
17906 return 0;
17908 nOld = memsys5Size(pPrior);
17909 if( nBytes<=nOld ){
17910 return pPrior;
17912 memsys5Enter();
17913 p = memsys5MallocUnsafe(nBytes);
17914 if( p ){
17915 memcpy(p, pPrior, nOld);
17916 memsys5FreeUnsafe(pPrior);
17918 memsys5Leave();
17919 return p;
17923 ** Round up a request size to the next valid allocation size. If
17924 ** the allocation is too large to be handled by this allocation system,
17925 ** return 0.
17927 ** All allocations must be a power of two and must be expressed by a
17928 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
17929 ** or 1073741824 bytes.
17931 static int memsys5Roundup(int n){
17932 int iFullSz;
17933 if( n > 0x40000000 ) return 0;
17934 for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17935 return iFullSz;
17939 ** Return the ceiling of the logarithm base 2 of iValue.
17941 ** Examples: memsys5Log(1) -> 0
17942 ** memsys5Log(2) -> 1
17943 ** memsys5Log(4) -> 2
17944 ** memsys5Log(5) -> 3
17945 ** memsys5Log(8) -> 3
17946 ** memsys5Log(9) -> 4
17948 static int memsys5Log(int iValue){
17949 int iLog;
17950 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17951 return iLog;
17955 ** Initialize the memory allocator.
17957 ** This routine is not threadsafe. The caller must be holding a mutex
17958 ** to prevent multiple threads from entering at the same time.
17960 static int memsys5Init(void *NotUsed){
17961 int ii; /* Loop counter */
17962 int nByte; /* Number of bytes of memory available to this allocator */
17963 u8 *zByte; /* Memory usable by this allocator */
17964 int nMinLog; /* Log base 2 of minimum allocation size in bytes */
17965 int iOffset; /* An offset into mem5.aCtrl[] */
17967 UNUSED_PARAMETER(NotUsed);
17969 /* For the purposes of this routine, disable the mutex */
17970 mem5.mutex = 0;
17972 /* The size of a Mem5Link object must be a power of two. Verify that
17973 ** this is case.
17975 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17977 nByte = sqlite3GlobalConfig.nHeap;
17978 zByte = (u8*)sqlite3GlobalConfig.pHeap;
17979 assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
17981 /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17982 nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17983 mem5.szAtom = (1<<nMinLog);
17984 while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17985 mem5.szAtom = mem5.szAtom << 1;
17988 mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17989 mem5.zPool = zByte;
17990 mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17992 for(ii=0; ii<=LOGMAX; ii++){
17993 mem5.aiFreelist[ii] = -1;
17996 iOffset = 0;
17997 for(ii=LOGMAX; ii>=0; ii--){
17998 int nAlloc = (1<<ii);
17999 if( (iOffset+nAlloc)<=mem5.nBlock ){
18000 mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18001 memsys5Link(iOffset, ii);
18002 iOffset += nAlloc;
18004 assert((iOffset+nAlloc)>mem5.nBlock);
18007 /* If a mutex is required for normal operation, allocate one */
18008 if( sqlite3GlobalConfig.bMemstat==0 ){
18009 mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18012 return SQLITE_OK;
18016 ** Deinitialize this module.
18018 static void memsys5Shutdown(void *NotUsed){
18019 UNUSED_PARAMETER(NotUsed);
18020 mem5.mutex = 0;
18021 return;
18024 #ifdef SQLITE_TEST
18026 ** Open the file indicated and write a log of all unfreed memory
18027 ** allocations into that log.
18029 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
18030 FILE *out;
18031 int i, j, n;
18032 int nMinLog;
18034 if( zFilename==0 || zFilename[0]==0 ){
18035 out = stdout;
18036 }else{
18037 out = fopen(zFilename, "w");
18038 if( out==0 ){
18039 fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18040 zFilename);
18041 return;
18044 memsys5Enter();
18045 nMinLog = memsys5Log(mem5.szAtom);
18046 for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18047 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18048 fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18050 fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
18051 fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
18052 fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
18053 fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
18054 fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18055 fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
18056 fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
18057 fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
18058 memsys5Leave();
18059 if( out==stdout ){
18060 fflush(stdout);
18061 }else{
18062 fclose(out);
18065 #endif
18068 ** This routine is the only routine in this file with external
18069 ** linkage. It returns a pointer to a static sqlite3_mem_methods
18070 ** struct populated with the memsys5 methods.
18072 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
18073 static const sqlite3_mem_methods memsys5Methods = {
18074 memsys5Malloc,
18075 memsys5Free,
18076 memsys5Realloc,
18077 memsys5Size,
18078 memsys5Roundup,
18079 memsys5Init,
18080 memsys5Shutdown,
18083 return &memsys5Methods;
18086 #endif /* SQLITE_ENABLE_MEMSYS5 */
18088 /************** End of mem5.c ************************************************/
18089 /************** Begin file mutex.c *******************************************/
18091 ** 2007 August 14
18093 ** The author disclaims copyright to this source code. In place of
18094 ** a legal notice, here is a blessing:
18096 ** May you do good and not evil.
18097 ** May you find forgiveness for yourself and forgive others.
18098 ** May you share freely, never taking more than you give.
18100 *************************************************************************
18101 ** This file contains the C functions that implement mutexes.
18103 ** This file contains code that is common across all mutex implementations.
18106 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
18108 ** For debugging purposes, record when the mutex subsystem is initialized
18109 ** and uninitialized so that we can assert() if there is an attempt to
18110 ** allocate a mutex while the system is uninitialized.
18112 static SQLITE_WSD int mutexIsInit = 0;
18113 #endif /* SQLITE_DEBUG */
18116 #ifndef SQLITE_MUTEX_OMIT
18118 ** Initialize the mutex system.
18120 SQLITE_PRIVATE int sqlite3MutexInit(void){
18121 int rc = SQLITE_OK;
18122 if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
18123 /* If the xMutexAlloc method has not been set, then the user did not
18124 ** install a mutex implementation via sqlite3_config() prior to
18125 ** sqlite3_initialize() being called. This block copies pointers to
18126 ** the default implementation into the sqlite3GlobalConfig structure.
18128 sqlite3_mutex_methods const *pFrom;
18129 sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
18131 if( sqlite3GlobalConfig.bCoreMutex ){
18132 pFrom = sqlite3DefaultMutex();
18133 }else{
18134 pFrom = sqlite3NoopMutex();
18136 memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
18137 memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
18138 sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
18139 pTo->xMutexAlloc = pFrom->xMutexAlloc;
18141 rc = sqlite3GlobalConfig.mutex.xMutexInit();
18143 #ifdef SQLITE_DEBUG
18144 GLOBAL(int, mutexIsInit) = 1;
18145 #endif
18147 return rc;
18151 ** Shutdown the mutex system. This call frees resources allocated by
18152 ** sqlite3MutexInit().
18154 SQLITE_PRIVATE int sqlite3MutexEnd(void){
18155 int rc = SQLITE_OK;
18156 if( sqlite3GlobalConfig.mutex.xMutexEnd ){
18157 rc = sqlite3GlobalConfig.mutex.xMutexEnd();
18160 #ifdef SQLITE_DEBUG
18161 GLOBAL(int, mutexIsInit) = 0;
18162 #endif
18164 return rc;
18168 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
18170 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
18171 #ifndef SQLITE_OMIT_AUTOINIT
18172 if( sqlite3_initialize() ) return 0;
18173 #endif
18174 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18177 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
18178 if( !sqlite3GlobalConfig.bCoreMutex ){
18179 return 0;
18181 assert( GLOBAL(int, mutexIsInit) );
18182 return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
18186 ** Free a dynamic mutex.
18188 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
18189 if( p ){
18190 sqlite3GlobalConfig.mutex.xMutexFree(p);
18195 ** Obtain the mutex p. If some other thread already has the mutex, block
18196 ** until it can be obtained.
18198 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
18199 if( p ){
18200 sqlite3GlobalConfig.mutex.xMutexEnter(p);
18205 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
18206 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
18208 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
18209 int rc = SQLITE_OK;
18210 if( p ){
18211 return sqlite3GlobalConfig.mutex.xMutexTry(p);
18213 return rc;
18217 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
18218 ** entered by the same thread. The behavior is undefined if the mutex
18219 ** is not currently entered. If a NULL pointer is passed as an argument
18220 ** this function is a no-op.
18222 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
18223 if( p ){
18224 sqlite3GlobalConfig.mutex.xMutexLeave(p);
18228 #ifndef NDEBUG
18230 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18231 ** intended for use inside assert() statements.
18233 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
18234 return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
18236 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
18237 return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
18239 #endif
18241 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18243 /************** End of mutex.c ***********************************************/
18244 /************** Begin file mutex_noop.c **************************************/
18246 ** 2008 October 07
18248 ** The author disclaims copyright to this source code. In place of
18249 ** a legal notice, here is a blessing:
18251 ** May you do good and not evil.
18252 ** May you find forgiveness for yourself and forgive others.
18253 ** May you share freely, never taking more than you give.
18255 *************************************************************************
18256 ** This file contains the C functions that implement mutexes.
18258 ** This implementation in this file does not provide any mutual
18259 ** exclusion and is thus suitable for use only in applications
18260 ** that use SQLite in a single thread. The routines defined
18261 ** here are place-holders. Applications can substitute working
18262 ** mutex routines at start-time using the
18264 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
18266 ** interface.
18268 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
18269 ** that does error checking on mutexes to make sure they are being
18270 ** called correctly.
18273 #ifndef SQLITE_MUTEX_OMIT
18275 #ifndef SQLITE_DEBUG
18277 ** Stub routines for all mutex methods.
18279 ** This routines provide no mutual exclusion or error checking.
18281 static int noopMutexInit(void){ return SQLITE_OK; }
18282 static int noopMutexEnd(void){ return SQLITE_OK; }
18283 static sqlite3_mutex *noopMutexAlloc(int id){
18284 UNUSED_PARAMETER(id);
18285 return (sqlite3_mutex*)8;
18287 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18288 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18289 static int noopMutexTry(sqlite3_mutex *p){
18290 UNUSED_PARAMETER(p);
18291 return SQLITE_OK;
18293 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
18295 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18296 static const sqlite3_mutex_methods sMutex = {
18297 noopMutexInit,
18298 noopMutexEnd,
18299 noopMutexAlloc,
18300 noopMutexFree,
18301 noopMutexEnter,
18302 noopMutexTry,
18303 noopMutexLeave,
18309 return &sMutex;
18311 #endif /* !SQLITE_DEBUG */
18313 #ifdef SQLITE_DEBUG
18315 ** In this implementation, error checking is provided for testing
18316 ** and debugging purposes. The mutexes still do not provide any
18317 ** mutual exclusion.
18321 ** The mutex object
18323 typedef struct sqlite3_debug_mutex {
18324 int id; /* The mutex type */
18325 int cnt; /* Number of entries without a matching leave */
18326 } sqlite3_debug_mutex;
18329 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18330 ** intended for use inside assert() statements.
18332 static int debugMutexHeld(sqlite3_mutex *pX){
18333 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18334 return p==0 || p->cnt>0;
18336 static int debugMutexNotheld(sqlite3_mutex *pX){
18337 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18338 return p==0 || p->cnt==0;
18342 ** Initialize and deinitialize the mutex subsystem.
18344 static int debugMutexInit(void){ return SQLITE_OK; }
18345 static int debugMutexEnd(void){ return SQLITE_OK; }
18348 ** The sqlite3_mutex_alloc() routine allocates a new
18349 ** mutex and returns a pointer to it. If it returns NULL
18350 ** that means that a mutex could not be allocated.
18352 static sqlite3_mutex *debugMutexAlloc(int id){
18353 static sqlite3_debug_mutex aStatic[6];
18354 sqlite3_debug_mutex *pNew = 0;
18355 switch( id ){
18356 case SQLITE_MUTEX_FAST:
18357 case SQLITE_MUTEX_RECURSIVE: {
18358 pNew = sqlite3Malloc(sizeof(*pNew));
18359 if( pNew ){
18360 pNew->id = id;
18361 pNew->cnt = 0;
18363 break;
18365 default: {
18366 assert( id-2 >= 0 );
18367 assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
18368 pNew = &aStatic[id-2];
18369 pNew->id = id;
18370 break;
18373 return (sqlite3_mutex*)pNew;
18377 ** This routine deallocates a previously allocated mutex.
18379 static void debugMutexFree(sqlite3_mutex *pX){
18380 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18381 assert( p->cnt==0 );
18382 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18383 sqlite3_free(p);
18387 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18388 ** to enter a mutex. If another thread is already within the mutex,
18389 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18390 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18391 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18392 ** be entered multiple times by the same thread. In such cases the,
18393 ** mutex must be exited an equal number of times before another thread
18394 ** can enter. If the same thread tries to enter any other kind of mutex
18395 ** more than once, the behavior is undefined.
18397 static void debugMutexEnter(sqlite3_mutex *pX){
18398 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18399 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18400 p->cnt++;
18402 static int debugMutexTry(sqlite3_mutex *pX){
18403 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18404 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18405 p->cnt++;
18406 return SQLITE_OK;
18410 ** The sqlite3_mutex_leave() routine exits a mutex that was
18411 ** previously entered by the same thread. The behavior
18412 ** is undefined if the mutex is not currently entered or
18413 ** is not currently allocated. SQLite will never do either.
18415 static void debugMutexLeave(sqlite3_mutex *pX){
18416 sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18417 assert( debugMutexHeld(pX) );
18418 p->cnt--;
18419 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18422 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18423 static const sqlite3_mutex_methods sMutex = {
18424 debugMutexInit,
18425 debugMutexEnd,
18426 debugMutexAlloc,
18427 debugMutexFree,
18428 debugMutexEnter,
18429 debugMutexTry,
18430 debugMutexLeave,
18432 debugMutexHeld,
18433 debugMutexNotheld
18436 return &sMutex;
18438 #endif /* SQLITE_DEBUG */
18441 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18442 ** is used regardless of the run-time threadsafety setting.
18444 #ifdef SQLITE_MUTEX_NOOP
18445 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18446 return sqlite3NoopMutex();
18448 #endif /* defined(SQLITE_MUTEX_NOOP) */
18449 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18451 /************** End of mutex_noop.c ******************************************/
18452 /************** Begin file mutex_unix.c **************************************/
18454 ** 2007 August 28
18456 ** The author disclaims copyright to this source code. In place of
18457 ** a legal notice, here is a blessing:
18459 ** May you do good and not evil.
18460 ** May you find forgiveness for yourself and forgive others.
18461 ** May you share freely, never taking more than you give.
18463 *************************************************************************
18464 ** This file contains the C functions that implement mutexes for pthreads
18468 ** The code in this file is only used if we are compiling threadsafe
18469 ** under unix with pthreads.
18471 ** Note that this implementation requires a version of pthreads that
18472 ** supports recursive mutexes.
18474 #ifdef SQLITE_MUTEX_PTHREADS
18476 #include <pthread.h>
18479 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18480 ** are necessary under two condidtions: (1) Debug builds and (2) using
18481 ** home-grown mutexes. Encapsulate these conditions into a single #define.
18483 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18484 # define SQLITE_MUTEX_NREF 1
18485 #else
18486 # define SQLITE_MUTEX_NREF 0
18487 #endif
18490 ** Each recursive mutex is an instance of the following structure.
18492 struct sqlite3_mutex {
18493 pthread_mutex_t mutex; /* Mutex controlling the lock */
18494 #if SQLITE_MUTEX_NREF
18495 int id; /* Mutex type */
18496 volatile int nRef; /* Number of entrances */
18497 volatile pthread_t owner; /* Thread that is within this mutex */
18498 int trace; /* True to trace changes */
18499 #endif
18501 #if SQLITE_MUTEX_NREF
18502 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18503 #else
18504 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18505 #endif
18508 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18509 ** intended for use only inside assert() statements. On some platforms,
18510 ** there might be race conditions that can cause these routines to
18511 ** deliver incorrect results. In particular, if pthread_equal() is
18512 ** not an atomic operation, then these routines might delivery
18513 ** incorrect results. On most platforms, pthread_equal() is a
18514 ** comparison of two integers and is therefore atomic. But we are
18515 ** told that HPUX is not such a platform. If so, then these routines
18516 ** will not always work correctly on HPUX.
18518 ** On those platforms where pthread_equal() is not atomic, SQLite
18519 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18520 ** make sure no assert() statements are evaluated and hence these
18521 ** routines are never called.
18523 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18524 static int pthreadMutexHeld(sqlite3_mutex *p){
18525 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18527 static int pthreadMutexNotheld(sqlite3_mutex *p){
18528 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18530 #endif
18533 ** Initialize and deinitialize the mutex subsystem.
18535 static int pthreadMutexInit(void){ return SQLITE_OK; }
18536 static int pthreadMutexEnd(void){ return SQLITE_OK; }
18539 ** The sqlite3_mutex_alloc() routine allocates a new
18540 ** mutex and returns a pointer to it. If it returns NULL
18541 ** that means that a mutex could not be allocated. SQLite
18542 ** will unwind its stack and return an error. The argument
18543 ** to sqlite3_mutex_alloc() is one of these integer constants:
18545 ** <ul>
18546 ** <li> SQLITE_MUTEX_FAST
18547 ** <li> SQLITE_MUTEX_RECURSIVE
18548 ** <li> SQLITE_MUTEX_STATIC_MASTER
18549 ** <li> SQLITE_MUTEX_STATIC_MEM
18550 ** <li> SQLITE_MUTEX_STATIC_MEM2
18551 ** <li> SQLITE_MUTEX_STATIC_PRNG
18552 ** <li> SQLITE_MUTEX_STATIC_LRU
18553 ** <li> SQLITE_MUTEX_STATIC_PMEM
18554 ** </ul>
18556 ** The first two constants cause sqlite3_mutex_alloc() to create
18557 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18558 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18559 ** The mutex implementation does not need to make a distinction
18560 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18561 ** not want to. But SQLite will only request a recursive mutex in
18562 ** cases where it really needs one. If a faster non-recursive mutex
18563 ** implementation is available on the host platform, the mutex subsystem
18564 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18566 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18567 ** a pointer to a static preexisting mutex. Six static mutexes are
18568 ** used by the current version of SQLite. Future versions of SQLite
18569 ** may add additional static mutexes. Static mutexes are for internal
18570 ** use by SQLite only. Applications that use SQLite mutexes should
18571 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18572 ** SQLITE_MUTEX_RECURSIVE.
18574 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18575 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18576 ** returns a different mutex on every call. But for the static
18577 ** mutex types, the same mutex is returned on every call that has
18578 ** the same type number.
18580 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18581 static sqlite3_mutex staticMutexes[] = {
18582 SQLITE3_MUTEX_INITIALIZER,
18583 SQLITE3_MUTEX_INITIALIZER,
18584 SQLITE3_MUTEX_INITIALIZER,
18585 SQLITE3_MUTEX_INITIALIZER,
18586 SQLITE3_MUTEX_INITIALIZER,
18587 SQLITE3_MUTEX_INITIALIZER
18589 sqlite3_mutex *p;
18590 switch( iType ){
18591 case SQLITE_MUTEX_RECURSIVE: {
18592 p = sqlite3MallocZero( sizeof(*p) );
18593 if( p ){
18594 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18595 /* If recursive mutexes are not available, we will have to
18596 ** build our own. See below. */
18597 pthread_mutex_init(&p->mutex, 0);
18598 #else
18599 /* Use a recursive mutex if it is available */
18600 pthread_mutexattr_t recursiveAttr;
18601 pthread_mutexattr_init(&recursiveAttr);
18602 pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18603 pthread_mutex_init(&p->mutex, &recursiveAttr);
18604 pthread_mutexattr_destroy(&recursiveAttr);
18605 #endif
18606 #if SQLITE_MUTEX_NREF
18607 p->id = iType;
18608 #endif
18610 break;
18612 case SQLITE_MUTEX_FAST: {
18613 p = sqlite3MallocZero( sizeof(*p) );
18614 if( p ){
18615 #if SQLITE_MUTEX_NREF
18616 p->id = iType;
18617 #endif
18618 pthread_mutex_init(&p->mutex, 0);
18620 break;
18622 default: {
18623 assert( iType-2 >= 0 );
18624 assert( iType-2 < ArraySize(staticMutexes) );
18625 p = &staticMutexes[iType-2];
18626 #if SQLITE_MUTEX_NREF
18627 p->id = iType;
18628 #endif
18629 break;
18632 return p;
18637 ** This routine deallocates a previously
18638 ** allocated mutex. SQLite is careful to deallocate every
18639 ** mutex that it allocates.
18641 static void pthreadMutexFree(sqlite3_mutex *p){
18642 assert( p->nRef==0 );
18643 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18644 pthread_mutex_destroy(&p->mutex);
18645 sqlite3_free(p);
18649 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18650 ** to enter a mutex. If another thread is already within the mutex,
18651 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18652 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
18653 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
18654 ** be entered multiple times by the same thread. In such cases the,
18655 ** mutex must be exited an equal number of times before another thread
18656 ** can enter. If the same thread tries to enter any other kind of mutex
18657 ** more than once, the behavior is undefined.
18659 static void pthreadMutexEnter(sqlite3_mutex *p){
18660 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18662 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18663 /* If recursive mutexes are not available, then we have to grow
18664 ** our own. This implementation assumes that pthread_equal()
18665 ** is atomic - that it cannot be deceived into thinking self
18666 ** and p->owner are equal if p->owner changes between two values
18667 ** that are not equal to self while the comparison is taking place.
18668 ** This implementation also assumes a coherent cache - that
18669 ** separate processes cannot read different values from the same
18670 ** address at the same time. If either of these two conditions
18671 ** are not met, then the mutexes will fail and problems will result.
18674 pthread_t self = pthread_self();
18675 if( p->nRef>0 && pthread_equal(p->owner, self) ){
18676 p->nRef++;
18677 }else{
18678 pthread_mutex_lock(&p->mutex);
18679 assert( p->nRef==0 );
18680 p->owner = self;
18681 p->nRef = 1;
18684 #else
18685 /* Use the built-in recursive mutexes if they are available.
18687 pthread_mutex_lock(&p->mutex);
18688 #if SQLITE_MUTEX_NREF
18689 assert( p->nRef>0 || p->owner==0 );
18690 p->owner = pthread_self();
18691 p->nRef++;
18692 #endif
18693 #endif
18695 #ifdef SQLITE_DEBUG
18696 if( p->trace ){
18697 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18699 #endif
18701 static int pthreadMutexTry(sqlite3_mutex *p){
18702 int rc;
18703 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18705 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18706 /* If recursive mutexes are not available, then we have to grow
18707 ** our own. This implementation assumes that pthread_equal()
18708 ** is atomic - that it cannot be deceived into thinking self
18709 ** and p->owner are equal if p->owner changes between two values
18710 ** that are not equal to self while the comparison is taking place.
18711 ** This implementation also assumes a coherent cache - that
18712 ** separate processes cannot read different values from the same
18713 ** address at the same time. If either of these two conditions
18714 ** are not met, then the mutexes will fail and problems will result.
18717 pthread_t self = pthread_self();
18718 if( p->nRef>0 && pthread_equal(p->owner, self) ){
18719 p->nRef++;
18720 rc = SQLITE_OK;
18721 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18722 assert( p->nRef==0 );
18723 p->owner = self;
18724 p->nRef = 1;
18725 rc = SQLITE_OK;
18726 }else{
18727 rc = SQLITE_BUSY;
18730 #else
18731 /* Use the built-in recursive mutexes if they are available.
18733 if( pthread_mutex_trylock(&p->mutex)==0 ){
18734 #if SQLITE_MUTEX_NREF
18735 p->owner = pthread_self();
18736 p->nRef++;
18737 #endif
18738 rc = SQLITE_OK;
18739 }else{
18740 rc = SQLITE_BUSY;
18742 #endif
18744 #ifdef SQLITE_DEBUG
18745 if( rc==SQLITE_OK && p->trace ){
18746 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18748 #endif
18749 return rc;
18753 ** The sqlite3_mutex_leave() routine exits a mutex that was
18754 ** previously entered by the same thread. The behavior
18755 ** is undefined if the mutex is not currently entered or
18756 ** is not currently allocated. SQLite will never do either.
18758 static void pthreadMutexLeave(sqlite3_mutex *p){
18759 assert( pthreadMutexHeld(p) );
18760 #if SQLITE_MUTEX_NREF
18761 p->nRef--;
18762 if( p->nRef==0 ) p->owner = 0;
18763 #endif
18764 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18766 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18767 if( p->nRef==0 ){
18768 pthread_mutex_unlock(&p->mutex);
18770 #else
18771 pthread_mutex_unlock(&p->mutex);
18772 #endif
18774 #ifdef SQLITE_DEBUG
18775 if( p->trace ){
18776 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18778 #endif
18781 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18782 static const sqlite3_mutex_methods sMutex = {
18783 pthreadMutexInit,
18784 pthreadMutexEnd,
18785 pthreadMutexAlloc,
18786 pthreadMutexFree,
18787 pthreadMutexEnter,
18788 pthreadMutexTry,
18789 pthreadMutexLeave,
18790 #ifdef SQLITE_DEBUG
18791 pthreadMutexHeld,
18792 pthreadMutexNotheld
18793 #else
18796 #endif
18799 return &sMutex;
18802 #endif /* SQLITE_MUTEX_PTHREADS */
18804 /************** End of mutex_unix.c ******************************************/
18805 /************** Begin file mutex_w32.c ***************************************/
18807 ** 2007 August 14
18809 ** The author disclaims copyright to this source code. In place of
18810 ** a legal notice, here is a blessing:
18812 ** May you do good and not evil.
18813 ** May you find forgiveness for yourself and forgive others.
18814 ** May you share freely, never taking more than you give.
18816 *************************************************************************
18817 ** This file contains the C functions that implement mutexes for win32
18821 ** The code in this file is only used if we are compiling multithreaded
18822 ** on a win32 system.
18824 #ifdef SQLITE_MUTEX_W32
18827 ** Each recursive mutex is an instance of the following structure.
18829 struct sqlite3_mutex {
18830 CRITICAL_SECTION mutex; /* Mutex controlling the lock */
18831 int id; /* Mutex type */
18832 #ifdef SQLITE_DEBUG
18833 volatile int nRef; /* Number of enterances */
18834 volatile DWORD owner; /* Thread holding this mutex */
18835 int trace; /* True to trace changes */
18836 #endif
18838 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18839 #ifdef SQLITE_DEBUG
18840 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18841 #else
18842 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18843 #endif
18846 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18847 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
18849 ** Here is an interesting observation: Win95, Win98, and WinME lack
18850 ** the LockFileEx() API. But we can still statically link against that
18851 ** API as long as we don't call it win running Win95/98/ME. A call to
18852 ** this routine is used to determine if the host is Win95/98/ME or
18853 ** WinNT/2K/XP so that we will know whether or not we can safely call
18854 ** the LockFileEx() API.
18856 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18857 ** which is only available if your application was compiled with
18858 ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
18859 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
18860 ** this out as well.
18862 #if 0
18863 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18864 # define mutexIsNT() (1)
18865 #else
18866 static int mutexIsNT(void){
18867 static int osType = 0;
18868 if( osType==0 ){
18869 OSVERSIONINFO sInfo;
18870 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18871 GetVersionEx(&sInfo);
18872 osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18874 return osType==2;
18876 #endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
18877 #endif
18879 #ifdef SQLITE_DEBUG
18881 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18882 ** intended for use only inside assert() statements.
18884 static int winMutexHeld(sqlite3_mutex *p){
18885 return p->nRef!=0 && p->owner==GetCurrentThreadId();
18887 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18888 return p->nRef==0 || p->owner!=tid;
18890 static int winMutexNotheld(sqlite3_mutex *p){
18891 DWORD tid = GetCurrentThreadId();
18892 return winMutexNotheld2(p, tid);
18894 #endif
18898 ** Initialize and deinitialize the mutex subsystem.
18900 static sqlite3_mutex winMutex_staticMutexes[6] = {
18901 SQLITE3_MUTEX_INITIALIZER,
18902 SQLITE3_MUTEX_INITIALIZER,
18903 SQLITE3_MUTEX_INITIALIZER,
18904 SQLITE3_MUTEX_INITIALIZER,
18905 SQLITE3_MUTEX_INITIALIZER,
18906 SQLITE3_MUTEX_INITIALIZER
18908 static int winMutex_isInit = 0;
18909 /* As winMutexInit() and winMutexEnd() are called as part
18910 ** of the sqlite3_initialize and sqlite3_shutdown()
18911 ** processing, the "interlocked" magic is probably not
18912 ** strictly necessary.
18914 static LONG winMutex_lock = 0;
18916 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18918 static int winMutexInit(void){
18919 /* The first to increment to 1 does actual initialization */
18920 if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18921 int i;
18922 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18923 #if SQLITE_OS_WINRT
18924 InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18925 #else
18926 InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18927 #endif
18929 winMutex_isInit = 1;
18930 }else{
18931 /* Someone else is in the process of initing the static mutexes */
18932 while( !winMutex_isInit ){
18933 sqlite3_win32_sleep(1);
18936 return SQLITE_OK;
18939 static int winMutexEnd(void){
18940 /* The first to decrement to 0 does actual shutdown
18941 ** (which should be the last to shutdown.) */
18942 if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18943 if( winMutex_isInit==1 ){
18944 int i;
18945 for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18946 DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18948 winMutex_isInit = 0;
18951 return SQLITE_OK;
18955 ** The sqlite3_mutex_alloc() routine allocates a new
18956 ** mutex and returns a pointer to it. If it returns NULL
18957 ** that means that a mutex could not be allocated. SQLite
18958 ** will unwind its stack and return an error. The argument
18959 ** to sqlite3_mutex_alloc() is one of these integer constants:
18961 ** <ul>
18962 ** <li> SQLITE_MUTEX_FAST
18963 ** <li> SQLITE_MUTEX_RECURSIVE
18964 ** <li> SQLITE_MUTEX_STATIC_MASTER
18965 ** <li> SQLITE_MUTEX_STATIC_MEM
18966 ** <li> SQLITE_MUTEX_STATIC_MEM2
18967 ** <li> SQLITE_MUTEX_STATIC_PRNG
18968 ** <li> SQLITE_MUTEX_STATIC_LRU
18969 ** <li> SQLITE_MUTEX_STATIC_PMEM
18970 ** </ul>
18972 ** The first two constants cause sqlite3_mutex_alloc() to create
18973 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18974 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18975 ** The mutex implementation does not need to make a distinction
18976 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18977 ** not want to. But SQLite will only request a recursive mutex in
18978 ** cases where it really needs one. If a faster non-recursive mutex
18979 ** implementation is available on the host platform, the mutex subsystem
18980 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18982 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18983 ** a pointer to a static preexisting mutex. Six static mutexes are
18984 ** used by the current version of SQLite. Future versions of SQLite
18985 ** may add additional static mutexes. Static mutexes are for internal
18986 ** use by SQLite only. Applications that use SQLite mutexes should
18987 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18988 ** SQLITE_MUTEX_RECURSIVE.
18990 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18991 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18992 ** returns a different mutex on every call. But for the static
18993 ** mutex types, the same mutex is returned on every call that has
18994 ** the same type number.
18996 static sqlite3_mutex *winMutexAlloc(int iType){
18997 sqlite3_mutex *p;
18999 switch( iType ){
19000 case SQLITE_MUTEX_FAST:
19001 case SQLITE_MUTEX_RECURSIVE: {
19002 p = sqlite3MallocZero( sizeof(*p) );
19003 if( p ){
19004 #ifdef SQLITE_DEBUG
19005 p->id = iType;
19006 #endif
19007 #if SQLITE_OS_WINRT
19008 InitializeCriticalSectionEx(&p->mutex, 0, 0);
19009 #else
19010 InitializeCriticalSection(&p->mutex);
19011 #endif
19013 break;
19015 default: {
19016 assert( winMutex_isInit==1 );
19017 assert( iType-2 >= 0 );
19018 assert( iType-2 < ArraySize(winMutex_staticMutexes) );
19019 p = &winMutex_staticMutexes[iType-2];
19020 #ifdef SQLITE_DEBUG
19021 p->id = iType;
19022 #endif
19023 break;
19026 return p;
19031 ** This routine deallocates a previously
19032 ** allocated mutex. SQLite is careful to deallocate every
19033 ** mutex that it allocates.
19035 static void winMutexFree(sqlite3_mutex *p){
19036 assert( p );
19037 assert( p->nRef==0 && p->owner==0 );
19038 assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
19039 DeleteCriticalSection(&p->mutex);
19040 sqlite3_free(p);
19044 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19045 ** to enter a mutex. If another thread is already within the mutex,
19046 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19047 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
19048 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
19049 ** be entered multiple times by the same thread. In such cases the,
19050 ** mutex must be exited an equal number of times before another thread
19051 ** can enter. If the same thread tries to enter any other kind of mutex
19052 ** more than once, the behavior is undefined.
19054 static void winMutexEnter(sqlite3_mutex *p){
19055 #ifdef SQLITE_DEBUG
19056 DWORD tid = GetCurrentThreadId();
19057 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19058 #endif
19059 EnterCriticalSection(&p->mutex);
19060 #ifdef SQLITE_DEBUG
19061 assert( p->nRef>0 || p->owner==0 );
19062 p->owner = tid;
19063 p->nRef++;
19064 if( p->trace ){
19065 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19067 #endif
19069 static int winMutexTry(sqlite3_mutex *p){
19070 #ifndef NDEBUG
19071 DWORD tid = GetCurrentThreadId();
19072 #endif
19073 int rc = SQLITE_BUSY;
19074 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
19076 ** The sqlite3_mutex_try() routine is very rarely used, and when it
19077 ** is used it is merely an optimization. So it is OK for it to always
19078 ** fail.
19080 ** The TryEnterCriticalSection() interface is only available on WinNT.
19081 ** And some windows compilers complain if you try to use it without
19082 ** first doing some #defines that prevent SQLite from building on Win98.
19083 ** For that reason, we will omit this optimization for now. See
19084 ** ticket #2685.
19086 #if 0
19087 if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
19088 p->owner = tid;
19089 p->nRef++;
19090 rc = SQLITE_OK;
19092 #else
19093 UNUSED_PARAMETER(p);
19094 #endif
19095 #ifdef SQLITE_DEBUG
19096 if( rc==SQLITE_OK && p->trace ){
19097 printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19099 #endif
19100 return rc;
19104 ** The sqlite3_mutex_leave() routine exits a mutex that was
19105 ** previously entered by the same thread. The behavior
19106 ** is undefined if the mutex is not currently entered or
19107 ** is not currently allocated. SQLite will never do either.
19109 static void winMutexLeave(sqlite3_mutex *p){
19110 #ifndef NDEBUG
19111 DWORD tid = GetCurrentThreadId();
19112 assert( p->nRef>0 );
19113 assert( p->owner==tid );
19114 p->nRef--;
19115 if( p->nRef==0 ) p->owner = 0;
19116 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19117 #endif
19118 LeaveCriticalSection(&p->mutex);
19119 #ifdef SQLITE_DEBUG
19120 if( p->trace ){
19121 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19123 #endif
19126 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19127 static const sqlite3_mutex_methods sMutex = {
19128 winMutexInit,
19129 winMutexEnd,
19130 winMutexAlloc,
19131 winMutexFree,
19132 winMutexEnter,
19133 winMutexTry,
19134 winMutexLeave,
19135 #ifdef SQLITE_DEBUG
19136 winMutexHeld,
19137 winMutexNotheld
19138 #else
19141 #endif
19144 return &sMutex;
19146 #endif /* SQLITE_MUTEX_W32 */
19148 /************** End of mutex_w32.c *******************************************/
19149 /************** Begin file malloc.c ******************************************/
19151 ** 2001 September 15
19153 ** The author disclaims copyright to this source code. In place of
19154 ** a legal notice, here is a blessing:
19156 ** May you do good and not evil.
19157 ** May you find forgiveness for yourself and forgive others.
19158 ** May you share freely, never taking more than you give.
19160 *************************************************************************
19162 ** Memory allocation functions used throughout sqlite.
19164 /* #include <stdarg.h> */
19167 ** Attempt to release up to n bytes of non-essential memory currently
19168 ** held by SQLite. An example of non-essential memory is memory used to
19169 ** cache database pages that are not currently in use.
19171 SQLITE_API int sqlite3_release_memory(int n){
19172 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19173 return sqlite3PcacheReleaseMemory(n);
19174 #else
19175 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
19176 ** is a no-op returning zero if SQLite is not compiled with
19177 ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
19178 UNUSED_PARAMETER(n);
19179 return 0;
19180 #endif
19184 ** An instance of the following object records the location of
19185 ** each unused scratch buffer.
19187 typedef struct ScratchFreeslot {
19188 struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
19189 } ScratchFreeslot;
19192 ** State information local to the memory allocation subsystem.
19194 static SQLITE_WSD struct Mem0Global {
19195 sqlite3_mutex *mutex; /* Mutex to serialize access */
19198 ** The alarm callback and its arguments. The mem0.mutex lock will
19199 ** be held while the callback is running. Recursive calls into
19200 ** the memory subsystem are allowed, but no new callbacks will be
19201 ** issued.
19203 sqlite3_int64 alarmThreshold;
19204 void (*alarmCallback)(void*, sqlite3_int64,int);
19205 void *alarmArg;
19208 ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
19209 ** (so that a range test can be used to determine if an allocation
19210 ** being freed came from pScratch) and a pointer to the list of
19211 ** unused scratch allocations.
19213 void *pScratchEnd;
19214 ScratchFreeslot *pScratchFree;
19215 u32 nScratchFree;
19218 ** True if heap is nearly "full" where "full" is defined by the
19219 ** sqlite3_soft_heap_limit() setting.
19221 int nearlyFull;
19222 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
19224 #define mem0 GLOBAL(struct Mem0Global, mem0)
19227 ** This routine runs when the memory allocator sees that the
19228 ** total memory allocation is about to exceed the soft heap
19229 ** limit.
19231 static void softHeapLimitEnforcer(
19232 void *NotUsed,
19233 sqlite3_int64 NotUsed2,
19234 int allocSize
19236 UNUSED_PARAMETER2(NotUsed, NotUsed2);
19237 sqlite3_release_memory(allocSize);
19241 ** Change the alarm callback
19243 static int sqlite3MemoryAlarm(
19244 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
19245 void *pArg,
19246 sqlite3_int64 iThreshold
19248 int nUsed;
19249 sqlite3_mutex_enter(mem0.mutex);
19250 mem0.alarmCallback = xCallback;
19251 mem0.alarmArg = pArg;
19252 mem0.alarmThreshold = iThreshold;
19253 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19254 mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
19255 sqlite3_mutex_leave(mem0.mutex);
19256 return SQLITE_OK;
19259 #ifndef SQLITE_OMIT_DEPRECATED
19261 ** Deprecated external interface. Internal/core SQLite code
19262 ** should call sqlite3MemoryAlarm.
19264 SQLITE_API int sqlite3_memory_alarm(
19265 void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
19266 void *pArg,
19267 sqlite3_int64 iThreshold
19269 return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
19271 #endif
19274 ** Set the soft heap-size limit for the library. Passing a zero or
19275 ** negative value indicates no limit.
19277 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
19278 sqlite3_int64 priorLimit;
19279 sqlite3_int64 excess;
19280 #ifndef SQLITE_OMIT_AUTOINIT
19281 int rc = sqlite3_initialize();
19282 if( rc ) return -1;
19283 #endif
19284 sqlite3_mutex_enter(mem0.mutex);
19285 priorLimit = mem0.alarmThreshold;
19286 sqlite3_mutex_leave(mem0.mutex);
19287 if( n<0 ) return priorLimit;
19288 if( n>0 ){
19289 sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
19290 }else{
19291 sqlite3MemoryAlarm(0, 0, 0);
19293 excess = sqlite3_memory_used() - n;
19294 if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
19295 return priorLimit;
19297 SQLITE_API void sqlite3_soft_heap_limit(int n){
19298 if( n<0 ) n = 0;
19299 sqlite3_soft_heap_limit64(n);
19303 ** Initialize the memory allocation subsystem.
19305 SQLITE_PRIVATE int sqlite3MallocInit(void){
19306 if( sqlite3GlobalConfig.m.xMalloc==0 ){
19307 sqlite3MemSetDefault();
19309 memset(&mem0, 0, sizeof(mem0));
19310 if( sqlite3GlobalConfig.bCoreMutex ){
19311 mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
19313 if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
19314 && sqlite3GlobalConfig.nScratch>0 ){
19315 int i, n, sz;
19316 ScratchFreeslot *pSlot;
19317 sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
19318 sqlite3GlobalConfig.szScratch = sz;
19319 pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
19320 n = sqlite3GlobalConfig.nScratch;
19321 mem0.pScratchFree = pSlot;
19322 mem0.nScratchFree = n;
19323 for(i=0; i<n-1; i++){
19324 pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
19325 pSlot = pSlot->pNext;
19327 pSlot->pNext = 0;
19328 mem0.pScratchEnd = (void*)&pSlot[1];
19329 }else{
19330 mem0.pScratchEnd = 0;
19331 sqlite3GlobalConfig.pScratch = 0;
19332 sqlite3GlobalConfig.szScratch = 0;
19333 sqlite3GlobalConfig.nScratch = 0;
19335 if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
19336 || sqlite3GlobalConfig.nPage<1 ){
19337 sqlite3GlobalConfig.pPage = 0;
19338 sqlite3GlobalConfig.szPage = 0;
19339 sqlite3GlobalConfig.nPage = 0;
19341 return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
19345 ** Return true if the heap is currently under memory pressure - in other
19346 ** words if the amount of heap used is close to the limit set by
19347 ** sqlite3_soft_heap_limit().
19349 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
19350 return mem0.nearlyFull;
19354 ** Deinitialize the memory allocation subsystem.
19356 SQLITE_PRIVATE void sqlite3MallocEnd(void){
19357 if( sqlite3GlobalConfig.m.xShutdown ){
19358 sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
19360 memset(&mem0, 0, sizeof(mem0));
19364 ** Return the amount of memory currently checked out.
19366 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
19367 int n, mx;
19368 sqlite3_int64 res;
19369 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
19370 res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
19371 return res;
19375 ** Return the maximum amount of memory that has ever been
19376 ** checked out since either the beginning of this process
19377 ** or since the most recent reset.
19379 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
19380 int n, mx;
19381 sqlite3_int64 res;
19382 sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
19383 res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
19384 return res;
19388 ** Trigger the alarm
19390 static void sqlite3MallocAlarm(int nByte){
19391 void (*xCallback)(void*,sqlite3_int64,int);
19392 sqlite3_int64 nowUsed;
19393 void *pArg;
19394 if( mem0.alarmCallback==0 ) return;
19395 xCallback = mem0.alarmCallback;
19396 nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19397 pArg = mem0.alarmArg;
19398 mem0.alarmCallback = 0;
19399 sqlite3_mutex_leave(mem0.mutex);
19400 xCallback(pArg, nowUsed, nByte);
19401 sqlite3_mutex_enter(mem0.mutex);
19402 mem0.alarmCallback = xCallback;
19403 mem0.alarmArg = pArg;
19407 ** Do a memory allocation with statistics and alarms. Assume the
19408 ** lock is already held.
19410 static int mallocWithAlarm(int n, void **pp){
19411 int nFull;
19412 void *p;
19413 assert( sqlite3_mutex_held(mem0.mutex) );
19414 nFull = sqlite3GlobalConfig.m.xRoundup(n);
19415 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
19416 if( mem0.alarmCallback!=0 ){
19417 int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19418 if( nUsed >= mem0.alarmThreshold - nFull ){
19419 mem0.nearlyFull = 1;
19420 sqlite3MallocAlarm(nFull);
19421 }else{
19422 mem0.nearlyFull = 0;
19425 p = sqlite3GlobalConfig.m.xMalloc(nFull);
19426 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19427 if( p==0 && mem0.alarmCallback ){
19428 sqlite3MallocAlarm(nFull);
19429 p = sqlite3GlobalConfig.m.xMalloc(nFull);
19431 #endif
19432 if( p ){
19433 nFull = sqlite3MallocSize(p);
19434 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
19435 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
19437 *pp = p;
19438 return nFull;
19442 ** Allocate memory. This routine is like sqlite3_malloc() except that it
19443 ** assumes the memory subsystem has already been initialized.
19445 SQLITE_PRIVATE void *sqlite3Malloc(int n){
19446 void *p;
19447 if( n<=0 /* IMP: R-65312-04917 */
19448 || n>=0x7fffff00
19450 /* A memory allocation of a number of bytes which is near the maximum
19451 ** signed integer value might cause an integer overflow inside of the
19452 ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
19453 ** 255 bytes of overhead. SQLite itself will never use anything near
19454 ** this amount. The only way to reach the limit is with sqlite3_malloc() */
19455 p = 0;
19456 }else if( sqlite3GlobalConfig.bMemstat ){
19457 sqlite3_mutex_enter(mem0.mutex);
19458 mallocWithAlarm(n, &p);
19459 sqlite3_mutex_leave(mem0.mutex);
19460 }else{
19461 p = sqlite3GlobalConfig.m.xMalloc(n);
19463 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
19464 return p;
19468 ** This version of the memory allocation is for use by the application.
19469 ** First make sure the memory subsystem is initialized, then do the
19470 ** allocation.
19472 SQLITE_API void *sqlite3_malloc(int n){
19473 #ifndef SQLITE_OMIT_AUTOINIT
19474 if( sqlite3_initialize() ) return 0;
19475 #endif
19476 return sqlite3Malloc(n);
19480 ** Each thread may only have a single outstanding allocation from
19481 ** xScratchMalloc(). We verify this constraint in the single-threaded
19482 ** case by setting scratchAllocOut to 1 when an allocation
19483 ** is outstanding clearing it when the allocation is freed.
19485 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19486 static int scratchAllocOut = 0;
19487 #endif
19491 ** Allocate memory that is to be used and released right away.
19492 ** This routine is similar to alloca() in that it is not intended
19493 ** for situations where the memory might be held long-term. This
19494 ** routine is intended to get memory to old large transient data
19495 ** structures that would not normally fit on the stack of an
19496 ** embedded processor.
19498 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19499 void *p;
19500 assert( n>0 );
19502 sqlite3_mutex_enter(mem0.mutex);
19503 if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19504 p = mem0.pScratchFree;
19505 mem0.pScratchFree = mem0.pScratchFree->pNext;
19506 mem0.nScratchFree--;
19507 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19508 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19509 sqlite3_mutex_leave(mem0.mutex);
19510 }else{
19511 if( sqlite3GlobalConfig.bMemstat ){
19512 sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19513 n = mallocWithAlarm(n, &p);
19514 if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19515 sqlite3_mutex_leave(mem0.mutex);
19516 }else{
19517 sqlite3_mutex_leave(mem0.mutex);
19518 p = sqlite3GlobalConfig.m.xMalloc(n);
19520 sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19522 assert( sqlite3_mutex_notheld(mem0.mutex) );
19525 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19526 /* Verify that no more than two scratch allocations per thread
19527 ** are outstanding at one time. (This is only checked in the
19528 ** single-threaded case since checking in the multi-threaded case
19529 ** would be much more complicated.) */
19530 assert( scratchAllocOut<=1 );
19531 if( p ) scratchAllocOut++;
19532 #endif
19534 return p;
19536 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19537 if( p ){
19539 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19540 /* Verify that no more than two scratch allocation per thread
19541 ** is outstanding at one time. (This is only checked in the
19542 ** single-threaded case since checking in the multi-threaded case
19543 ** would be much more complicated.) */
19544 assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19545 scratchAllocOut--;
19546 #endif
19548 if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19549 /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19550 ScratchFreeslot *pSlot;
19551 pSlot = (ScratchFreeslot*)p;
19552 sqlite3_mutex_enter(mem0.mutex);
19553 pSlot->pNext = mem0.pScratchFree;
19554 mem0.pScratchFree = pSlot;
19555 mem0.nScratchFree++;
19556 assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19557 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19558 sqlite3_mutex_leave(mem0.mutex);
19559 }else{
19560 /* Release memory back to the heap */
19561 assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19562 assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19563 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19564 if( sqlite3GlobalConfig.bMemstat ){
19565 int iSize = sqlite3MallocSize(p);
19566 sqlite3_mutex_enter(mem0.mutex);
19567 sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19568 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19569 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19570 sqlite3GlobalConfig.m.xFree(p);
19571 sqlite3_mutex_leave(mem0.mutex);
19572 }else{
19573 sqlite3GlobalConfig.m.xFree(p);
19580 ** TRUE if p is a lookaside memory allocation from db
19582 #ifndef SQLITE_OMIT_LOOKASIDE
19583 static int isLookaside(sqlite3 *db, void *p){
19584 return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19586 #else
19587 #define isLookaside(A,B) 0
19588 #endif
19591 ** Return the size of a memory allocation previously obtained from
19592 ** sqlite3Malloc() or sqlite3_malloc().
19594 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19595 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19596 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19597 return sqlite3GlobalConfig.m.xSize(p);
19599 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19600 assert( db!=0 );
19601 assert( sqlite3_mutex_held(db->mutex) );
19602 if( isLookaside(db, p) ){
19603 return db->lookaside.sz;
19604 }else{
19605 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19606 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19607 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19608 return sqlite3GlobalConfig.m.xSize(p);
19613 ** Free memory previously obtained from sqlite3Malloc().
19615 SQLITE_API void sqlite3_free(void *p){
19616 if( p==0 ) return; /* IMP: R-49053-54554 */
19617 assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19618 assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19619 if( sqlite3GlobalConfig.bMemstat ){
19620 sqlite3_mutex_enter(mem0.mutex);
19621 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19622 sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19623 sqlite3GlobalConfig.m.xFree(p);
19624 sqlite3_mutex_leave(mem0.mutex);
19625 }else{
19626 sqlite3GlobalConfig.m.xFree(p);
19631 ** Free memory that might be associated with a particular database
19632 ** connection.
19634 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19635 assert( db==0 || sqlite3_mutex_held(db->mutex) );
19636 if( p==0 ) return;
19637 if( db ){
19638 if( db->pnBytesFreed ){
19639 *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19640 return;
19642 if( isLookaside(db, p) ){
19643 LookasideSlot *pBuf = (LookasideSlot*)p;
19644 #if SQLITE_DEBUG
19645 /* Trash all content in the buffer being freed */
19646 memset(p, 0xaa, db->lookaside.sz);
19647 #endif
19648 pBuf->pNext = db->lookaside.pFree;
19649 db->lookaside.pFree = pBuf;
19650 db->lookaside.nOut--;
19651 return;
19654 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19655 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19656 assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19657 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19658 sqlite3_free(p);
19662 ** Change the size of an existing memory allocation
19664 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19665 int nOld, nNew, nDiff;
19666 void *pNew;
19667 if( pOld==0 ){
19668 return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19670 if( nBytes<=0 ){
19671 sqlite3_free(pOld); /* IMP: R-31593-10574 */
19672 return 0;
19674 if( nBytes>=0x7fffff00 ){
19675 /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19676 return 0;
19678 nOld = sqlite3MallocSize(pOld);
19679 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19680 ** argument to xRealloc is always a value returned by a prior call to
19681 ** xRoundup. */
19682 nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19683 if( nOld==nNew ){
19684 pNew = pOld;
19685 }else if( sqlite3GlobalConfig.bMemstat ){
19686 sqlite3_mutex_enter(mem0.mutex);
19687 sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19688 nDiff = nNew - nOld;
19689 if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19690 mem0.alarmThreshold-nDiff ){
19691 sqlite3MallocAlarm(nDiff);
19693 assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19694 assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19695 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19696 if( pNew==0 && mem0.alarmCallback ){
19697 sqlite3MallocAlarm(nBytes);
19698 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19700 if( pNew ){
19701 nNew = sqlite3MallocSize(pNew);
19702 sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19704 sqlite3_mutex_leave(mem0.mutex);
19705 }else{
19706 pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19708 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19709 return pNew;
19713 ** The public interface to sqlite3Realloc. Make sure that the memory
19714 ** subsystem is initialized prior to invoking sqliteRealloc.
19716 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19717 #ifndef SQLITE_OMIT_AUTOINIT
19718 if( sqlite3_initialize() ) return 0;
19719 #endif
19720 return sqlite3Realloc(pOld, n);
19725 ** Allocate and zero memory.
19727 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19728 void *p = sqlite3Malloc(n);
19729 if( p ){
19730 memset(p, 0, n);
19732 return p;
19736 ** Allocate and zero memory. If the allocation fails, make
19737 ** the mallocFailed flag in the connection pointer.
19739 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19740 void *p = sqlite3DbMallocRaw(db, n);
19741 if( p ){
19742 memset(p, 0, n);
19744 return p;
19748 ** Allocate and zero memory. If the allocation fails, make
19749 ** the mallocFailed flag in the connection pointer.
19751 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19752 ** failure on the same database connection) then always return 0.
19753 ** Hence for a particular database connection, once malloc starts
19754 ** failing, it fails consistently until mallocFailed is reset.
19755 ** This is an important assumption. There are many places in the
19756 ** code that do things like this:
19758 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
19759 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
19760 ** if( b ) a[10] = 9;
19762 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19763 ** that all prior mallocs (ex: "a") worked too.
19765 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19766 void *p;
19767 assert( db==0 || sqlite3_mutex_held(db->mutex) );
19768 assert( db==0 || db->pnBytesFreed==0 );
19769 #ifndef SQLITE_OMIT_LOOKASIDE
19770 if( db ){
19771 LookasideSlot *pBuf;
19772 if( db->mallocFailed ){
19773 return 0;
19775 if( db->lookaside.bEnabled ){
19776 if( n>db->lookaside.sz ){
19777 db->lookaside.anStat[1]++;
19778 }else if( (pBuf = db->lookaside.pFree)==0 ){
19779 db->lookaside.anStat[2]++;
19780 }else{
19781 db->lookaside.pFree = pBuf->pNext;
19782 db->lookaside.nOut++;
19783 db->lookaside.anStat[0]++;
19784 if( db->lookaside.nOut>db->lookaside.mxOut ){
19785 db->lookaside.mxOut = db->lookaside.nOut;
19787 return (void*)pBuf;
19791 #else
19792 if( db && db->mallocFailed ){
19793 return 0;
19795 #endif
19796 p = sqlite3Malloc(n);
19797 if( !p && db ){
19798 db->mallocFailed = 1;
19800 sqlite3MemdebugSetType(p, MEMTYPE_DB |
19801 ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19802 return p;
19806 ** Resize the block of memory pointed to by p to n bytes. If the
19807 ** resize fails, set the mallocFailed flag in the connection object.
19809 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19810 void *pNew = 0;
19811 assert( db!=0 );
19812 assert( sqlite3_mutex_held(db->mutex) );
19813 if( db->mallocFailed==0 ){
19814 if( p==0 ){
19815 return sqlite3DbMallocRaw(db, n);
19817 if( isLookaside(db, p) ){
19818 if( n<=db->lookaside.sz ){
19819 return p;
19821 pNew = sqlite3DbMallocRaw(db, n);
19822 if( pNew ){
19823 memcpy(pNew, p, db->lookaside.sz);
19824 sqlite3DbFree(db, p);
19826 }else{
19827 assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19828 assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19829 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19830 pNew = sqlite3_realloc(p, n);
19831 if( !pNew ){
19832 sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19833 db->mallocFailed = 1;
19835 sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
19836 (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19839 return pNew;
19843 ** Attempt to reallocate p. If the reallocation fails, then free p
19844 ** and set the mallocFailed flag in the database connection.
19846 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19847 void *pNew;
19848 pNew = sqlite3DbRealloc(db, p, n);
19849 if( !pNew ){
19850 sqlite3DbFree(db, p);
19852 return pNew;
19856 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
19857 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19858 ** is because when memory debugging is turned on, these two functions are
19859 ** called via macros that record the current file and line number in the
19860 ** ThreadData structure.
19862 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19863 char *zNew;
19864 size_t n;
19865 if( z==0 ){
19866 return 0;
19868 n = sqlite3Strlen30(z) + 1;
19869 assert( (n&0x7fffffff)==n );
19870 zNew = sqlite3DbMallocRaw(db, (int)n);
19871 if( zNew ){
19872 memcpy(zNew, z, n);
19874 return zNew;
19876 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19877 char *zNew;
19878 if( z==0 ){
19879 return 0;
19881 assert( (n&0x7fffffff)==n );
19882 zNew = sqlite3DbMallocRaw(db, n+1);
19883 if( zNew ){
19884 memcpy(zNew, z, n);
19885 zNew[n] = 0;
19887 return zNew;
19891 ** Create a string from the zFromat argument and the va_list that follows.
19892 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19893 ** point to that string.
19895 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19896 va_list ap;
19897 char *z;
19899 va_start(ap, zFormat);
19900 z = sqlite3VMPrintf(db, zFormat, ap);
19901 va_end(ap);
19902 sqlite3DbFree(db, *pz);
19903 *pz = z;
19908 ** This function must be called before exiting any API function (i.e.
19909 ** returning control to the user) that has called sqlite3_malloc or
19910 ** sqlite3_realloc.
19912 ** The returned value is normally a copy of the second argument to this
19913 ** function. However, if a malloc() failure has occurred since the previous
19914 ** invocation SQLITE_NOMEM is returned instead.
19916 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19917 ** then the connection error-code (the value returned by sqlite3_errcode())
19918 ** is set to SQLITE_NOMEM.
19920 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19921 /* If the db handle is not NULL, then we must hold the connection handle
19922 ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
19923 ** is unsafe, as is the call to sqlite3Error().
19925 assert( !db || sqlite3_mutex_held(db->mutex) );
19926 if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19927 sqlite3Error(db, SQLITE_NOMEM, 0);
19928 db->mallocFailed = 0;
19929 rc = SQLITE_NOMEM;
19931 return rc & (db ? db->errMask : 0xff);
19934 /************** End of malloc.c **********************************************/
19935 /************** Begin file printf.c ******************************************/
19937 ** The "printf" code that follows dates from the 1980's. It is in
19938 ** the public domain. The original comments are included here for
19939 ** completeness. They are very out-of-date but might be useful as
19940 ** an historical reference. Most of the "enhancements" have been backed
19941 ** out so that the functionality is now the same as standard printf().
19943 **************************************************************************
19945 ** This file contains code for a set of "printf"-like routines. These
19946 ** routines format strings much like the printf() from the standard C
19947 ** library, though the implementation here has enhancements to support
19948 ** SQLlite.
19952 ** Conversion types fall into various categories as defined by the
19953 ** following enumeration.
19955 #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
19956 #define etFLOAT 2 /* Floating point. %f */
19957 #define etEXP 3 /* Exponentional notation. %e and %E */
19958 #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
19959 #define etSIZE 5 /* Return number of characters processed so far. %n */
19960 #define etSTRING 6 /* Strings. %s */
19961 #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
19962 #define etPERCENT 8 /* Percent symbol. %% */
19963 #define etCHARX 9 /* Characters. %c */
19964 /* The rest are extensions, not normally found in printf() */
19965 #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
19966 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19967 NULL pointers replaced by SQL NULL. %Q */
19968 #define etTOKEN 12 /* a pointer to a Token structure */
19969 #define etSRCLIST 13 /* a pointer to a SrcList */
19970 #define etPOINTER 14 /* The %p conversion */
19971 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19972 #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
19974 #define etINVALID 0 /* Any unrecognized conversion type */
19978 ** An "etByte" is an 8-bit unsigned value.
19980 typedef unsigned char etByte;
19983 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19984 ** by an instance of the following structure
19986 typedef struct et_info { /* Information about each format field */
19987 char fmttype; /* The format field code letter */
19988 etByte base; /* The base for radix conversion */
19989 etByte flags; /* One or more of FLAG_ constants below */
19990 etByte type; /* Conversion paradigm */
19991 etByte charset; /* Offset into aDigits[] of the digits string */
19992 etByte prefix; /* Offset into aPrefix[] of the prefix string */
19993 } et_info;
19996 ** Allowed values for et_info.flags
19998 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
19999 #define FLAG_INTERN 2 /* True if for internal use only */
20000 #define FLAG_STRING 4 /* Allow infinity precision */
20004 ** The following table is searched linearly, so it is good to put the
20005 ** most frequently used conversion types first.
20007 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
20008 static const char aPrefix[] = "-x0\000X0";
20009 static const et_info fmtinfo[] = {
20010 { 'd', 10, 1, etRADIX, 0, 0 },
20011 { 's', 0, 4, etSTRING, 0, 0 },
20012 { 'g', 0, 1, etGENERIC, 30, 0 },
20013 { 'z', 0, 4, etDYNSTRING, 0, 0 },
20014 { 'q', 0, 4, etSQLESCAPE, 0, 0 },
20015 { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
20016 { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
20017 { 'c', 0, 0, etCHARX, 0, 0 },
20018 { 'o', 8, 0, etRADIX, 0, 2 },
20019 { 'u', 10, 0, etRADIX, 0, 0 },
20020 { 'x', 16, 0, etRADIX, 16, 1 },
20021 { 'X', 16, 0, etRADIX, 0, 4 },
20022 #ifndef SQLITE_OMIT_FLOATING_POINT
20023 { 'f', 0, 1, etFLOAT, 0, 0 },
20024 { 'e', 0, 1, etEXP, 30, 0 },
20025 { 'E', 0, 1, etEXP, 14, 0 },
20026 { 'G', 0, 1, etGENERIC, 14, 0 },
20027 #endif
20028 { 'i', 10, 1, etRADIX, 0, 0 },
20029 { 'n', 0, 0, etSIZE, 0, 0 },
20030 { '%', 0, 0, etPERCENT, 0, 0 },
20031 { 'p', 16, 0, etPOINTER, 0, 1 },
20033 /* All the rest have the FLAG_INTERN bit set and are thus for internal
20034 ** use only */
20035 { 'T', 0, 2, etTOKEN, 0, 0 },
20036 { 'S', 0, 2, etSRCLIST, 0, 0 },
20037 { 'r', 10, 3, etORDINAL, 0, 0 },
20041 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
20042 ** conversions will work.
20044 #ifndef SQLITE_OMIT_FLOATING_POINT
20046 ** "*val" is a double such that 0.1 <= *val < 10.0
20047 ** Return the ascii code for the leading digit of *val, then
20048 ** multiply "*val" by 10.0 to renormalize.
20050 ** Example:
20051 ** input: *val = 3.14159
20052 ** output: *val = 1.4159 function return = '3'
20054 ** The counter *cnt is incremented each time. After counter exceeds
20055 ** 16 (the number of significant digits in a 64-bit float) '0' is
20056 ** always returned.
20058 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
20059 int digit;
20060 LONGDOUBLE_TYPE d;
20061 if( (*cnt)<=0 ) return '0';
20062 (*cnt)--;
20063 digit = (int)*val;
20064 d = digit;
20065 digit += '0';
20066 *val = (*val - d)*10.0;
20067 return (char)digit;
20069 #endif /* SQLITE_OMIT_FLOATING_POINT */
20072 ** Append N space characters to the given string buffer.
20074 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
20075 static const char zSpaces[] = " ";
20076 while( N>=(int)sizeof(zSpaces)-1 ){
20077 sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
20078 N -= sizeof(zSpaces)-1;
20080 if( N>0 ){
20081 sqlite3StrAccumAppend(pAccum, zSpaces, N);
20086 ** Set the StrAccum object to an error mode.
20088 static void setStrAccumError(StrAccum *p, u8 eError){
20089 p->accError = eError;
20090 p->nAlloc = 0;
20094 ** Extra argument values from a PrintfArguments object
20096 static sqlite3_int64 getIntArg(PrintfArguments *p){
20097 if( p->nArg<=p->nUsed ) return 0;
20098 return sqlite3_value_int64(p->apArg[p->nUsed++]);
20100 static double getDoubleArg(PrintfArguments *p){
20101 if( p->nArg<=p->nUsed ) return 0.0;
20102 return sqlite3_value_double(p->apArg[p->nUsed++]);
20104 static char *getTextArg(PrintfArguments *p){
20105 if( p->nArg<=p->nUsed ) return 0;
20106 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
20111 ** On machines with a small stack size, you can redefine the
20112 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
20114 #ifndef SQLITE_PRINT_BUF_SIZE
20115 # define SQLITE_PRINT_BUF_SIZE 70
20116 #endif
20117 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
20120 ** Render a string given by "fmt" into the StrAccum object.
20122 SQLITE_PRIVATE void sqlite3VXPrintf(
20123 StrAccum *pAccum, /* Accumulate results here */
20124 u32 bFlags, /* SQLITE_PRINTF_* flags */
20125 const char *fmt, /* Format string */
20126 va_list ap /* arguments */
20128 int c; /* Next character in the format string */
20129 char *bufpt; /* Pointer to the conversion buffer */
20130 int precision; /* Precision of the current field */
20131 int length; /* Length of the field */
20132 int idx; /* A general purpose loop counter */
20133 int width; /* Width of the current field */
20134 etByte flag_leftjustify; /* True if "-" flag is present */
20135 etByte flag_plussign; /* True if "+" flag is present */
20136 etByte flag_blanksign; /* True if " " flag is present */
20137 etByte flag_alternateform; /* True if "#" flag is present */
20138 etByte flag_altform2; /* True if "!" flag is present */
20139 etByte flag_zeropad; /* True if field width constant starts with zero */
20140 etByte flag_long; /* True if "l" flag is present */
20141 etByte flag_longlong; /* True if the "ll" flag is present */
20142 etByte done; /* Loop termination flag */
20143 etByte xtype = 0; /* Conversion paradigm */
20144 u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
20145 u8 useIntern; /* Ok to use internal conversions (ex: %T) */
20146 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
20147 sqlite_uint64 longvalue; /* Value for integer types */
20148 LONGDOUBLE_TYPE realvalue; /* Value for real types */
20149 const et_info *infop; /* Pointer to the appropriate info structure */
20150 char *zOut; /* Rendering buffer */
20151 int nOut; /* Size of the rendering buffer */
20152 char *zExtra; /* Malloced memory used by some conversion */
20153 #ifndef SQLITE_OMIT_FLOATING_POINT
20154 int exp, e2; /* exponent of real numbers */
20155 int nsd; /* Number of significant digits returned */
20156 double rounder; /* Used for rounding floating point values */
20157 etByte flag_dp; /* True if decimal point should be shown */
20158 etByte flag_rtz; /* True if trailing zeros should be removed */
20159 #endif
20160 PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
20161 char buf[etBUFSIZE]; /* Conversion buffer */
20163 bufpt = 0;
20164 if( bFlags ){
20165 if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
20166 pArgList = va_arg(ap, PrintfArguments*);
20168 useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
20169 }else{
20170 bArgList = useIntern = 0;
20172 for(; (c=(*fmt))!=0; ++fmt){
20173 if( c!='%' ){
20174 int amt;
20175 bufpt = (char *)fmt;
20176 amt = 1;
20177 while( (c=(*++fmt))!='%' && c!=0 ) amt++;
20178 sqlite3StrAccumAppend(pAccum, bufpt, amt);
20179 if( c==0 ) break;
20181 if( (c=(*++fmt))==0 ){
20182 sqlite3StrAccumAppend(pAccum, "%", 1);
20183 break;
20185 /* Find out what flags are present */
20186 flag_leftjustify = flag_plussign = flag_blanksign =
20187 flag_alternateform = flag_altform2 = flag_zeropad = 0;
20188 done = 0;
20190 switch( c ){
20191 case '-': flag_leftjustify = 1; break;
20192 case '+': flag_plussign = 1; break;
20193 case ' ': flag_blanksign = 1; break;
20194 case '#': flag_alternateform = 1; break;
20195 case '!': flag_altform2 = 1; break;
20196 case '0': flag_zeropad = 1; break;
20197 default: done = 1; break;
20199 }while( !done && (c=(*++fmt))!=0 );
20200 /* Get the field width */
20201 width = 0;
20202 if( c=='*' ){
20203 if( bArgList ){
20204 width = (int)getIntArg(pArgList);
20205 }else{
20206 width = va_arg(ap,int);
20208 if( width<0 ){
20209 flag_leftjustify = 1;
20210 width = -width;
20212 c = *++fmt;
20213 }else{
20214 while( c>='0' && c<='9' ){
20215 width = width*10 + c - '0';
20216 c = *++fmt;
20219 /* Get the precision */
20220 if( c=='.' ){
20221 precision = 0;
20222 c = *++fmt;
20223 if( c=='*' ){
20224 if( bArgList ){
20225 precision = (int)getIntArg(pArgList);
20226 }else{
20227 precision = va_arg(ap,int);
20229 if( precision<0 ) precision = -precision;
20230 c = *++fmt;
20231 }else{
20232 while( c>='0' && c<='9' ){
20233 precision = precision*10 + c - '0';
20234 c = *++fmt;
20237 }else{
20238 precision = -1;
20240 /* Get the conversion type modifier */
20241 if( c=='l' ){
20242 flag_long = 1;
20243 c = *++fmt;
20244 if( c=='l' ){
20245 flag_longlong = 1;
20246 c = *++fmt;
20247 }else{
20248 flag_longlong = 0;
20250 }else{
20251 flag_long = flag_longlong = 0;
20253 /* Fetch the info entry for the field */
20254 infop = &fmtinfo[0];
20255 xtype = etINVALID;
20256 for(idx=0; idx<ArraySize(fmtinfo); idx++){
20257 if( c==fmtinfo[idx].fmttype ){
20258 infop = &fmtinfo[idx];
20259 if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
20260 xtype = infop->type;
20261 }else{
20262 return;
20264 break;
20267 zExtra = 0;
20270 ** At this point, variables are initialized as follows:
20272 ** flag_alternateform TRUE if a '#' is present.
20273 ** flag_altform2 TRUE if a '!' is present.
20274 ** flag_plussign TRUE if a '+' is present.
20275 ** flag_leftjustify TRUE if a '-' is present or if the
20276 ** field width was negative.
20277 ** flag_zeropad TRUE if the width began with 0.
20278 ** flag_long TRUE if the letter 'l' (ell) prefixed
20279 ** the conversion character.
20280 ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
20281 ** the conversion character.
20282 ** flag_blanksign TRUE if a ' ' is present.
20283 ** width The specified field width. This is
20284 ** always non-negative. Zero is the default.
20285 ** precision The specified precision. The default
20286 ** is -1.
20287 ** xtype The class of the conversion.
20288 ** infop Pointer to the appropriate info struct.
20290 switch( xtype ){
20291 case etPOINTER:
20292 flag_longlong = sizeof(char*)==sizeof(i64);
20293 flag_long = sizeof(char*)==sizeof(long int);
20294 /* Fall through into the next case */
20295 case etORDINAL:
20296 case etRADIX:
20297 if( infop->flags & FLAG_SIGNED ){
20298 i64 v;
20299 if( bArgList ){
20300 v = getIntArg(pArgList);
20301 }else if( flag_longlong ){
20302 v = va_arg(ap,i64);
20303 }else if( flag_long ){
20304 v = va_arg(ap,long int);
20305 }else{
20306 v = va_arg(ap,int);
20308 if( v<0 ){
20309 if( v==SMALLEST_INT64 ){
20310 longvalue = ((u64)1)<<63;
20311 }else{
20312 longvalue = -v;
20314 prefix = '-';
20315 }else{
20316 longvalue = v;
20317 if( flag_plussign ) prefix = '+';
20318 else if( flag_blanksign ) prefix = ' ';
20319 else prefix = 0;
20321 }else{
20322 if( bArgList ){
20323 longvalue = (u64)getIntArg(pArgList);
20324 }else if( flag_longlong ){
20325 longvalue = va_arg(ap,u64);
20326 }else if( flag_long ){
20327 longvalue = va_arg(ap,unsigned long int);
20328 }else{
20329 longvalue = va_arg(ap,unsigned int);
20331 prefix = 0;
20333 if( longvalue==0 ) flag_alternateform = 0;
20334 if( flag_zeropad && precision<width-(prefix!=0) ){
20335 precision = width-(prefix!=0);
20337 if( precision<etBUFSIZE-10 ){
20338 nOut = etBUFSIZE;
20339 zOut = buf;
20340 }else{
20341 nOut = precision + 10;
20342 zOut = zExtra = sqlite3Malloc( nOut );
20343 if( zOut==0 ){
20344 setStrAccumError(pAccum, STRACCUM_NOMEM);
20345 return;
20348 bufpt = &zOut[nOut-1];
20349 if( xtype==etORDINAL ){
20350 static const char zOrd[] = "thstndrd";
20351 int x = (int)(longvalue % 10);
20352 if( x>=4 || (longvalue/10)%10==1 ){
20353 x = 0;
20355 *(--bufpt) = zOrd[x*2+1];
20356 *(--bufpt) = zOrd[x*2];
20359 register const char *cset; /* Use registers for speed */
20360 register int base;
20361 cset = &aDigits[infop->charset];
20362 base = infop->base;
20363 do{ /* Convert to ascii */
20364 *(--bufpt) = cset[longvalue%base];
20365 longvalue = longvalue/base;
20366 }while( longvalue>0 );
20368 length = (int)(&zOut[nOut-1]-bufpt);
20369 for(idx=precision-length; idx>0; idx--){
20370 *(--bufpt) = '0'; /* Zero pad */
20372 if( prefix ) *(--bufpt) = prefix; /* Add sign */
20373 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
20374 const char *pre;
20375 char x;
20376 pre = &aPrefix[infop->prefix];
20377 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
20379 length = (int)(&zOut[nOut-1]-bufpt);
20380 break;
20381 case etFLOAT:
20382 case etEXP:
20383 case etGENERIC:
20384 if( bArgList ){
20385 realvalue = getDoubleArg(pArgList);
20386 }else{
20387 realvalue = va_arg(ap,double);
20389 #ifdef SQLITE_OMIT_FLOATING_POINT
20390 length = 0;
20391 #else
20392 if( precision<0 ) precision = 6; /* Set default precision */
20393 if( realvalue<0.0 ){
20394 realvalue = -realvalue;
20395 prefix = '-';
20396 }else{
20397 if( flag_plussign ) prefix = '+';
20398 else if( flag_blanksign ) prefix = ' ';
20399 else prefix = 0;
20401 if( xtype==etGENERIC && precision>0 ) precision--;
20402 for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
20403 if( xtype==etFLOAT ) realvalue += rounder;
20404 /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
20405 exp = 0;
20406 if( sqlite3IsNaN((double)realvalue) ){
20407 bufpt = "NaN";
20408 length = 3;
20409 break;
20411 if( realvalue>0.0 ){
20412 LONGDOUBLE_TYPE scale = 1.0;
20413 #if __DBL_MAX_10_EXP__ > 100
20414 while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
20415 #endif
20416 #if __DBL_MAX_10_EXP__ > 64
20417 while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
20418 #endif
20419 while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
20420 while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
20421 realvalue /= scale;
20422 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
20423 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
20424 if( exp>350 ){
20425 if( prefix=='-' ){
20426 bufpt = "-Inf";
20427 }else if( prefix=='+' ){
20428 bufpt = "+Inf";
20429 }else{
20430 bufpt = "Inf";
20432 length = sqlite3Strlen30(bufpt);
20433 break;
20436 bufpt = buf;
20438 ** If the field type is etGENERIC, then convert to either etEXP
20439 ** or etFLOAT, as appropriate.
20441 if( xtype!=etFLOAT ){
20442 realvalue += rounder;
20443 if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
20445 if( xtype==etGENERIC ){
20446 flag_rtz = !flag_alternateform;
20447 if( exp<-4 || exp>precision ){
20448 xtype = etEXP;
20449 }else{
20450 precision = precision - exp;
20451 xtype = etFLOAT;
20453 }else{
20454 flag_rtz = flag_altform2;
20456 if( xtype==etEXP ){
20457 e2 = 0;
20458 }else{
20459 e2 = exp;
20461 if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
20462 bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
20463 if( bufpt==0 ){
20464 setStrAccumError(pAccum, STRACCUM_NOMEM);
20465 return;
20468 zOut = bufpt;
20469 nsd = 16 + flag_altform2*10;
20470 flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
20471 /* The sign in front of the number */
20472 if( prefix ){
20473 *(bufpt++) = prefix;
20475 /* Digits prior to the decimal point */
20476 if( e2<0 ){
20477 *(bufpt++) = '0';
20478 }else{
20479 for(; e2>=0; e2--){
20480 *(bufpt++) = et_getdigit(&realvalue,&nsd);
20483 /* The decimal point */
20484 if( flag_dp ){
20485 *(bufpt++) = '.';
20487 /* "0" digits after the decimal point but before the first
20488 ** significant digit of the number */
20489 for(e2++; e2<0; precision--, e2++){
20490 assert( precision>0 );
20491 *(bufpt++) = '0';
20493 /* Significant digits after the decimal point */
20494 while( (precision--)>0 ){
20495 *(bufpt++) = et_getdigit(&realvalue,&nsd);
20497 /* Remove trailing zeros and the "." if no digits follow the "." */
20498 if( flag_rtz && flag_dp ){
20499 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
20500 assert( bufpt>zOut );
20501 if( bufpt[-1]=='.' ){
20502 if( flag_altform2 ){
20503 *(bufpt++) = '0';
20504 }else{
20505 *(--bufpt) = 0;
20509 /* Add the "eNNN" suffix */
20510 if( xtype==etEXP ){
20511 *(bufpt++) = aDigits[infop->charset];
20512 if( exp<0 ){
20513 *(bufpt++) = '-'; exp = -exp;
20514 }else{
20515 *(bufpt++) = '+';
20517 if( exp>=100 ){
20518 *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
20519 exp %= 100;
20521 *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
20522 *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
20524 *bufpt = 0;
20526 /* The converted number is in buf[] and zero terminated. Output it.
20527 ** Note that the number is in the usual order, not reversed as with
20528 ** integer conversions. */
20529 length = (int)(bufpt-zOut);
20530 bufpt = zOut;
20532 /* Special case: Add leading zeros if the flag_zeropad flag is
20533 ** set and we are not left justified */
20534 if( flag_zeropad && !flag_leftjustify && length < width){
20535 int i;
20536 int nPad = width - length;
20537 for(i=width; i>=nPad; i--){
20538 bufpt[i] = bufpt[i-nPad];
20540 i = prefix!=0;
20541 while( nPad-- ) bufpt[i++] = '0';
20542 length = width;
20544 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20545 break;
20546 case etSIZE:
20547 if( !bArgList ){
20548 *(va_arg(ap,int*)) = pAccum->nChar;
20550 length = width = 0;
20551 break;
20552 case etPERCENT:
20553 buf[0] = '%';
20554 bufpt = buf;
20555 length = 1;
20556 break;
20557 case etCHARX:
20558 if( bArgList ){
20559 bufpt = getTextArg(pArgList);
20560 c = bufpt ? bufpt[0] : 0;
20561 }else{
20562 c = va_arg(ap,int);
20564 buf[0] = (char)c;
20565 if( precision>=0 ){
20566 for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20567 length = precision;
20568 }else{
20569 length =1;
20571 bufpt = buf;
20572 break;
20573 case etSTRING:
20574 case etDYNSTRING:
20575 if( bArgList ){
20576 bufpt = getTextArg(pArgList);
20577 }else{
20578 bufpt = va_arg(ap,char*);
20580 if( bufpt==0 ){
20581 bufpt = "";
20582 }else if( xtype==etDYNSTRING && !bArgList ){
20583 zExtra = bufpt;
20585 if( precision>=0 ){
20586 for(length=0; length<precision && bufpt[length]; length++){}
20587 }else{
20588 length = sqlite3Strlen30(bufpt);
20590 break;
20591 case etSQLESCAPE:
20592 case etSQLESCAPE2:
20593 case etSQLESCAPE3: {
20594 int i, j, k, n, isnull;
20595 int needQuote;
20596 char ch;
20597 char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
20598 char *escarg;
20600 if( bArgList ){
20601 escarg = getTextArg(pArgList);
20602 }else{
20603 escarg = va_arg(ap,char*);
20605 isnull = escarg==0;
20606 if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20607 k = precision;
20608 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20609 if( ch==q ) n++;
20611 needQuote = !isnull && xtype==etSQLESCAPE2;
20612 n += i + 1 + needQuote*2;
20613 if( n>etBUFSIZE ){
20614 bufpt = zExtra = sqlite3Malloc( n );
20615 if( bufpt==0 ){
20616 setStrAccumError(pAccum, STRACCUM_NOMEM);
20617 return;
20619 }else{
20620 bufpt = buf;
20622 j = 0;
20623 if( needQuote ) bufpt[j++] = q;
20624 k = i;
20625 for(i=0; i<k; i++){
20626 bufpt[j++] = ch = escarg[i];
20627 if( ch==q ) bufpt[j++] = ch;
20629 if( needQuote ) bufpt[j++] = q;
20630 bufpt[j] = 0;
20631 length = j;
20632 /* The precision in %q and %Q means how many input characters to
20633 ** consume, not the length of the output...
20634 ** if( precision>=0 && precision<length ) length = precision; */
20635 break;
20637 case etTOKEN: {
20638 Token *pToken = va_arg(ap, Token*);
20639 assert( bArgList==0 );
20640 if( pToken && pToken->n ){
20641 sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20643 length = width = 0;
20644 break;
20646 case etSRCLIST: {
20647 SrcList *pSrc = va_arg(ap, SrcList*);
20648 int k = va_arg(ap, int);
20649 struct SrcList_item *pItem = &pSrc->a[k];
20650 assert( bArgList==0 );
20651 assert( k>=0 && k<pSrc->nSrc );
20652 if( pItem->zDatabase ){
20653 sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
20654 sqlite3StrAccumAppend(pAccum, ".", 1);
20656 sqlite3StrAccumAppendAll(pAccum, pItem->zName);
20657 length = width = 0;
20658 break;
20660 default: {
20661 assert( xtype==etINVALID );
20662 return;
20664 }/* End switch over the format type */
20666 ** The text of the conversion is pointed to by "bufpt" and is
20667 ** "length" characters long. The field width is "width". Do
20668 ** the output.
20670 if( !flag_leftjustify ){
20671 register int nspace;
20672 nspace = width-length;
20673 if( nspace>0 ){
20674 sqlite3AppendSpace(pAccum, nspace);
20677 if( length>0 ){
20678 sqlite3StrAccumAppend(pAccum, bufpt, length);
20680 if( flag_leftjustify ){
20681 register int nspace;
20682 nspace = width-length;
20683 if( nspace>0 ){
20684 sqlite3AppendSpace(pAccum, nspace);
20687 if( zExtra ) sqlite3_free(zExtra);
20688 }/* End for loop over the format string */
20689 } /* End of function */
20692 ** Append N bytes of text from z to the StrAccum object.
20694 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20695 assert( z!=0 );
20696 assert( p->zText!=0 || p->nChar==0 || p->accError );
20697 assert( N>=0 );
20698 assert( p->accError==0 || p->nAlloc==0 );
20699 if( p->nChar+N >= p->nAlloc ){
20700 char *zNew;
20701 if( p->accError ){
20702 testcase(p->accError==STRACCUM_TOOBIG);
20703 testcase(p->accError==STRACCUM_NOMEM);
20704 return;
20706 if( !p->useMalloc ){
20707 N = p->nAlloc - p->nChar - 1;
20708 setStrAccumError(p, STRACCUM_TOOBIG);
20709 if( N<=0 ){
20710 return;
20712 }else{
20713 char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20714 i64 szNew = p->nChar;
20715 szNew += N + 1;
20716 if( szNew > p->mxAlloc ){
20717 sqlite3StrAccumReset(p);
20718 setStrAccumError(p, STRACCUM_TOOBIG);
20719 return;
20720 }else{
20721 p->nAlloc = (int)szNew;
20723 if( p->useMalloc==1 ){
20724 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20725 }else{
20726 zNew = sqlite3_realloc(zOld, p->nAlloc);
20728 if( zNew ){
20729 if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20730 p->zText = zNew;
20731 }else{
20732 sqlite3StrAccumReset(p);
20733 setStrAccumError(p, STRACCUM_NOMEM);
20734 return;
20738 assert( p->zText );
20739 memcpy(&p->zText[p->nChar], z, N);
20740 p->nChar += N;
20744 ** Append the complete text of zero-terminated string z[] to the p string.
20746 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
20747 sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
20752 ** Finish off a string by making sure it is zero-terminated.
20753 ** Return a pointer to the resulting string. Return a NULL
20754 ** pointer if any kind of error was encountered.
20756 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20757 if( p->zText ){
20758 p->zText[p->nChar] = 0;
20759 if( p->useMalloc && p->zText==p->zBase ){
20760 if( p->useMalloc==1 ){
20761 p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20762 }else{
20763 p->zText = sqlite3_malloc(p->nChar+1);
20765 if( p->zText ){
20766 memcpy(p->zText, p->zBase, p->nChar+1);
20767 }else{
20768 setStrAccumError(p, STRACCUM_NOMEM);
20772 return p->zText;
20776 ** Reset an StrAccum string. Reclaim all malloced memory.
20778 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20779 if( p->zText!=p->zBase ){
20780 if( p->useMalloc==1 ){
20781 sqlite3DbFree(p->db, p->zText);
20782 }else{
20783 sqlite3_free(p->zText);
20786 p->zText = 0;
20790 ** Initialize a string accumulator
20792 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20793 p->zText = p->zBase = zBase;
20794 p->db = 0;
20795 p->nChar = 0;
20796 p->nAlloc = n;
20797 p->mxAlloc = mx;
20798 p->useMalloc = 1;
20799 p->accError = 0;
20803 ** Print into memory obtained from sqliteMalloc(). Use the internal
20804 ** %-conversion extensions.
20806 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20807 char *z;
20808 char zBase[SQLITE_PRINT_BUF_SIZE];
20809 StrAccum acc;
20810 assert( db!=0 );
20811 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20812 db->aLimit[SQLITE_LIMIT_LENGTH]);
20813 acc.db = db;
20814 sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
20815 z = sqlite3StrAccumFinish(&acc);
20816 if( acc.accError==STRACCUM_NOMEM ){
20817 db->mallocFailed = 1;
20819 return z;
20823 ** Print into memory obtained from sqliteMalloc(). Use the internal
20824 ** %-conversion extensions.
20826 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20827 va_list ap;
20828 char *z;
20829 va_start(ap, zFormat);
20830 z = sqlite3VMPrintf(db, zFormat, ap);
20831 va_end(ap);
20832 return z;
20836 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20837 ** the string and before returnning. This routine is intended to be used
20838 ** to modify an existing string. For example:
20840 ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20843 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20844 va_list ap;
20845 char *z;
20846 va_start(ap, zFormat);
20847 z = sqlite3VMPrintf(db, zFormat, ap);
20848 va_end(ap);
20849 sqlite3DbFree(db, zStr);
20850 return z;
20854 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
20855 ** %-conversion extensions.
20857 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20858 char *z;
20859 char zBase[SQLITE_PRINT_BUF_SIZE];
20860 StrAccum acc;
20861 #ifndef SQLITE_OMIT_AUTOINIT
20862 if( sqlite3_initialize() ) return 0;
20863 #endif
20864 sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20865 acc.useMalloc = 2;
20866 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20867 z = sqlite3StrAccumFinish(&acc);
20868 return z;
20872 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
20873 ** %-conversion extensions.
20875 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20876 va_list ap;
20877 char *z;
20878 #ifndef SQLITE_OMIT_AUTOINIT
20879 if( sqlite3_initialize() ) return 0;
20880 #endif
20881 va_start(ap, zFormat);
20882 z = sqlite3_vmprintf(zFormat, ap);
20883 va_end(ap);
20884 return z;
20888 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20889 ** current locale settings. This is important for SQLite because we
20890 ** are not able to use a "," as the decimal point in place of "." as
20891 ** specified by some locales.
20893 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
20894 ** from the snprintf() standard. Unfortunately, it is too late to change
20895 ** this without breaking compatibility, so we just have to live with the
20896 ** mistake.
20898 ** sqlite3_vsnprintf() is the varargs version.
20900 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20901 StrAccum acc;
20902 if( n<=0 ) return zBuf;
20903 sqlite3StrAccumInit(&acc, zBuf, n, 0);
20904 acc.useMalloc = 0;
20905 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20906 return sqlite3StrAccumFinish(&acc);
20908 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20909 char *z;
20910 va_list ap;
20911 va_start(ap,zFormat);
20912 z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20913 va_end(ap);
20914 return z;
20918 ** This is the routine that actually formats the sqlite3_log() message.
20919 ** We house it in a separate routine from sqlite3_log() to avoid using
20920 ** stack space on small-stack systems when logging is disabled.
20922 ** sqlite3_log() must render into a static buffer. It cannot dynamically
20923 ** allocate memory because it might be called while the memory allocator
20924 ** mutex is held.
20926 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20927 StrAccum acc; /* String accumulator */
20928 char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
20930 sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20931 acc.useMalloc = 0;
20932 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20933 sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20934 sqlite3StrAccumFinish(&acc));
20938 ** Format and write a message to the log if logging is enabled.
20940 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20941 va_list ap; /* Vararg list */
20942 if( sqlite3GlobalConfig.xLog ){
20943 va_start(ap, zFormat);
20944 renderLogMsg(iErrCode, zFormat, ap);
20945 va_end(ap);
20949 #if defined(SQLITE_DEBUG)
20951 ** A version of printf() that understands %lld. Used for debugging.
20952 ** The printf() built into some versions of windows does not understand %lld
20953 ** and segfaults if you give it a long long int.
20955 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20956 va_list ap;
20957 StrAccum acc;
20958 char zBuf[500];
20959 sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20960 acc.useMalloc = 0;
20961 va_start(ap,zFormat);
20962 sqlite3VXPrintf(&acc, 0, zFormat, ap);
20963 va_end(ap);
20964 sqlite3StrAccumFinish(&acc);
20965 fprintf(stdout,"%s", zBuf);
20966 fflush(stdout);
20968 #endif
20971 ** variable-argument wrapper around sqlite3VXPrintf().
20973 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
20974 va_list ap;
20975 va_start(ap,zFormat);
20976 sqlite3VXPrintf(p, bFlags, zFormat, ap);
20977 va_end(ap);
20980 /************** End of printf.c **********************************************/
20981 /************** Begin file random.c ******************************************/
20983 ** 2001 September 15
20985 ** The author disclaims copyright to this source code. In place of
20986 ** a legal notice, here is a blessing:
20988 ** May you do good and not evil.
20989 ** May you find forgiveness for yourself and forgive others.
20990 ** May you share freely, never taking more than you give.
20992 *************************************************************************
20993 ** This file contains code to implement a pseudo-random number
20994 ** generator (PRNG) for SQLite.
20996 ** Random numbers are used by some of the database backends in order
20997 ** to generate random integer keys for tables or random filenames.
21001 /* All threads share a single random number generator.
21002 ** This structure is the current state of the generator.
21004 static SQLITE_WSD struct sqlite3PrngType {
21005 unsigned char isInit; /* True if initialized */
21006 unsigned char i, j; /* State variables */
21007 unsigned char s[256]; /* State variables */
21008 } sqlite3Prng;
21011 ** Return N random bytes.
21013 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
21014 unsigned char t;
21015 unsigned char *zBuf = pBuf;
21017 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
21018 ** state vector. If writable static data is unsupported on the target,
21019 ** we have to locate the state vector at run-time. In the more common
21020 ** case where writable static data is supported, wsdPrng can refer directly
21021 ** to the "sqlite3Prng" state vector declared above.
21023 #ifdef SQLITE_OMIT_WSD
21024 struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
21025 # define wsdPrng p[0]
21026 #else
21027 # define wsdPrng sqlite3Prng
21028 #endif
21030 #if SQLITE_THREADSAFE
21031 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
21032 sqlite3_mutex_enter(mutex);
21033 #endif
21035 if( N<=0 ){
21036 wsdPrng.isInit = 0;
21037 sqlite3_mutex_leave(mutex);
21038 return;
21041 /* Initialize the state of the random number generator once,
21042 ** the first time this routine is called. The seed value does
21043 ** not need to contain a lot of randomness since we are not
21044 ** trying to do secure encryption or anything like that...
21046 ** Nothing in this file or anywhere else in SQLite does any kind of
21047 ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
21048 ** number generator) not as an encryption device.
21050 if( !wsdPrng.isInit ){
21051 int i;
21052 char k[256];
21053 wsdPrng.j = 0;
21054 wsdPrng.i = 0;
21055 sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
21056 for(i=0; i<256; i++){
21057 wsdPrng.s[i] = (u8)i;
21059 for(i=0; i<256; i++){
21060 wsdPrng.j += wsdPrng.s[i] + k[i];
21061 t = wsdPrng.s[wsdPrng.j];
21062 wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
21063 wsdPrng.s[i] = t;
21065 wsdPrng.isInit = 1;
21068 assert( N>0 );
21070 wsdPrng.i++;
21071 t = wsdPrng.s[wsdPrng.i];
21072 wsdPrng.j += t;
21073 wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
21074 wsdPrng.s[wsdPrng.j] = t;
21075 t += wsdPrng.s[wsdPrng.i];
21076 *(zBuf++) = wsdPrng.s[t];
21077 }while( --N );
21078 sqlite3_mutex_leave(mutex);
21081 #ifndef SQLITE_OMIT_BUILTIN_TEST
21083 ** For testing purposes, we sometimes want to preserve the state of
21084 ** PRNG and restore the PRNG to its saved state at a later time, or
21085 ** to reset the PRNG to its initial state. These routines accomplish
21086 ** those tasks.
21088 ** The sqlite3_test_control() interface calls these routines to
21089 ** control the PRNG.
21091 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
21092 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
21093 memcpy(
21094 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
21095 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
21096 sizeof(sqlite3Prng)
21099 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
21100 memcpy(
21101 &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
21102 &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
21103 sizeof(sqlite3Prng)
21106 #endif /* SQLITE_OMIT_BUILTIN_TEST */
21108 /************** End of random.c **********************************************/
21109 /************** Begin file utf.c *********************************************/
21111 ** 2004 April 13
21113 ** The author disclaims copyright to this source code. In place of
21114 ** a legal notice, here is a blessing:
21116 ** May you do good and not evil.
21117 ** May you find forgiveness for yourself and forgive others.
21118 ** May you share freely, never taking more than you give.
21120 *************************************************************************
21121 ** This file contains routines used to translate between UTF-8,
21122 ** UTF-16, UTF-16BE, and UTF-16LE.
21124 ** Notes on UTF-8:
21126 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
21127 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
21128 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
21129 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
21130 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
21133 ** Notes on UTF-16: (with wwww+1==uuuuu)
21135 ** Word-0 Word-1 Value
21136 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
21137 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
21140 ** BOM or Byte Order Mark:
21141 ** 0xff 0xfe little-endian utf-16 follows
21142 ** 0xfe 0xff big-endian utf-16 follows
21145 /* #include <assert.h> */
21147 #ifndef SQLITE_AMALGAMATION
21149 ** The following constant value is used by the SQLITE_BIGENDIAN and
21150 ** SQLITE_LITTLEENDIAN macros.
21152 SQLITE_PRIVATE const int sqlite3one = 1;
21153 #endif /* SQLITE_AMALGAMATION */
21156 ** This lookup table is used to help decode the first byte of
21157 ** a multi-byte UTF8 character.
21159 static const unsigned char sqlite3Utf8Trans1[] = {
21160 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
21161 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
21162 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
21163 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
21164 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
21165 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
21166 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
21167 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
21171 #define WRITE_UTF8(zOut, c) { \
21172 if( c<0x00080 ){ \
21173 *zOut++ = (u8)(c&0xFF); \
21175 else if( c<0x00800 ){ \
21176 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
21177 *zOut++ = 0x80 + (u8)(c & 0x3F); \
21179 else if( c<0x10000 ){ \
21180 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
21181 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
21182 *zOut++ = 0x80 + (u8)(c & 0x3F); \
21183 }else{ \
21184 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
21185 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
21186 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
21187 *zOut++ = 0x80 + (u8)(c & 0x3F); \
21191 #define WRITE_UTF16LE(zOut, c) { \
21192 if( c<=0xFFFF ){ \
21193 *zOut++ = (u8)(c&0x00FF); \
21194 *zOut++ = (u8)((c>>8)&0x00FF); \
21195 }else{ \
21196 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
21197 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
21198 *zOut++ = (u8)(c&0x00FF); \
21199 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
21203 #define WRITE_UTF16BE(zOut, c) { \
21204 if( c<=0xFFFF ){ \
21205 *zOut++ = (u8)((c>>8)&0x00FF); \
21206 *zOut++ = (u8)(c&0x00FF); \
21207 }else{ \
21208 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
21209 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
21210 *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
21211 *zOut++ = (u8)(c&0x00FF); \
21215 #define READ_UTF16LE(zIn, TERM, c){ \
21216 c = (*zIn++); \
21217 c += ((*zIn++)<<8); \
21218 if( c>=0xD800 && c<0xE000 && TERM ){ \
21219 int c2 = (*zIn++); \
21220 c2 += ((*zIn++)<<8); \
21221 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
21225 #define READ_UTF16BE(zIn, TERM, c){ \
21226 c = ((*zIn++)<<8); \
21227 c += (*zIn++); \
21228 if( c>=0xD800 && c<0xE000 && TERM ){ \
21229 int c2 = ((*zIn++)<<8); \
21230 c2 += (*zIn++); \
21231 c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
21236 ** Translate a single UTF-8 character. Return the unicode value.
21238 ** During translation, assume that the byte that zTerm points
21239 ** is a 0x00.
21241 ** Write a pointer to the next unread byte back into *pzNext.
21243 ** Notes On Invalid UTF-8:
21245 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
21246 ** be encoded as a multi-byte character. Any multi-byte character that
21247 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
21249 ** * This routine never allows a UTF16 surrogate value to be encoded.
21250 ** If a multi-byte character attempts to encode a value between
21251 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
21253 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
21254 ** byte of a character are interpreted as single-byte characters
21255 ** and rendered as themselves even though they are technically
21256 ** invalid characters.
21258 ** * This routine accepts an infinite number of different UTF8 encodings
21259 ** for unicode values 0x80 and greater. It do not change over-length
21260 ** encodings to 0xfffd as some systems recommend.
21262 #define READ_UTF8(zIn, zTerm, c) \
21263 c = *(zIn++); \
21264 if( c>=0xc0 ){ \
21265 c = sqlite3Utf8Trans1[c-0xc0]; \
21266 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
21267 c = (c<<6) + (0x3f & *(zIn++)); \
21269 if( c<0x80 \
21270 || (c&0xFFFFF800)==0xD800 \
21271 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
21273 SQLITE_PRIVATE u32 sqlite3Utf8Read(
21274 const unsigned char **pz /* Pointer to string from which to read char */
21276 unsigned int c;
21278 /* Same as READ_UTF8() above but without the zTerm parameter.
21279 ** For this routine, we assume the UTF8 string is always zero-terminated.
21281 c = *((*pz)++);
21282 if( c>=0xc0 ){
21283 c = sqlite3Utf8Trans1[c-0xc0];
21284 while( (*(*pz) & 0xc0)==0x80 ){
21285 c = (c<<6) + (0x3f & *((*pz)++));
21287 if( c<0x80
21288 || (c&0xFFFFF800)==0xD800
21289 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
21291 return c;
21298 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
21299 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
21301 /* #define TRANSLATE_TRACE 1 */
21303 #ifndef SQLITE_OMIT_UTF16
21305 ** This routine transforms the internal text encoding used by pMem to
21306 ** desiredEnc. It is an error if the string is already of the desired
21307 ** encoding, or if *pMem does not contain a string value.
21309 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
21310 int len; /* Maximum length of output string in bytes */
21311 unsigned char *zOut; /* Output buffer */
21312 unsigned char *zIn; /* Input iterator */
21313 unsigned char *zTerm; /* End of input */
21314 unsigned char *z; /* Output iterator */
21315 unsigned int c;
21317 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
21318 assert( pMem->flags&MEM_Str );
21319 assert( pMem->enc!=desiredEnc );
21320 assert( pMem->enc!=0 );
21321 assert( pMem->n>=0 );
21323 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
21325 char zBuf[100];
21326 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21327 fprintf(stderr, "INPUT: %s\n", zBuf);
21329 #endif
21331 /* If the translation is between UTF-16 little and big endian, then
21332 ** all that is required is to swap the byte order. This case is handled
21333 ** differently from the others.
21335 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
21336 u8 temp;
21337 int rc;
21338 rc = sqlite3VdbeMemMakeWriteable(pMem);
21339 if( rc!=SQLITE_OK ){
21340 assert( rc==SQLITE_NOMEM );
21341 return SQLITE_NOMEM;
21343 zIn = (u8*)pMem->z;
21344 zTerm = &zIn[pMem->n&~1];
21345 while( zIn<zTerm ){
21346 temp = *zIn;
21347 *zIn = *(zIn+1);
21348 zIn++;
21349 *zIn++ = temp;
21351 pMem->enc = desiredEnc;
21352 goto translate_out;
21355 /* Set len to the maximum number of bytes required in the output buffer. */
21356 if( desiredEnc==SQLITE_UTF8 ){
21357 /* When converting from UTF-16, the maximum growth results from
21358 ** translating a 2-byte character to a 4-byte UTF-8 character.
21359 ** A single byte is required for the output string
21360 ** nul-terminator.
21362 pMem->n &= ~1;
21363 len = pMem->n * 2 + 1;
21364 }else{
21365 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
21366 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
21367 ** character. Two bytes are required in the output buffer for the
21368 ** nul-terminator.
21370 len = pMem->n * 2 + 2;
21373 /* Set zIn to point at the start of the input buffer and zTerm to point 1
21374 ** byte past the end.
21376 ** Variable zOut is set to point at the output buffer, space obtained
21377 ** from sqlite3_malloc().
21379 zIn = (u8*)pMem->z;
21380 zTerm = &zIn[pMem->n];
21381 zOut = sqlite3DbMallocRaw(pMem->db, len);
21382 if( !zOut ){
21383 return SQLITE_NOMEM;
21385 z = zOut;
21387 if( pMem->enc==SQLITE_UTF8 ){
21388 if( desiredEnc==SQLITE_UTF16LE ){
21389 /* UTF-8 -> UTF-16 Little-endian */
21390 while( zIn<zTerm ){
21391 READ_UTF8(zIn, zTerm, c);
21392 WRITE_UTF16LE(z, c);
21394 }else{
21395 assert( desiredEnc==SQLITE_UTF16BE );
21396 /* UTF-8 -> UTF-16 Big-endian */
21397 while( zIn<zTerm ){
21398 READ_UTF8(zIn, zTerm, c);
21399 WRITE_UTF16BE(z, c);
21402 pMem->n = (int)(z - zOut);
21403 *z++ = 0;
21404 }else{
21405 assert( desiredEnc==SQLITE_UTF8 );
21406 if( pMem->enc==SQLITE_UTF16LE ){
21407 /* UTF-16 Little-endian -> UTF-8 */
21408 while( zIn<zTerm ){
21409 READ_UTF16LE(zIn, zIn<zTerm, c);
21410 WRITE_UTF8(z, c);
21412 }else{
21413 /* UTF-16 Big-endian -> UTF-8 */
21414 while( zIn<zTerm ){
21415 READ_UTF16BE(zIn, zIn<zTerm, c);
21416 WRITE_UTF8(z, c);
21419 pMem->n = (int)(z - zOut);
21421 *z = 0;
21422 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
21424 sqlite3VdbeMemRelease(pMem);
21425 pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
21426 pMem->enc = desiredEnc;
21427 pMem->flags |= (MEM_Term|MEM_Dyn);
21428 pMem->z = (char*)zOut;
21429 pMem->zMalloc = pMem->z;
21431 translate_out:
21432 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
21434 char zBuf[100];
21435 sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21436 fprintf(stderr, "OUTPUT: %s\n", zBuf);
21438 #endif
21439 return SQLITE_OK;
21443 ** This routine checks for a byte-order mark at the beginning of the
21444 ** UTF-16 string stored in *pMem. If one is present, it is removed and
21445 ** the encoding of the Mem adjusted. This routine does not do any
21446 ** byte-swapping, it just sets Mem.enc appropriately.
21448 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
21449 ** changed by this function.
21451 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
21452 int rc = SQLITE_OK;
21453 u8 bom = 0;
21455 assert( pMem->n>=0 );
21456 if( pMem->n>1 ){
21457 u8 b1 = *(u8 *)pMem->z;
21458 u8 b2 = *(((u8 *)pMem->z) + 1);
21459 if( b1==0xFE && b2==0xFF ){
21460 bom = SQLITE_UTF16BE;
21462 if( b1==0xFF && b2==0xFE ){
21463 bom = SQLITE_UTF16LE;
21467 if( bom ){
21468 rc = sqlite3VdbeMemMakeWriteable(pMem);
21469 if( rc==SQLITE_OK ){
21470 pMem->n -= 2;
21471 memmove(pMem->z, &pMem->z[2], pMem->n);
21472 pMem->z[pMem->n] = '\0';
21473 pMem->z[pMem->n+1] = '\0';
21474 pMem->flags |= MEM_Term;
21475 pMem->enc = bom;
21478 return rc;
21480 #endif /* SQLITE_OMIT_UTF16 */
21483 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
21484 ** return the number of unicode characters in pZ up to (but not including)
21485 ** the first 0x00 byte. If nByte is not less than zero, return the
21486 ** number of unicode characters in the first nByte of pZ (or up to
21487 ** the first 0x00, whichever comes first).
21489 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
21490 int r = 0;
21491 const u8 *z = (const u8*)zIn;
21492 const u8 *zTerm;
21493 if( nByte>=0 ){
21494 zTerm = &z[nByte];
21495 }else{
21496 zTerm = (const u8*)(-1);
21498 assert( z<=zTerm );
21499 while( *z!=0 && z<zTerm ){
21500 SQLITE_SKIP_UTF8(z);
21501 r++;
21503 return r;
21506 /* This test function is not currently used by the automated test-suite.
21507 ** Hence it is only available in debug builds.
21509 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21511 ** Translate UTF-8 to UTF-8.
21513 ** This has the effect of making sure that the string is well-formed
21514 ** UTF-8. Miscoded characters are removed.
21516 ** The translation is done in-place and aborted if the output
21517 ** overruns the input.
21519 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21520 unsigned char *zOut = zIn;
21521 unsigned char *zStart = zIn;
21522 u32 c;
21524 while( zIn[0] && zOut<=zIn ){
21525 c = sqlite3Utf8Read((const u8**)&zIn);
21526 if( c!=0xfffd ){
21527 WRITE_UTF8(zOut, c);
21530 *zOut = 0;
21531 return (int)(zOut - zStart);
21533 #endif
21535 #ifndef SQLITE_OMIT_UTF16
21537 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21538 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21539 ** be freed by the calling function.
21541 ** NULL is returned if there is an allocation error.
21543 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21544 Mem m;
21545 memset(&m, 0, sizeof(m));
21546 m.db = db;
21547 sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21548 sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21549 if( db->mallocFailed ){
21550 sqlite3VdbeMemRelease(&m);
21551 m.z = 0;
21553 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21554 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21555 assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
21556 assert( m.z || db->mallocFailed );
21557 return m.z;
21561 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21562 ** Return the number of bytes in the first nChar unicode characters
21563 ** in pZ. nChar must be non-negative.
21565 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21566 int c;
21567 unsigned char const *z = zIn;
21568 int n = 0;
21570 if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21571 while( n<nChar ){
21572 READ_UTF16BE(z, 1, c);
21573 n++;
21575 }else{
21576 while( n<nChar ){
21577 READ_UTF16LE(z, 1, c);
21578 n++;
21581 return (int)(z-(unsigned char const *)zIn);
21584 #if defined(SQLITE_TEST)
21586 ** This routine is called from the TCL test function "translate_selftest".
21587 ** It checks that the primitives for serializing and deserializing
21588 ** characters in each encoding are inverses of each other.
21590 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21591 unsigned int i, t;
21592 unsigned char zBuf[20];
21593 unsigned char *z;
21594 int n;
21595 unsigned int c;
21597 for(i=0; i<0x00110000; i++){
21598 z = zBuf;
21599 WRITE_UTF8(z, i);
21600 n = (int)(z-zBuf);
21601 assert( n>0 && n<=4 );
21602 z[0] = 0;
21603 z = zBuf;
21604 c = sqlite3Utf8Read((const u8**)&z);
21605 t = i;
21606 if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21607 if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21608 assert( c==t );
21609 assert( (z-zBuf)==n );
21611 for(i=0; i<0x00110000; i++){
21612 if( i>=0xD800 && i<0xE000 ) continue;
21613 z = zBuf;
21614 WRITE_UTF16LE(z, i);
21615 n = (int)(z-zBuf);
21616 assert( n>0 && n<=4 );
21617 z[0] = 0;
21618 z = zBuf;
21619 READ_UTF16LE(z, 1, c);
21620 assert( c==i );
21621 assert( (z-zBuf)==n );
21623 for(i=0; i<0x00110000; i++){
21624 if( i>=0xD800 && i<0xE000 ) continue;
21625 z = zBuf;
21626 WRITE_UTF16BE(z, i);
21627 n = (int)(z-zBuf);
21628 assert( n>0 && n<=4 );
21629 z[0] = 0;
21630 z = zBuf;
21631 READ_UTF16BE(z, 1, c);
21632 assert( c==i );
21633 assert( (z-zBuf)==n );
21636 #endif /* SQLITE_TEST */
21637 #endif /* SQLITE_OMIT_UTF16 */
21639 /************** End of utf.c *************************************************/
21640 /************** Begin file util.c ********************************************/
21642 ** 2001 September 15
21644 ** The author disclaims copyright to this source code. In place of
21645 ** a legal notice, here is a blessing:
21647 ** May you do good and not evil.
21648 ** May you find forgiveness for yourself and forgive others.
21649 ** May you share freely, never taking more than you give.
21651 *************************************************************************
21652 ** Utility functions used throughout sqlite.
21654 ** This file contains functions for allocating memory, comparing
21655 ** strings, and stuff like that.
21658 /* #include <stdarg.h> */
21659 #ifdef SQLITE_HAVE_ISNAN
21660 # include <math.h>
21661 #endif
21664 ** Routine needed to support the testcase() macro.
21666 #ifdef SQLITE_COVERAGE_TEST
21667 SQLITE_PRIVATE void sqlite3Coverage(int x){
21668 static unsigned dummy = 0;
21669 dummy += (unsigned)x;
21671 #endif
21673 #ifndef SQLITE_OMIT_FLOATING_POINT
21675 ** Return true if the floating point value is Not a Number (NaN).
21677 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21678 ** Otherwise, we have our own implementation that works on most systems.
21680 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21681 int rc; /* The value return */
21682 #if !defined(SQLITE_HAVE_ISNAN)
21684 ** Systems that support the isnan() library function should probably
21685 ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
21686 ** found that many systems do not have a working isnan() function so
21687 ** this implementation is provided as an alternative.
21689 ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21690 ** On the other hand, the use of -ffast-math comes with the following
21691 ** warning:
21693 ** This option [-ffast-math] should never be turned on by any
21694 ** -O option since it can result in incorrect output for programs
21695 ** which depend on an exact implementation of IEEE or ISO
21696 ** rules/specifications for math functions.
21698 ** Under MSVC, this NaN test may fail if compiled with a floating-
21699 ** point precision mode other than /fp:precise. From the MSDN
21700 ** documentation:
21702 ** The compiler [with /fp:precise] will properly handle comparisons
21703 ** involving NaN. For example, x != x evaluates to true if x is NaN
21704 ** ...
21706 #ifdef __FAST_MATH__
21707 # error SQLite will not work correctly with the -ffast-math option of GCC.
21708 #endif
21709 volatile double y = x;
21710 volatile double z = y;
21711 rc = (y!=z);
21712 #else /* if defined(SQLITE_HAVE_ISNAN) */
21713 rc = isnan(x);
21714 #endif /* SQLITE_HAVE_ISNAN */
21715 testcase( rc );
21716 return rc;
21718 #endif /* SQLITE_OMIT_FLOATING_POINT */
21721 ** Compute a string length that is limited to what can be stored in
21722 ** lower 30 bits of a 32-bit signed integer.
21724 ** The value returned will never be negative. Nor will it ever be greater
21725 ** than the actual length of the string. For very long strings (greater
21726 ** than 1GiB) the value returned might be less than the true string length.
21728 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21729 const char *z2 = z;
21730 if( z==0 ) return 0;
21731 while( *z2 ){ z2++; }
21732 return 0x3fffffff & (int)(z2 - z);
21736 ** Set the most recent error code and error string for the sqlite
21737 ** handle "db". The error code is set to "err_code".
21739 ** If it is not NULL, string zFormat specifies the format of the
21740 ** error string in the style of the printf functions: The following
21741 ** format characters are allowed:
21743 ** %s Insert a string
21744 ** %z A string that should be freed after use
21745 ** %d Insert an integer
21746 ** %T Insert a token
21747 ** %S Insert the first element of a SrcList
21749 ** zFormat and any string tokens that follow it are assumed to be
21750 ** encoded in UTF-8.
21752 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21753 ** should be called with err_code set to SQLITE_OK and zFormat set
21754 ** to NULL.
21756 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21757 assert( db!=0 );
21758 db->errCode = err_code;
21759 if( zFormat && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21760 char *z;
21761 va_list ap;
21762 va_start(ap, zFormat);
21763 z = sqlite3VMPrintf(db, zFormat, ap);
21764 va_end(ap);
21765 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21766 }else if( db->pErr ){
21767 sqlite3ValueSetNull(db->pErr);
21772 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21773 ** The following formatting characters are allowed:
21775 ** %s Insert a string
21776 ** %z A string that should be freed after use
21777 ** %d Insert an integer
21778 ** %T Insert a token
21779 ** %S Insert the first element of a SrcList
21781 ** This function should be used to report any error that occurs whilst
21782 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21783 ** last thing the sqlite3_prepare() function does is copy the error
21784 ** stored by this function into the database handle using sqlite3Error().
21785 ** Function sqlite3Error() should be used during statement execution
21786 ** (sqlite3_step() etc.).
21788 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21789 char *zMsg;
21790 va_list ap;
21791 sqlite3 *db = pParse->db;
21792 va_start(ap, zFormat);
21793 zMsg = sqlite3VMPrintf(db, zFormat, ap);
21794 va_end(ap);
21795 if( db->suppressErr ){
21796 sqlite3DbFree(db, zMsg);
21797 }else{
21798 pParse->nErr++;
21799 sqlite3DbFree(db, pParse->zErrMsg);
21800 pParse->zErrMsg = zMsg;
21801 pParse->rc = SQLITE_ERROR;
21806 ** Convert an SQL-style quoted string into a normal string by removing
21807 ** the quote characters. The conversion is done in-place. If the
21808 ** input does not begin with a quote character, then this routine
21809 ** is a no-op.
21811 ** The input string must be zero-terminated. A new zero-terminator
21812 ** is added to the dequoted string.
21814 ** The return value is -1 if no dequoting occurs or the length of the
21815 ** dequoted string, exclusive of the zero terminator, if dequoting does
21816 ** occur.
21818 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21819 ** brackets from around identifers. For example: "[a-b-c]" becomes
21820 ** "a-b-c".
21822 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21823 char quote;
21824 int i, j;
21825 if( z==0 ) return -1;
21826 quote = z[0];
21827 switch( quote ){
21828 case '\'': break;
21829 case '"': break;
21830 case '`': break; /* For MySQL compatibility */
21831 case '[': quote = ']'; break; /* For MS SqlServer compatibility */
21832 default: return -1;
21834 for(i=1, j=0;; i++){
21835 assert( z[i] );
21836 if( z[i]==quote ){
21837 if( z[i+1]==quote ){
21838 z[j++] = quote;
21839 i++;
21840 }else{
21841 break;
21843 }else{
21844 z[j++] = z[i];
21847 z[j] = 0;
21848 return j;
21851 /* Convenient short-hand */
21852 #define UpperToLower sqlite3UpperToLower
21855 ** Some systems have stricmp(). Others have strcasecmp(). Because
21856 ** there is no consistency, we will define our own.
21858 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21859 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21860 ** the contents of two buffers containing UTF-8 strings in a
21861 ** case-independent fashion, using the same definition of "case
21862 ** independence" that SQLite uses internally when comparing identifiers.
21864 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21865 register unsigned char *a, *b;
21866 a = (unsigned char *)zLeft;
21867 b = (unsigned char *)zRight;
21868 while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21869 return UpperToLower[*a] - UpperToLower[*b];
21871 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21872 register unsigned char *a, *b;
21873 a = (unsigned char *)zLeft;
21874 b = (unsigned char *)zRight;
21875 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21876 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21880 ** The string z[] is an text representation of a real number.
21881 ** Convert this string to a double and write it into *pResult.
21883 ** The string z[] is length bytes in length (bytes, not characters) and
21884 ** uses the encoding enc. The string is not necessarily zero-terminated.
21886 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21887 ** if the string is empty or contains extraneous text. Valid numbers
21888 ** are in one of these formats:
21890 ** [+-]digits[E[+-]digits]
21891 ** [+-]digits.[digits][E[+-]digits]
21892 ** [+-].digits[E[+-]digits]
21894 ** Leading and trailing whitespace is ignored for the purpose of determining
21895 ** validity.
21897 ** If some prefix of the input string is a valid number, this routine
21898 ** returns FALSE but it still converts the prefix and writes the result
21899 ** into *pResult.
21901 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21902 #ifndef SQLITE_OMIT_FLOATING_POINT
21903 int incr;
21904 const char *zEnd = z + length;
21905 /* sign * significand * (10 ^ (esign * exponent)) */
21906 int sign = 1; /* sign of significand */
21907 i64 s = 0; /* significand */
21908 int d = 0; /* adjust exponent for shifting decimal point */
21909 int esign = 1; /* sign of exponent */
21910 int e = 0; /* exponent */
21911 int eValid = 1; /* True exponent is either not used or is well-formed */
21912 double result;
21913 int nDigits = 0;
21914 int nonNum = 0;
21916 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21917 *pResult = 0.0; /* Default return value, in case of an error */
21919 if( enc==SQLITE_UTF8 ){
21920 incr = 1;
21921 }else{
21922 int i;
21923 incr = 2;
21924 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21925 for(i=3-enc; i<length && z[i]==0; i+=2){}
21926 nonNum = i<length;
21927 zEnd = z+i+enc-3;
21928 z += (enc&1);
21931 /* skip leading spaces */
21932 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21933 if( z>=zEnd ) return 0;
21935 /* get sign of significand */
21936 if( *z=='-' ){
21937 sign = -1;
21938 z+=incr;
21939 }else if( *z=='+' ){
21940 z+=incr;
21943 /* skip leading zeroes */
21944 while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21946 /* copy max significant digits to significand */
21947 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21948 s = s*10 + (*z - '0');
21949 z+=incr, nDigits++;
21952 /* skip non-significant significand digits
21953 ** (increase exponent by d to shift decimal left) */
21954 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21955 if( z>=zEnd ) goto do_atof_calc;
21957 /* if decimal point is present */
21958 if( *z=='.' ){
21959 z+=incr;
21960 /* copy digits from after decimal to significand
21961 ** (decrease exponent by d to shift decimal right) */
21962 while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21963 s = s*10 + (*z - '0');
21964 z+=incr, nDigits++, d--;
21966 /* skip non-significant digits */
21967 while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21969 if( z>=zEnd ) goto do_atof_calc;
21971 /* if exponent is present */
21972 if( *z=='e' || *z=='E' ){
21973 z+=incr;
21974 eValid = 0;
21975 if( z>=zEnd ) goto do_atof_calc;
21976 /* get sign of exponent */
21977 if( *z=='-' ){
21978 esign = -1;
21979 z+=incr;
21980 }else if( *z=='+' ){
21981 z+=incr;
21983 /* copy digits to exponent */
21984 while( z<zEnd && sqlite3Isdigit(*z) ){
21985 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21986 z+=incr;
21987 eValid = 1;
21991 /* skip trailing spaces */
21992 if( nDigits && eValid ){
21993 while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21996 do_atof_calc:
21997 /* adjust exponent by d, and update sign */
21998 e = (e*esign) + d;
21999 if( e<0 ) {
22000 esign = -1;
22001 e *= -1;
22002 } else {
22003 esign = 1;
22006 /* if 0 significand */
22007 if( !s ) {
22008 /* In the IEEE 754 standard, zero is signed.
22009 ** Add the sign if we've seen at least one digit */
22010 result = (sign<0 && nDigits) ? -(double)0 : (double)0;
22011 } else {
22012 /* attempt to reduce exponent */
22013 if( esign>0 ){
22014 while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
22015 }else{
22016 while( !(s%10) && e>0 ) e--,s/=10;
22019 /* adjust the sign of significand */
22020 s = sign<0 ? -s : s;
22022 /* if exponent, scale significand as appropriate
22023 ** and store in result. */
22024 if( e ){
22025 LONGDOUBLE_TYPE scale = 1.0;
22026 #ifndef __vax__
22027 /* attempt to handle extremely small/large numbers better */
22028 if( e>307 && e<342 ){
22029 while( e%308 ) { scale *= 1.0e+1; e -= 1; }
22030 if( esign<0 ){
22031 result = s / scale;
22032 result /= SQLITE_HUGE_DBL;
22033 }else{
22034 result = s * scale;
22035 result *= SQLITE_HUGE_DBL;
22037 }else if( e>=342 ){
22038 if( esign<0 ){
22039 result = 0.0*s;
22040 }else{
22041 result = SQLITE_HUGE_DBL*SQLITE_HUGE_DBL*s; /* Infinity */
22043 }else
22044 #endif
22046 /* 1.0e+22 is the largest power of 10 than can be
22047 ** represented exactly. */
22048 while( e%22 ) { scale *= 1.0e+1; e -= 1; }
22049 while( e>0 ) { scale *= 1.0e+22; e -= 22; }
22050 if( esign<0 ){
22051 result = s / scale;
22052 }else{
22053 result = s * scale;
22056 } else {
22057 result = (double)s;
22061 /* store the result */
22062 *pResult = result;
22064 /* return true if number and no extra non-whitespace chracters after */
22065 return z>=zEnd && nDigits>0 && eValid && nonNum==0;
22066 #else
22067 return !sqlite3Atoi64(z, pResult, length, enc);
22068 #endif /* SQLITE_OMIT_FLOATING_POINT */
22072 ** Compare the 19-character string zNum against the text representation
22073 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
22074 ** if zNum is less than, equal to, or greater than the string.
22075 ** Note that zNum must contain exactly 19 characters.
22077 ** Unlike memcmp() this routine is guaranteed to return the difference
22078 ** in the values of the last digit if the only difference is in the
22079 ** last digit. So, for example,
22081 ** compare2pow63("9223372036854775800", 1)
22083 ** will return -8.
22085 static int compare2pow63(const char *zNum, int incr){
22086 int c = 0;
22087 int i;
22088 /* 012345678901234567 */
22089 const char *pow63 = "922337203685477580";
22090 for(i=0; c==0 && i<18; i++){
22091 c = (zNum[i*incr]-pow63[i])*10;
22093 if( c==0 ){
22094 c = zNum[18*incr] - '8';
22095 testcase( c==(-1) );
22096 testcase( c==0 );
22097 testcase( c==(+1) );
22099 return c;
22104 ** Convert zNum to a 64-bit signed integer.
22106 ** If the zNum value is representable as a 64-bit twos-complement
22107 ** integer, then write that value into *pNum and return 0.
22109 ** If zNum is exactly 9223372036854775808, return 2. This special
22110 ** case is broken out because while 9223372036854775808 cannot be a
22111 ** signed 64-bit integer, its negative -9223372036854775808 can be.
22113 ** If zNum is too big for a 64-bit integer and is not
22114 ** 9223372036854775808 or if zNum contains any non-numeric text,
22115 ** then return 1.
22117 ** length is the number of bytes in the string (bytes, not characters).
22118 ** The string is not necessarily zero-terminated. The encoding is
22119 ** given by enc.
22121 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
22122 int incr;
22123 u64 u = 0;
22124 int neg = 0; /* assume positive */
22125 int i;
22126 int c = 0;
22127 int nonNum = 0;
22128 const char *zStart;
22129 const char *zEnd = zNum + length;
22130 assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
22131 if( enc==SQLITE_UTF8 ){
22132 incr = 1;
22133 }else{
22134 incr = 2;
22135 assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
22136 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
22137 nonNum = i<length;
22138 zEnd = zNum+i+enc-3;
22139 zNum += (enc&1);
22141 while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
22142 if( zNum<zEnd ){
22143 if( *zNum=='-' ){
22144 neg = 1;
22145 zNum+=incr;
22146 }else if( *zNum=='+' ){
22147 zNum+=incr;
22150 zStart = zNum;
22151 while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
22152 for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
22153 u = u*10 + c - '0';
22155 if( u>LARGEST_INT64 ){
22156 *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
22157 }else if( neg ){
22158 *pNum = -(i64)u;
22159 }else{
22160 *pNum = (i64)u;
22162 testcase( i==18 );
22163 testcase( i==19 );
22164 testcase( i==20 );
22165 if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
22166 /* zNum is empty or contains non-numeric text or is longer
22167 ** than 19 digits (thus guaranteeing that it is too large) */
22168 return 1;
22169 }else if( i<19*incr ){
22170 /* Less than 19 digits, so we know that it fits in 64 bits */
22171 assert( u<=LARGEST_INT64 );
22172 return 0;
22173 }else{
22174 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
22175 c = compare2pow63(zNum, incr);
22176 if( c<0 ){
22177 /* zNum is less than 9223372036854775808 so it fits */
22178 assert( u<=LARGEST_INT64 );
22179 return 0;
22180 }else if( c>0 ){
22181 /* zNum is greater than 9223372036854775808 so it overflows */
22182 return 1;
22183 }else{
22184 /* zNum is exactly 9223372036854775808. Fits if negative. The
22185 ** special case 2 overflow if positive */
22186 assert( u-1==LARGEST_INT64 );
22187 return neg ? 0 : 2;
22193 ** If zNum represents an integer that will fit in 32-bits, then set
22194 ** *pValue to that integer and return true. Otherwise return false.
22196 ** Any non-numeric characters that following zNum are ignored.
22197 ** This is different from sqlite3Atoi64() which requires the
22198 ** input number to be zero-terminated.
22200 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
22201 sqlite_int64 v = 0;
22202 int i, c;
22203 int neg = 0;
22204 if( zNum[0]=='-' ){
22205 neg = 1;
22206 zNum++;
22207 }else if( zNum[0]=='+' ){
22208 zNum++;
22210 while( zNum[0]=='0' ) zNum++;
22211 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
22212 v = v*10 + c;
22215 /* The longest decimal representation of a 32 bit integer is 10 digits:
22217 ** 1234567890
22218 ** 2^31 -> 2147483648
22220 testcase( i==10 );
22221 if( i>10 ){
22222 return 0;
22224 testcase( v-neg==2147483647 );
22225 if( v-neg>2147483647 ){
22226 return 0;
22228 if( neg ){
22229 v = -v;
22231 *pValue = (int)v;
22232 return 1;
22236 ** Return a 32-bit integer value extracted from a string. If the
22237 ** string is not an integer, just return 0.
22239 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
22240 int x = 0;
22241 if( z ) sqlite3GetInt32(z, &x);
22242 return x;
22246 ** The variable-length integer encoding is as follows:
22248 ** KEY:
22249 ** A = 0xxxxxxx 7 bits of data and one flag bit
22250 ** B = 1xxxxxxx 7 bits of data and one flag bit
22251 ** C = xxxxxxxx 8 bits of data
22253 ** 7 bits - A
22254 ** 14 bits - BA
22255 ** 21 bits - BBA
22256 ** 28 bits - BBBA
22257 ** 35 bits - BBBBA
22258 ** 42 bits - BBBBBA
22259 ** 49 bits - BBBBBBA
22260 ** 56 bits - BBBBBBBA
22261 ** 64 bits - BBBBBBBBC
22265 ** Write a 64-bit variable-length integer to memory starting at p[0].
22266 ** The length of data write will be between 1 and 9 bytes. The number
22267 ** of bytes written is returned.
22269 ** A variable-length integer consists of the lower 7 bits of each byte
22270 ** for all bytes that have the 8th bit set and one byte with the 8th
22271 ** bit clear. Except, if we get to the 9th byte, it stores the full
22272 ** 8 bits and is the last byte.
22274 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
22275 int i, j, n;
22276 u8 buf[10];
22277 if( v & (((u64)0xff000000)<<32) ){
22278 p[8] = (u8)v;
22279 v >>= 8;
22280 for(i=7; i>=0; i--){
22281 p[i] = (u8)((v & 0x7f) | 0x80);
22282 v >>= 7;
22284 return 9;
22286 n = 0;
22288 buf[n++] = (u8)((v & 0x7f) | 0x80);
22289 v >>= 7;
22290 }while( v!=0 );
22291 buf[0] &= 0x7f;
22292 assert( n<=9 );
22293 for(i=0, j=n-1; j>=0; j--, i++){
22294 p[i] = buf[j];
22296 return n;
22300 ** This routine is a faster version of sqlite3PutVarint() that only
22301 ** works for 32-bit positive integers and which is optimized for
22302 ** the common case of small integers. A MACRO version, putVarint32,
22303 ** is provided which inlines the single-byte case. All code should use
22304 ** the MACRO version as this function assumes the single-byte case has
22305 ** already been handled.
22307 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
22308 #ifndef putVarint32
22309 if( (v & ~0x7f)==0 ){
22310 p[0] = v;
22311 return 1;
22313 #endif
22314 if( (v & ~0x3fff)==0 ){
22315 p[0] = (u8)((v>>7) | 0x80);
22316 p[1] = (u8)(v & 0x7f);
22317 return 2;
22319 return sqlite3PutVarint(p, v);
22323 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
22324 ** are defined here rather than simply putting the constant expressions
22325 ** inline in order to work around bugs in the RVT compiler.
22327 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
22329 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
22331 #define SLOT_2_0 0x001fc07f
22332 #define SLOT_4_2_0 0xf01fc07f
22336 ** Read a 64-bit variable-length integer from memory starting at p[0].
22337 ** Return the number of bytes read. The value is stored in *v.
22339 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
22340 u32 a,b,s;
22342 a = *p;
22343 /* a: p0 (unmasked) */
22344 if (!(a&0x80))
22346 *v = a;
22347 return 1;
22350 p++;
22351 b = *p;
22352 /* b: p1 (unmasked) */
22353 if (!(b&0x80))
22355 a &= 0x7f;
22356 a = a<<7;
22357 a |= b;
22358 *v = a;
22359 return 2;
22362 /* Verify that constants are precomputed correctly */
22363 assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
22364 assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
22366 p++;
22367 a = a<<14;
22368 a |= *p;
22369 /* a: p0<<14 | p2 (unmasked) */
22370 if (!(a&0x80))
22372 a &= SLOT_2_0;
22373 b &= 0x7f;
22374 b = b<<7;
22375 a |= b;
22376 *v = a;
22377 return 3;
22380 /* CSE1 from below */
22381 a &= SLOT_2_0;
22382 p++;
22383 b = b<<14;
22384 b |= *p;
22385 /* b: p1<<14 | p3 (unmasked) */
22386 if (!(b&0x80))
22388 b &= SLOT_2_0;
22389 /* moved CSE1 up */
22390 /* a &= (0x7f<<14)|(0x7f); */
22391 a = a<<7;
22392 a |= b;
22393 *v = a;
22394 return 4;
22397 /* a: p0<<14 | p2 (masked) */
22398 /* b: p1<<14 | p3 (unmasked) */
22399 /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22400 /* moved CSE1 up */
22401 /* a &= (0x7f<<14)|(0x7f); */
22402 b &= SLOT_2_0;
22403 s = a;
22404 /* s: p0<<14 | p2 (masked) */
22406 p++;
22407 a = a<<14;
22408 a |= *p;
22409 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22410 if (!(a&0x80))
22412 /* we can skip these cause they were (effectively) done above in calc'ing s */
22413 /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22414 /* b &= (0x7f<<14)|(0x7f); */
22415 b = b<<7;
22416 a |= b;
22417 s = s>>18;
22418 *v = ((u64)s)<<32 | a;
22419 return 5;
22422 /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22423 s = s<<7;
22424 s |= b;
22425 /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22427 p++;
22428 b = b<<14;
22429 b |= *p;
22430 /* b: p1<<28 | p3<<14 | p5 (unmasked) */
22431 if (!(b&0x80))
22433 /* we can skip this cause it was (effectively) done above in calc'ing s */
22434 /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22435 a &= SLOT_2_0;
22436 a = a<<7;
22437 a |= b;
22438 s = s>>18;
22439 *v = ((u64)s)<<32 | a;
22440 return 6;
22443 p++;
22444 a = a<<14;
22445 a |= *p;
22446 /* a: p2<<28 | p4<<14 | p6 (unmasked) */
22447 if (!(a&0x80))
22449 a &= SLOT_4_2_0;
22450 b &= SLOT_2_0;
22451 b = b<<7;
22452 a |= b;
22453 s = s>>11;
22454 *v = ((u64)s)<<32 | a;
22455 return 7;
22458 /* CSE2 from below */
22459 a &= SLOT_2_0;
22460 p++;
22461 b = b<<14;
22462 b |= *p;
22463 /* b: p3<<28 | p5<<14 | p7 (unmasked) */
22464 if (!(b&0x80))
22466 b &= SLOT_4_2_0;
22467 /* moved CSE2 up */
22468 /* a &= (0x7f<<14)|(0x7f); */
22469 a = a<<7;
22470 a |= b;
22471 s = s>>4;
22472 *v = ((u64)s)<<32 | a;
22473 return 8;
22476 p++;
22477 a = a<<15;
22478 a |= *p;
22479 /* a: p4<<29 | p6<<15 | p8 (unmasked) */
22481 /* moved CSE2 up */
22482 /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
22483 b &= SLOT_2_0;
22484 b = b<<8;
22485 a |= b;
22487 s = s<<4;
22488 b = p[-4];
22489 b &= 0x7f;
22490 b = b>>3;
22491 s |= b;
22493 *v = ((u64)s)<<32 | a;
22495 return 9;
22499 ** Read a 32-bit variable-length integer from memory starting at p[0].
22500 ** Return the number of bytes read. The value is stored in *v.
22502 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
22503 ** integer, then set *v to 0xffffffff.
22505 ** A MACRO version, getVarint32, is provided which inlines the
22506 ** single-byte case. All code should use the MACRO version as
22507 ** this function assumes the single-byte case has already been handled.
22509 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22510 u32 a,b;
22512 /* The 1-byte case. Overwhelmingly the most common. Handled inline
22513 ** by the getVarin32() macro */
22514 a = *p;
22515 /* a: p0 (unmasked) */
22516 #ifndef getVarint32
22517 if (!(a&0x80))
22519 /* Values between 0 and 127 */
22520 *v = a;
22521 return 1;
22523 #endif
22525 /* The 2-byte case */
22526 p++;
22527 b = *p;
22528 /* b: p1 (unmasked) */
22529 if (!(b&0x80))
22531 /* Values between 128 and 16383 */
22532 a &= 0x7f;
22533 a = a<<7;
22534 *v = a | b;
22535 return 2;
22538 /* The 3-byte case */
22539 p++;
22540 a = a<<14;
22541 a |= *p;
22542 /* a: p0<<14 | p2 (unmasked) */
22543 if (!(a&0x80))
22545 /* Values between 16384 and 2097151 */
22546 a &= (0x7f<<14)|(0x7f);
22547 b &= 0x7f;
22548 b = b<<7;
22549 *v = a | b;
22550 return 3;
22553 /* A 32-bit varint is used to store size information in btrees.
22554 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22555 ** A 3-byte varint is sufficient, for example, to record the size
22556 ** of a 1048569-byte BLOB or string.
22558 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
22559 ** rare larger cases can be handled by the slower 64-bit varint
22560 ** routine.
22562 #if 1
22564 u64 v64;
22565 u8 n;
22567 p -= 2;
22568 n = sqlite3GetVarint(p, &v64);
22569 assert( n>3 && n<=9 );
22570 if( (v64 & SQLITE_MAX_U32)!=v64 ){
22571 *v = 0xffffffff;
22572 }else{
22573 *v = (u32)v64;
22575 return n;
22578 #else
22579 /* For following code (kept for historical record only) shows an
22580 ** unrolling for the 3- and 4-byte varint cases. This code is
22581 ** slightly faster, but it is also larger and much harder to test.
22583 p++;
22584 b = b<<14;
22585 b |= *p;
22586 /* b: p1<<14 | p3 (unmasked) */
22587 if (!(b&0x80))
22589 /* Values between 2097152 and 268435455 */
22590 b &= (0x7f<<14)|(0x7f);
22591 a &= (0x7f<<14)|(0x7f);
22592 a = a<<7;
22593 *v = a | b;
22594 return 4;
22597 p++;
22598 a = a<<14;
22599 a |= *p;
22600 /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22601 if (!(a&0x80))
22603 /* Values between 268435456 and 34359738367 */
22604 a &= SLOT_4_2_0;
22605 b &= SLOT_4_2_0;
22606 b = b<<7;
22607 *v = a | b;
22608 return 5;
22611 /* We can only reach this point when reading a corrupt database
22612 ** file. In that case we are not in any hurry. Use the (relatively
22613 ** slow) general-purpose sqlite3GetVarint() routine to extract the
22614 ** value. */
22616 u64 v64;
22617 u8 n;
22619 p -= 4;
22620 n = sqlite3GetVarint(p, &v64);
22621 assert( n>5 && n<=9 );
22622 *v = (u32)v64;
22623 return n;
22625 #endif
22629 ** Return the number of bytes that will be needed to store the given
22630 ** 64-bit integer.
22632 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22633 int i = 0;
22635 i++;
22636 v >>= 7;
22637 }while( v!=0 && ALWAYS(i<9) );
22638 return i;
22643 ** Read or write a four-byte big-endian integer value.
22645 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22646 testcase( p[0]&0x80 );
22647 return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22649 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22650 p[0] = (u8)(v>>24);
22651 p[1] = (u8)(v>>16);
22652 p[2] = (u8)(v>>8);
22653 p[3] = (u8)v;
22659 ** Translate a single byte of Hex into an integer.
22660 ** This routine only works if h really is a valid hexadecimal
22661 ** character: 0..9a..fA..F
22663 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22664 assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
22665 #ifdef SQLITE_ASCII
22666 h += 9*(1&(h>>6));
22667 #endif
22668 #ifdef SQLITE_EBCDIC
22669 h += 9*(1&~(h>>4));
22670 #endif
22671 return (u8)(h & 0xf);
22674 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22676 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22677 ** value. Return a pointer to its binary value. Space to hold the
22678 ** binary value has been obtained from malloc and must be freed by
22679 ** the calling routine.
22681 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22682 char *zBlob;
22683 int i;
22685 zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22686 n--;
22687 if( zBlob ){
22688 for(i=0; i<n; i+=2){
22689 zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22691 zBlob[i/2] = 0;
22693 return zBlob;
22695 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22698 ** Log an error that is an API call on a connection pointer that should
22699 ** not have been used. The "type" of connection pointer is given as the
22700 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
22702 static void logBadConnection(const char *zType){
22703 sqlite3_log(SQLITE_MISUSE,
22704 "API call with %s database connection pointer",
22705 zType
22710 ** Check to make sure we have a valid db pointer. This test is not
22711 ** foolproof but it does provide some measure of protection against
22712 ** misuse of the interface such as passing in db pointers that are
22713 ** NULL or which have been previously closed. If this routine returns
22714 ** 1 it means that the db pointer is valid and 0 if it should not be
22715 ** dereferenced for any reason. The calling function should invoke
22716 ** SQLITE_MISUSE immediately.
22718 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22719 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22720 ** open properly and is not fit for general use but which can be
22721 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22723 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22724 u32 magic;
22725 if( db==0 ){
22726 logBadConnection("NULL");
22727 return 0;
22729 magic = db->magic;
22730 if( magic!=SQLITE_MAGIC_OPEN ){
22731 if( sqlite3SafetyCheckSickOrOk(db) ){
22732 testcase( sqlite3GlobalConfig.xLog!=0 );
22733 logBadConnection("unopened");
22735 return 0;
22736 }else{
22737 return 1;
22740 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22741 u32 magic;
22742 magic = db->magic;
22743 if( magic!=SQLITE_MAGIC_SICK &&
22744 magic!=SQLITE_MAGIC_OPEN &&
22745 magic!=SQLITE_MAGIC_BUSY ){
22746 testcase( sqlite3GlobalConfig.xLog!=0 );
22747 logBadConnection("invalid");
22748 return 0;
22749 }else{
22750 return 1;
22755 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22756 ** the other 64-bit signed integer at *pA and store the result in *pA.
22757 ** Return 0 on success. Or if the operation would have resulted in an
22758 ** overflow, leave *pA unchanged and return 1.
22760 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22761 i64 iA = *pA;
22762 testcase( iA==0 ); testcase( iA==1 );
22763 testcase( iB==-1 ); testcase( iB==0 );
22764 if( iB>=0 ){
22765 testcase( iA>0 && LARGEST_INT64 - iA == iB );
22766 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22767 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22768 *pA += iB;
22769 }else{
22770 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22771 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22772 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22773 *pA += iB;
22775 return 0;
22777 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22778 testcase( iB==SMALLEST_INT64+1 );
22779 if( iB==SMALLEST_INT64 ){
22780 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22781 if( (*pA)>=0 ) return 1;
22782 *pA -= iB;
22783 return 0;
22784 }else{
22785 return sqlite3AddInt64(pA, -iB);
22788 #define TWOPOWER32 (((i64)1)<<32)
22789 #define TWOPOWER31 (((i64)1)<<31)
22790 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22791 i64 iA = *pA;
22792 i64 iA1, iA0, iB1, iB0, r;
22794 iA1 = iA/TWOPOWER32;
22795 iA0 = iA % TWOPOWER32;
22796 iB1 = iB/TWOPOWER32;
22797 iB0 = iB % TWOPOWER32;
22798 if( iA1*iB1 != 0 ) return 1;
22799 assert( iA1*iB0==0 || iA0*iB1==0 );
22800 r = iA1*iB0 + iA0*iB1;
22801 testcase( r==(-TWOPOWER31)-1 );
22802 testcase( r==(-TWOPOWER31) );
22803 testcase( r==TWOPOWER31 );
22804 testcase( r==TWOPOWER31-1 );
22805 if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22806 r *= TWOPOWER32;
22807 if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22808 *pA = r;
22809 return 0;
22813 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
22814 ** if the integer has a value of -2147483648, return +2147483647
22816 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22817 if( x>=0 ) return x;
22818 if( x==(int)0x80000000 ) return 0x7fffffff;
22819 return -x;
22822 #ifdef SQLITE_ENABLE_8_3_NAMES
22824 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22825 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22826 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22827 ** three characters, then shorten the suffix on z[] to be the last three
22828 ** characters of the original suffix.
22830 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22831 ** do the suffix shortening regardless of URI parameter.
22833 ** Examples:
22835 ** test.db-journal => test.nal
22836 ** test.db-wal => test.wal
22837 ** test.db-shm => test.shm
22838 ** test.db-mj7f3319fa => test.9fa
22840 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22841 #if SQLITE_ENABLE_8_3_NAMES<2
22842 if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22843 #endif
22845 int i, sz;
22846 sz = sqlite3Strlen30(z);
22847 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22848 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22851 #endif
22854 ** Find (an approximate) sum of two LogEst values. This computation is
22855 ** not a simple "+" operator because LogEst is stored as a logarithmic
22856 ** value.
22859 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
22860 static const unsigned char x[] = {
22861 10, 10, /* 0,1 */
22862 9, 9, /* 2,3 */
22863 8, 8, /* 4,5 */
22864 7, 7, 7, /* 6,7,8 */
22865 6, 6, 6, /* 9,10,11 */
22866 5, 5, 5, /* 12-14 */
22867 4, 4, 4, 4, /* 15-18 */
22868 3, 3, 3, 3, 3, 3, /* 19-24 */
22869 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
22871 if( a>=b ){
22872 if( a>b+49 ) return a;
22873 if( a>b+31 ) return a+1;
22874 return a+x[a-b];
22875 }else{
22876 if( b>a+49 ) return b;
22877 if( b>a+31 ) return b+1;
22878 return b+x[b-a];
22883 ** Convert an integer into a LogEst. In other words, compute a
22884 ** good approximatation for 10*log2(x).
22886 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
22887 static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
22888 LogEst y = 40;
22889 if( x<8 ){
22890 if( x<2 ) return 0;
22891 while( x<8 ){ y -= 10; x <<= 1; }
22892 }else{
22893 while( x>255 ){ y += 40; x >>= 4; }
22894 while( x>15 ){ y += 10; x >>= 1; }
22896 return a[x&7] + y - 10;
22899 #ifndef SQLITE_OMIT_VIRTUALTABLE
22901 ** Convert a double into a LogEst
22902 ** In other words, compute an approximation for 10*log2(x).
22904 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
22905 u64 a;
22906 LogEst e;
22907 assert( sizeof(x)==8 && sizeof(a)==8 );
22908 if( x<=1 ) return 0;
22909 if( x<=2000000000 ) return sqlite3LogEst((u64)x);
22910 memcpy(&a, &x, 8);
22911 e = (a>>52) - 1022;
22912 return e*10;
22914 #endif /* SQLITE_OMIT_VIRTUALTABLE */
22917 ** Convert a LogEst into an integer.
22919 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
22920 u64 n;
22921 if( x<10 ) return 1;
22922 n = x%10;
22923 x /= 10;
22924 if( n>=5 ) n -= 2;
22925 else if( n>=1 ) n -= 1;
22926 if( x>=3 ){
22927 return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
22929 return (n+8)>>(3-x);
22932 /************** End of util.c ************************************************/
22933 /************** Begin file hash.c ********************************************/
22935 ** 2001 September 22
22937 ** The author disclaims copyright to this source code. In place of
22938 ** a legal notice, here is a blessing:
22940 ** May you do good and not evil.
22941 ** May you find forgiveness for yourself and forgive others.
22942 ** May you share freely, never taking more than you give.
22944 *************************************************************************
22945 ** This is the implementation of generic hash-tables
22946 ** used in SQLite.
22948 /* #include <assert.h> */
22950 /* Turn bulk memory into a hash table object by initializing the
22951 ** fields of the Hash structure.
22953 ** "pNew" is a pointer to the hash table that is to be initialized.
22955 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22956 assert( pNew!=0 );
22957 pNew->first = 0;
22958 pNew->count = 0;
22959 pNew->htsize = 0;
22960 pNew->ht = 0;
22963 /* Remove all entries from a hash table. Reclaim all memory.
22964 ** Call this routine to delete a hash table or to reset a hash table
22965 ** to the empty state.
22967 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22968 HashElem *elem; /* For looping over all elements of the table */
22970 assert( pH!=0 );
22971 elem = pH->first;
22972 pH->first = 0;
22973 sqlite3_free(pH->ht);
22974 pH->ht = 0;
22975 pH->htsize = 0;
22976 while( elem ){
22977 HashElem *next_elem = elem->next;
22978 sqlite3_free(elem);
22979 elem = next_elem;
22981 pH->count = 0;
22985 ** The hashing function.
22987 static unsigned int strHash(const char *z, int nKey){
22988 unsigned int h = 0;
22989 assert( nKey>=0 );
22990 while( nKey > 0 ){
22991 h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22992 nKey--;
22994 return h;
22998 /* Link pNew element into the hash table pH. If pEntry!=0 then also
22999 ** insert pNew into the pEntry hash bucket.
23001 static void insertElement(
23002 Hash *pH, /* The complete hash table */
23003 struct _ht *pEntry, /* The entry into which pNew is inserted */
23004 HashElem *pNew /* The element to be inserted */
23006 HashElem *pHead; /* First element already in pEntry */
23007 if( pEntry ){
23008 pHead = pEntry->count ? pEntry->chain : 0;
23009 pEntry->count++;
23010 pEntry->chain = pNew;
23011 }else{
23012 pHead = 0;
23014 if( pHead ){
23015 pNew->next = pHead;
23016 pNew->prev = pHead->prev;
23017 if( pHead->prev ){ pHead->prev->next = pNew; }
23018 else { pH->first = pNew; }
23019 pHead->prev = pNew;
23020 }else{
23021 pNew->next = pH->first;
23022 if( pH->first ){ pH->first->prev = pNew; }
23023 pNew->prev = 0;
23024 pH->first = pNew;
23029 /* Resize the hash table so that it cantains "new_size" buckets.
23031 ** The hash table might fail to resize if sqlite3_malloc() fails or
23032 ** if the new size is the same as the prior size.
23033 ** Return TRUE if the resize occurs and false if not.
23035 static int rehash(Hash *pH, unsigned int new_size){
23036 struct _ht *new_ht; /* The new hash table */
23037 HashElem *elem, *next_elem; /* For looping over existing elements */
23039 #if SQLITE_MALLOC_SOFT_LIMIT>0
23040 if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
23041 new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
23043 if( new_size==pH->htsize ) return 0;
23044 #endif
23046 /* The inability to allocates space for a larger hash table is
23047 ** a performance hit but it is not a fatal error. So mark the
23048 ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
23049 ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
23050 ** only zeroes the requested number of bytes whereas this module will
23051 ** use the actual amount of space allocated for the hash table (which
23052 ** may be larger than the requested amount).
23054 sqlite3BeginBenignMalloc();
23055 new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
23056 sqlite3EndBenignMalloc();
23058 if( new_ht==0 ) return 0;
23059 sqlite3_free(pH->ht);
23060 pH->ht = new_ht;
23061 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
23062 memset(new_ht, 0, new_size*sizeof(struct _ht));
23063 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
23064 unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
23065 next_elem = elem->next;
23066 insertElement(pH, &new_ht[h], elem);
23068 return 1;
23071 /* This function (for internal use only) locates an element in an
23072 ** hash table that matches the given key. The hash for this key has
23073 ** already been computed and is passed as the 4th parameter.
23075 static HashElem *findElementGivenHash(
23076 const Hash *pH, /* The pH to be searched */
23077 const char *pKey, /* The key we are searching for */
23078 int nKey, /* Bytes in key (not counting zero terminator) */
23079 unsigned int h /* The hash for this key. */
23081 HashElem *elem; /* Used to loop thru the element list */
23082 int count; /* Number of elements left to test */
23084 if( pH->ht ){
23085 struct _ht *pEntry = &pH->ht[h];
23086 elem = pEntry->chain;
23087 count = pEntry->count;
23088 }else{
23089 elem = pH->first;
23090 count = pH->count;
23092 while( count-- && ALWAYS(elem) ){
23093 if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
23094 return elem;
23096 elem = elem->next;
23098 return 0;
23101 /* Remove a single entry from the hash table given a pointer to that
23102 ** element and a hash on the element's key.
23104 static void removeElementGivenHash(
23105 Hash *pH, /* The pH containing "elem" */
23106 HashElem* elem, /* The element to be removed from the pH */
23107 unsigned int h /* Hash value for the element */
23109 struct _ht *pEntry;
23110 if( elem->prev ){
23111 elem->prev->next = elem->next;
23112 }else{
23113 pH->first = elem->next;
23115 if( elem->next ){
23116 elem->next->prev = elem->prev;
23118 if( pH->ht ){
23119 pEntry = &pH->ht[h];
23120 if( pEntry->chain==elem ){
23121 pEntry->chain = elem->next;
23123 pEntry->count--;
23124 assert( pEntry->count>=0 );
23126 sqlite3_free( elem );
23127 pH->count--;
23128 if( pH->count==0 ){
23129 assert( pH->first==0 );
23130 assert( pH->count==0 );
23131 sqlite3HashClear(pH);
23135 /* Attempt to locate an element of the hash table pH with a key
23136 ** that matches pKey,nKey. Return the data for this element if it is
23137 ** found, or NULL if there is no match.
23139 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
23140 HashElem *elem; /* The element that matches key */
23141 unsigned int h; /* A hash on key */
23143 assert( pH!=0 );
23144 assert( pKey!=0 );
23145 assert( nKey>=0 );
23146 if( pH->ht ){
23147 h = strHash(pKey, nKey) % pH->htsize;
23148 }else{
23149 h = 0;
23151 elem = findElementGivenHash(pH, pKey, nKey, h);
23152 return elem ? elem->data : 0;
23155 /* Insert an element into the hash table pH. The key is pKey,nKey
23156 ** and the data is "data".
23158 ** If no element exists with a matching key, then a new
23159 ** element is created and NULL is returned.
23161 ** If another element already exists with the same key, then the
23162 ** new data replaces the old data and the old data is returned.
23163 ** The key is not copied in this instance. If a malloc fails, then
23164 ** the new data is returned and the hash table is unchanged.
23166 ** If the "data" parameter to this function is NULL, then the
23167 ** element corresponding to "key" is removed from the hash table.
23169 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
23170 unsigned int h; /* the hash of the key modulo hash table size */
23171 HashElem *elem; /* Used to loop thru the element list */
23172 HashElem *new_elem; /* New element added to the pH */
23174 assert( pH!=0 );
23175 assert( pKey!=0 );
23176 assert( nKey>=0 );
23177 if( pH->htsize ){
23178 h = strHash(pKey, nKey) % pH->htsize;
23179 }else{
23180 h = 0;
23182 elem = findElementGivenHash(pH,pKey,nKey,h);
23183 if( elem ){
23184 void *old_data = elem->data;
23185 if( data==0 ){
23186 removeElementGivenHash(pH,elem,h);
23187 }else{
23188 elem->data = data;
23189 elem->pKey = pKey;
23190 assert(nKey==elem->nKey);
23192 return old_data;
23194 if( data==0 ) return 0;
23195 new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
23196 if( new_elem==0 ) return data;
23197 new_elem->pKey = pKey;
23198 new_elem->nKey = nKey;
23199 new_elem->data = data;
23200 pH->count++;
23201 if( pH->count>=10 && pH->count > 2*pH->htsize ){
23202 if( rehash(pH, pH->count*2) ){
23203 assert( pH->htsize>0 );
23204 h = strHash(pKey, nKey) % pH->htsize;
23207 if( pH->ht ){
23208 insertElement(pH, &pH->ht[h], new_elem);
23209 }else{
23210 insertElement(pH, 0, new_elem);
23212 return 0;
23215 /************** End of hash.c ************************************************/
23216 /************** Begin file opcodes.c *****************************************/
23217 /* Automatically generated. Do not edit */
23218 /* See the mkopcodec.awk script for details. */
23219 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
23220 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
23221 # define OpHelp(X) "\0" X
23222 #else
23223 # define OpHelp(X)
23224 #endif
23225 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
23226 static const char *const azName[] = { "?",
23227 /* 1 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
23228 /* 2 */ "Savepoint" OpHelp(""),
23229 /* 3 */ "AutoCommit" OpHelp(""),
23230 /* 4 */ "Transaction" OpHelp(""),
23231 /* 5 */ "SorterNext" OpHelp(""),
23232 /* 6 */ "PrevIfOpen" OpHelp(""),
23233 /* 7 */ "NextIfOpen" OpHelp(""),
23234 /* 8 */ "Prev" OpHelp(""),
23235 /* 9 */ "Next" OpHelp(""),
23236 /* 10 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
23237 /* 11 */ "Checkpoint" OpHelp(""),
23238 /* 12 */ "JournalMode" OpHelp(""),
23239 /* 13 */ "Vacuum" OpHelp(""),
23240 /* 14 */ "VFilter" OpHelp("iPlan=r[P3] zPlan='P4'"),
23241 /* 15 */ "VUpdate" OpHelp("data=r[P3@P2]"),
23242 /* 16 */ "Goto" OpHelp(""),
23243 /* 17 */ "Gosub" OpHelp(""),
23244 /* 18 */ "Return" OpHelp(""),
23245 /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
23246 /* 20 */ "Yield" OpHelp(""),
23247 /* 21 */ "HaltIfNull" OpHelp("if r[P3] null then halt"),
23248 /* 22 */ "Halt" OpHelp(""),
23249 /* 23 */ "Integer" OpHelp("r[P2]=P1"),
23250 /* 24 */ "Int64" OpHelp("r[P2]=P4"),
23251 /* 25 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
23252 /* 26 */ "Null" OpHelp("r[P2..P3]=NULL"),
23253 /* 27 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
23254 /* 28 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
23255 /* 29 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
23256 /* 30 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
23257 /* 31 */ "SCopy" OpHelp("r[P2]=r[P1]"),
23258 /* 32 */ "ResultRow" OpHelp("output=r[P1@P2]"),
23259 /* 33 */ "CollSeq" OpHelp(""),
23260 /* 34 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
23261 /* 35 */ "MustBeInt" OpHelp(""),
23262 /* 36 */ "RealAffinity" OpHelp(""),
23263 /* 37 */ "Permutation" OpHelp(""),
23264 /* 38 */ "Compare" OpHelp(""),
23265 /* 39 */ "Jump" OpHelp(""),
23266 /* 40 */ "Once" OpHelp(""),
23267 /* 41 */ "If" OpHelp(""),
23268 /* 42 */ "IfNot" OpHelp(""),
23269 /* 43 */ "Column" OpHelp("r[P3]=PX"),
23270 /* 44 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
23271 /* 45 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
23272 /* 46 */ "Count" OpHelp("r[P2]=count()"),
23273 /* 47 */ "ReadCookie" OpHelp(""),
23274 /* 48 */ "SetCookie" OpHelp(""),
23275 /* 49 */ "VerifyCookie" OpHelp(""),
23276 /* 50 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
23277 /* 51 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
23278 /* 52 */ "OpenAutoindex" OpHelp("nColumn=P2"),
23279 /* 53 */ "OpenEphemeral" OpHelp("nColumn=P2"),
23280 /* 54 */ "SorterOpen" OpHelp(""),
23281 /* 55 */ "OpenPseudo" OpHelp("content in r[P2@P3]"),
23282 /* 56 */ "Close" OpHelp(""),
23283 /* 57 */ "SeekLt" OpHelp("key=r[P3@P4]"),
23284 /* 58 */ "SeekLe" OpHelp("key=r[P3@P4]"),
23285 /* 59 */ "SeekGe" OpHelp("key=r[P3@P4]"),
23286 /* 60 */ "SeekGt" OpHelp("key=r[P3@P4]"),
23287 /* 61 */ "Seek" OpHelp("intkey=r[P2]"),
23288 /* 62 */ "NoConflict" OpHelp("key=r[P3@P4]"),
23289 /* 63 */ "NotFound" OpHelp("key=r[P3@P4]"),
23290 /* 64 */ "Found" OpHelp("key=r[P3@P4]"),
23291 /* 65 */ "NotExists" OpHelp("intkey=r[P3]"),
23292 /* 66 */ "Sequence" OpHelp("r[P2]=rowid"),
23293 /* 67 */ "NewRowid" OpHelp("r[P2]=rowid"),
23294 /* 68 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
23295 /* 69 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
23296 /* 70 */ "Delete" OpHelp(""),
23297 /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
23298 /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
23299 /* 73 */ "ResetCount" OpHelp(""),
23300 /* 74 */ "SorterCompare" OpHelp("if key(P1)!=rtrim(r[P3],P4) goto P2"),
23301 /* 75 */ "SorterData" OpHelp("r[P2]=data"),
23302 /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
23303 /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
23304 /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
23305 /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
23306 /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
23307 /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
23308 /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
23309 /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
23310 /* 84 */ "RowKey" OpHelp("r[P2]=key"),
23311 /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
23312 /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
23313 /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
23314 /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
23315 /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
23316 /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
23317 /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
23318 /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
23319 /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
23320 /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
23321 /* 95 */ "RowData" OpHelp("r[P2]=data"),
23322 /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
23323 /* 97 */ "String8" OpHelp("r[P2]='P4'"),
23324 /* 98 */ "Rowid" OpHelp("r[P2]=rowid"),
23325 /* 99 */ "NullRow" OpHelp(""),
23326 /* 100 */ "Last" OpHelp(""),
23327 /* 101 */ "SorterSort" OpHelp(""),
23328 /* 102 */ "Sort" OpHelp(""),
23329 /* 103 */ "Rewind" OpHelp(""),
23330 /* 104 */ "SorterInsert" OpHelp(""),
23331 /* 105 */ "IdxInsert" OpHelp("key=r[P2]"),
23332 /* 106 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
23333 /* 107 */ "IdxRowid" OpHelp("r[P2]=rowid"),
23334 /* 108 */ "IdxLT" OpHelp("key=r[P3@P4]"),
23335 /* 109 */ "IdxGE" OpHelp("key=r[P3@P4]"),
23336 /* 110 */ "Destroy" OpHelp(""),
23337 /* 111 */ "Clear" OpHelp(""),
23338 /* 112 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
23339 /* 113 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
23340 /* 114 */ "ParseSchema" OpHelp(""),
23341 /* 115 */ "LoadAnalysis" OpHelp(""),
23342 /* 116 */ "DropTable" OpHelp(""),
23343 /* 117 */ "DropIndex" OpHelp(""),
23344 /* 118 */ "DropTrigger" OpHelp(""),
23345 /* 119 */ "IntegrityCk" OpHelp(""),
23346 /* 120 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
23347 /* 121 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
23348 /* 122 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
23349 /* 123 */ "Program" OpHelp(""),
23350 /* 124 */ "Param" OpHelp(""),
23351 /* 125 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
23352 /* 126 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
23353 /* 127 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
23354 /* 128 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
23355 /* 129 */ "IfNeg" OpHelp("if r[P1]<0 goto P2"),
23356 /* 130 */ "IfZero" OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
23357 /* 131 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
23358 /* 132 */ "IncrVacuum" OpHelp(""),
23359 /* 133 */ "Real" OpHelp("r[P2]=P4"),
23360 /* 134 */ "Expire" OpHelp(""),
23361 /* 135 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
23362 /* 136 */ "VBegin" OpHelp(""),
23363 /* 137 */ "VCreate" OpHelp(""),
23364 /* 138 */ "VDestroy" OpHelp(""),
23365 /* 139 */ "VOpen" OpHelp(""),
23366 /* 140 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
23367 /* 141 */ "VNext" OpHelp(""),
23368 /* 142 */ "VRename" OpHelp(""),
23369 /* 143 */ "ToText" OpHelp(""),
23370 /* 144 */ "ToBlob" OpHelp(""),
23371 /* 145 */ "ToNumeric" OpHelp(""),
23372 /* 146 */ "ToInt" OpHelp(""),
23373 /* 147 */ "ToReal" OpHelp(""),
23374 /* 148 */ "Pagecount" OpHelp(""),
23375 /* 149 */ "MaxPgcnt" OpHelp(""),
23376 /* 150 */ "Trace" OpHelp(""),
23377 /* 151 */ "Noop" OpHelp(""),
23378 /* 152 */ "Explain" OpHelp(""),
23380 return azName[i];
23382 #endif
23384 /************** End of opcodes.c *********************************************/
23385 /************** Begin file os_unix.c *****************************************/
23387 ** 2004 May 22
23389 ** The author disclaims copyright to this source code. In place of
23390 ** a legal notice, here is a blessing:
23392 ** May you do good and not evil.
23393 ** May you find forgiveness for yourself and forgive others.
23394 ** May you share freely, never taking more than you give.
23396 ******************************************************************************
23398 ** This file contains the VFS implementation for unix-like operating systems
23399 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
23401 ** There are actually several different VFS implementations in this file.
23402 ** The differences are in the way that file locking is done. The default
23403 ** implementation uses Posix Advisory Locks. Alternative implementations
23404 ** use flock(), dot-files, various proprietary locking schemas, or simply
23405 ** skip locking all together.
23407 ** This source file is organized into divisions where the logic for various
23408 ** subfunctions is contained within the appropriate division. PLEASE
23409 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
23410 ** in the correct division and should be clearly labeled.
23412 ** The layout of divisions is as follows:
23414 ** * General-purpose declarations and utility functions.
23415 ** * Unique file ID logic used by VxWorks.
23416 ** * Various locking primitive implementations (all except proxy locking):
23417 ** + for Posix Advisory Locks
23418 ** + for no-op locks
23419 ** + for dot-file locks
23420 ** + for flock() locking
23421 ** + for named semaphore locks (VxWorks only)
23422 ** + for AFP filesystem locks (MacOSX only)
23423 ** * sqlite3_file methods not associated with locking.
23424 ** * Definitions of sqlite3_io_methods objects for all locking
23425 ** methods plus "finder" functions for each locking method.
23426 ** * sqlite3_vfs method implementations.
23427 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
23428 ** * Definitions of sqlite3_vfs objects for all locking methods
23429 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
23431 #if SQLITE_OS_UNIX /* This file is used on unix only */
23434 ** There are various methods for file locking used for concurrency
23435 ** control:
23437 ** 1. POSIX locking (the default),
23438 ** 2. No locking,
23439 ** 3. Dot-file locking,
23440 ** 4. flock() locking,
23441 ** 5. AFP locking (OSX only),
23442 ** 6. Named POSIX semaphores (VXWorks only),
23443 ** 7. proxy locking. (OSX only)
23445 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
23446 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
23447 ** selection of the appropriate locking style based on the filesystem
23448 ** where the database is located.
23450 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
23451 # if defined(__APPLE__)
23452 # define SQLITE_ENABLE_LOCKING_STYLE 1
23453 # else
23454 # define SQLITE_ENABLE_LOCKING_STYLE 0
23455 # endif
23456 #endif
23459 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
23460 ** vxworks, or 0 otherwise.
23462 #ifndef OS_VXWORKS
23463 # if defined(__RTP__) || defined(_WRS_KERNEL)
23464 # define OS_VXWORKS 1
23465 # else
23466 # define OS_VXWORKS 0
23467 # endif
23468 #endif
23471 ** These #defines should enable >2GB file support on Posix if the
23472 ** underlying operating system supports it. If the OS lacks
23473 ** large file support, these should be no-ops.
23475 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
23476 ** on the compiler command line. This is necessary if you are compiling
23477 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
23478 ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
23479 ** without this option, LFS is enable. But LFS does not exist in the kernel
23480 ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
23481 ** portability you should omit LFS.
23483 ** The previous paragraph was written in 2005. (This paragraph is written
23484 ** on 2008-11-28.) These days, all Linux kernels support large files, so
23485 ** you should probably leave LFS enabled. But some embedded platforms might
23486 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
23488 #ifndef SQLITE_DISABLE_LFS
23489 # define _LARGE_FILE 1
23490 # ifndef _FILE_OFFSET_BITS
23491 # define _FILE_OFFSET_BITS 64
23492 # endif
23493 # define _LARGEFILE_SOURCE 1
23494 #endif
23497 ** standard include files.
23499 #include <sys/types.h>
23500 #include <sys/stat.h>
23501 #include <fcntl.h>
23502 #include <unistd.h>
23503 /* #include <time.h> */
23504 #include <sys/time.h>
23505 #include <errno.h>
23506 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
23507 #include <sys/mman.h>
23508 #endif
23511 #if SQLITE_ENABLE_LOCKING_STYLE
23512 # include <sys/ioctl.h>
23513 # if OS_VXWORKS
23514 # include <semaphore.h>
23515 # include <limits.h>
23516 # else
23517 # include <sys/file.h>
23518 # include <sys/param.h>
23519 # endif
23520 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
23522 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
23523 # include <sys/mount.h>
23524 #endif
23526 #ifdef HAVE_UTIME
23527 # include <utime.h>
23528 #endif
23531 ** Allowed values of unixFile.fsFlags
23533 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
23536 ** If we are to be thread-safe, include the pthreads header and define
23537 ** the SQLITE_UNIX_THREADS macro.
23539 #if SQLITE_THREADSAFE
23540 /* # include <pthread.h> */
23541 # define SQLITE_UNIX_THREADS 1
23542 #endif
23545 ** Default permissions when creating a new file
23547 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23548 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23549 #endif
23552 ** Default permissions when creating auto proxy dir
23554 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23555 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23556 #endif
23559 ** Maximum supported path-length.
23561 #define MAX_PATHNAME 512
23564 ** Only set the lastErrno if the error code is a real error and not
23565 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23567 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23569 /* Forward references */
23570 typedef struct unixShm unixShm; /* Connection shared memory */
23571 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
23572 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
23573 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
23576 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
23577 ** cannot be closed immediately. In these cases, instances of the following
23578 ** structure are used to store the file descriptor while waiting for an
23579 ** opportunity to either close or reuse it.
23581 struct UnixUnusedFd {
23582 int fd; /* File descriptor to close */
23583 int flags; /* Flags this file descriptor was opened with */
23584 UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
23588 ** The unixFile structure is subclass of sqlite3_file specific to the unix
23589 ** VFS implementations.
23591 typedef struct unixFile unixFile;
23592 struct unixFile {
23593 sqlite3_io_methods const *pMethod; /* Always the first entry */
23594 sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
23595 unixInodeInfo *pInode; /* Info about locks on this inode */
23596 int h; /* The file descriptor */
23597 unsigned char eFileLock; /* The type of lock held on this fd */
23598 unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
23599 int lastErrno; /* The unix errno from last I/O error */
23600 void *lockingContext; /* Locking style specific state */
23601 UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
23602 const char *zPath; /* Name of the file */
23603 unixShm *pShm; /* Shared memory segment information */
23604 int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
23605 #if SQLITE_MAX_MMAP_SIZE>0
23606 int nFetchOut; /* Number of outstanding xFetch refs */
23607 sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
23608 sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
23609 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
23610 void *pMapRegion; /* Memory mapped region */
23611 #endif
23612 #ifdef __QNXNTO__
23613 int sectorSize; /* Device sector size */
23614 int deviceCharacteristics; /* Precomputed device characteristics */
23615 #endif
23616 #if SQLITE_ENABLE_LOCKING_STYLE
23617 int openFlags; /* The flags specified at open() */
23618 #endif
23619 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23620 unsigned fsFlags; /* cached details from statfs() */
23621 #endif
23622 #if OS_VXWORKS
23623 struct vxworksFileId *pId; /* Unique file ID */
23624 #endif
23625 #ifdef SQLITE_DEBUG
23626 /* The next group of variables are used to track whether or not the
23627 ** transaction counter in bytes 24-27 of database files are updated
23628 ** whenever any part of the database changes. An assertion fault will
23629 ** occur if a file is updated without also updating the transaction
23630 ** counter. This test is made to avoid new problems similar to the
23631 ** one described by ticket #3584.
23633 unsigned char transCntrChng; /* True if the transaction counter changed */
23634 unsigned char dbUpdate; /* True if any part of database file changed */
23635 unsigned char inNormalWrite; /* True if in a normal write operation */
23637 #endif
23639 #ifdef SQLITE_TEST
23640 /* In test mode, increase the size of this structure a bit so that
23641 ** it is larger than the struct CrashFile defined in test6.c.
23643 char aPadding[32];
23644 #endif
23647 /* This variable holds the process id (pid) from when the xRandomness()
23648 ** method was called. If xOpen() is called from a different process id,
23649 ** indicating that a fork() has occurred, the PRNG will be reset.
23651 static int randomnessPid = 0;
23654 ** Allowed values for the unixFile.ctrlFlags bitmask:
23656 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
23657 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
23658 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
23659 #ifndef SQLITE_DISABLE_DIRSYNC
23660 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
23661 #else
23662 # define UNIXFILE_DIRSYNC 0x00
23663 #endif
23664 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
23665 #define UNIXFILE_DELETE 0x20 /* Delete on close */
23666 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
23667 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
23668 #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
23671 ** Include code that is common to all os_*.c files
23673 /************** Include os_common.h in the middle of os_unix.c ***************/
23674 /************** Begin file os_common.h ***************************************/
23676 ** 2004 May 22
23678 ** The author disclaims copyright to this source code. In place of
23679 ** a legal notice, here is a blessing:
23681 ** May you do good and not evil.
23682 ** May you find forgiveness for yourself and forgive others.
23683 ** May you share freely, never taking more than you give.
23685 ******************************************************************************
23687 ** This file contains macros and a little bit of code that is common to
23688 ** all of the platform-specific files (os_*.c) and is #included into those
23689 ** files.
23691 ** This file should be #included by the os_*.c files only. It is not a
23692 ** general purpose header file.
23694 #ifndef _OS_COMMON_H_
23695 #define _OS_COMMON_H_
23698 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23699 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23700 ** switch. The following code should catch this problem at compile-time.
23702 #ifdef MEMORY_DEBUG
23703 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
23704 #endif
23706 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23707 # ifndef SQLITE_DEBUG_OS_TRACE
23708 # define SQLITE_DEBUG_OS_TRACE 0
23709 # endif
23710 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23711 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
23712 #else
23713 # define OSTRACE(X)
23714 #endif
23717 ** Macros for performance tracing. Normally turned off. Only works
23718 ** on i486 hardware.
23720 #ifdef SQLITE_PERFORMANCE_TRACE
23723 ** hwtime.h contains inline assembler code for implementing
23724 ** high-performance timing routines.
23726 /************** Include hwtime.h in the middle of os_common.h ****************/
23727 /************** Begin file hwtime.h ******************************************/
23729 ** 2008 May 27
23731 ** The author disclaims copyright to this source code. In place of
23732 ** a legal notice, here is a blessing:
23734 ** May you do good and not evil.
23735 ** May you find forgiveness for yourself and forgive others.
23736 ** May you share freely, never taking more than you give.
23738 ******************************************************************************
23740 ** This file contains inline asm code for retrieving "high-performance"
23741 ** counters for x86 class CPUs.
23743 #ifndef _HWTIME_H_
23744 #define _HWTIME_H_
23747 ** The following routine only works on pentium-class (or newer) processors.
23748 ** It uses the RDTSC opcode to read the cycle count value out of the
23749 ** processor and returns that value. This can be used for high-res
23750 ** profiling.
23752 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23753 (defined(i386) || defined(__i386__) || defined(_M_IX86))
23755 #if defined(__GNUC__)
23757 __inline__ sqlite_uint64 sqlite3Hwtime(void){
23758 unsigned int lo, hi;
23759 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23760 return (sqlite_uint64)hi << 32 | lo;
23763 #elif defined(_MSC_VER)
23765 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23766 __asm {
23767 rdtsc
23768 ret ; return value at EDX:EAX
23772 #endif
23774 #elif (defined(__GNUC__) && defined(__x86_64__))
23776 __inline__ sqlite_uint64 sqlite3Hwtime(void){
23777 unsigned long val;
23778 __asm__ __volatile__ ("rdtsc" : "=A" (val));
23779 return val;
23782 #elif (defined(__GNUC__) && defined(__ppc__))
23784 __inline__ sqlite_uint64 sqlite3Hwtime(void){
23785 unsigned long long retval;
23786 unsigned long junk;
23787 __asm__ __volatile__ ("\n\
23788 1: mftbu %1\n\
23789 mftb %L0\n\
23790 mftbu %0\n\
23791 cmpw %0,%1\n\
23792 bne 1b"
23793 : "=r" (retval), "=r" (junk));
23794 return retval;
23797 #else
23799 #error Need implementation of sqlite3Hwtime() for your platform.
23802 ** To compile without implementing sqlite3Hwtime() for your platform,
23803 ** you can remove the above #error and use the following
23804 ** stub function. You will lose timing support for many
23805 ** of the debugging and testing utilities, but it should at
23806 ** least compile and run.
23808 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23810 #endif
23812 #endif /* !defined(_HWTIME_H_) */
23814 /************** End of hwtime.h **********************************************/
23815 /************** Continuing where we left off in os_common.h ******************/
23817 static sqlite_uint64 g_start;
23818 static sqlite_uint64 g_elapsed;
23819 #define TIMER_START g_start=sqlite3Hwtime()
23820 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
23821 #define TIMER_ELAPSED g_elapsed
23822 #else
23823 #define TIMER_START
23824 #define TIMER_END
23825 #define TIMER_ELAPSED ((sqlite_uint64)0)
23826 #endif
23829 ** If we compile with the SQLITE_TEST macro set, then the following block
23830 ** of code will give us the ability to simulate a disk I/O error. This
23831 ** is used for testing the I/O recovery logic.
23833 #ifdef SQLITE_TEST
23834 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
23835 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
23836 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
23837 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
23838 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
23839 SQLITE_API int sqlite3_diskfull_pending = 0;
23840 SQLITE_API int sqlite3_diskfull = 0;
23841 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23842 #define SimulateIOError(CODE) \
23843 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23844 || sqlite3_io_error_pending-- == 1 ) \
23845 { local_ioerr(); CODE; }
23846 static void local_ioerr(){
23847 IOTRACE(("IOERR\n"));
23848 sqlite3_io_error_hit++;
23849 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23851 #define SimulateDiskfullError(CODE) \
23852 if( sqlite3_diskfull_pending ){ \
23853 if( sqlite3_diskfull_pending == 1 ){ \
23854 local_ioerr(); \
23855 sqlite3_diskfull = 1; \
23856 sqlite3_io_error_hit = 1; \
23857 CODE; \
23858 }else{ \
23859 sqlite3_diskfull_pending--; \
23862 #else
23863 #define SimulateIOErrorBenign(X)
23864 #define SimulateIOError(A)
23865 #define SimulateDiskfullError(A)
23866 #endif
23869 ** When testing, keep a count of the number of open files.
23871 #ifdef SQLITE_TEST
23872 SQLITE_API int sqlite3_open_file_count = 0;
23873 #define OpenCounter(X) sqlite3_open_file_count+=(X)
23874 #else
23875 #define OpenCounter(X)
23876 #endif
23878 #endif /* !defined(_OS_COMMON_H_) */
23880 /************** End of os_common.h *******************************************/
23881 /************** Continuing where we left off in os_unix.c ********************/
23884 ** Define various macros that are missing from some systems.
23886 #ifndef O_LARGEFILE
23887 # define O_LARGEFILE 0
23888 #endif
23889 #ifdef SQLITE_DISABLE_LFS
23890 # undef O_LARGEFILE
23891 # define O_LARGEFILE 0
23892 #endif
23893 #ifndef O_NOFOLLOW
23894 # define O_NOFOLLOW 0
23895 #endif
23896 #ifndef O_BINARY
23897 # define O_BINARY 0
23898 #endif
23901 ** The threadid macro resolves to the thread-id or to 0. Used for
23902 ** testing and debugging only.
23904 #if SQLITE_THREADSAFE
23905 #define threadid pthread_self()
23906 #else
23907 #define threadid 0
23908 #endif
23911 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
23913 #if !defined(HAVE_MREMAP)
23914 # if defined(__linux__) && defined(_GNU_SOURCE)
23915 # define HAVE_MREMAP 1
23916 # else
23917 # define HAVE_MREMAP 0
23918 # endif
23919 #endif
23922 ** Different Unix systems declare open() in different ways. Same use
23923 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
23924 ** The difference is important when using a pointer to the function.
23926 ** The safest way to deal with the problem is to always use this wrapper
23927 ** which always has the same well-defined interface.
23929 static int posixOpen(const char *zFile, int flags, int mode){
23930 return open(zFile, flags, mode);
23934 ** On some systems, calls to fchown() will trigger a message in a security
23935 ** log if they come from non-root processes. So avoid calling fchown() if
23936 ** we are not running as root.
23938 static int posixFchown(int fd, uid_t uid, gid_t gid){
23939 return geteuid() ? 0 : fchown(fd,uid,gid);
23942 /* Forward reference */
23943 static int openDirectory(const char*, int*);
23946 ** Many system calls are accessed through pointer-to-functions so that
23947 ** they may be overridden at runtime to facilitate fault injection during
23948 ** testing and sandboxing. The following array holds the names and pointers
23949 ** to all overrideable system calls.
23951 static struct unix_syscall {
23952 const char *zName; /* Name of the system call */
23953 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23954 sqlite3_syscall_ptr pDefault; /* Default value */
23955 } aSyscall[] = {
23956 { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
23957 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23959 { "close", (sqlite3_syscall_ptr)close, 0 },
23960 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
23962 { "access", (sqlite3_syscall_ptr)access, 0 },
23963 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
23965 { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
23966 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23968 { "stat", (sqlite3_syscall_ptr)stat, 0 },
23969 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23972 ** The DJGPP compiler environment looks mostly like Unix, but it
23973 ** lacks the fcntl() system call. So redefine fcntl() to be something
23974 ** that always succeeds. This means that locking does not occur under
23975 ** DJGPP. But it is DOS - what did you expect?
23977 #ifdef __DJGPP__
23978 { "fstat", 0, 0 },
23979 #define osFstat(a,b,c) 0
23980 #else
23981 { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
23982 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23983 #endif
23985 { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
23986 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23988 { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
23989 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
23991 { "read", (sqlite3_syscall_ptr)read, 0 },
23992 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23994 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23995 { "pread", (sqlite3_syscall_ptr)pread, 0 },
23996 #else
23997 { "pread", (sqlite3_syscall_ptr)0, 0 },
23998 #endif
23999 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24001 #if defined(USE_PREAD64)
24002 { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
24003 #else
24004 { "pread64", (sqlite3_syscall_ptr)0, 0 },
24005 #endif
24006 #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24008 { "write", (sqlite3_syscall_ptr)write, 0 },
24009 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24011 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24012 { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
24013 #else
24014 { "pwrite", (sqlite3_syscall_ptr)0, 0 },
24015 #endif
24016 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
24017 aSyscall[12].pCurrent)
24019 #if defined(USE_PREAD64)
24020 { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
24021 #else
24022 { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
24023 #endif
24024 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
24025 aSyscall[13].pCurrent)
24027 { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
24028 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24030 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24031 { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
24032 #else
24033 { "fallocate", (sqlite3_syscall_ptr)0, 0 },
24034 #endif
24035 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24037 { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
24038 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
24040 { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
24041 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
24043 { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
24044 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
24046 { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
24047 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
24049 { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
24050 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
24052 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
24053 { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
24054 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
24056 { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
24057 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
24059 #if HAVE_MREMAP
24060 { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
24061 #else
24062 { "mremap", (sqlite3_syscall_ptr)0, 0 },
24063 #endif
24064 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
24065 #endif
24067 }; /* End of the overrideable system calls */
24070 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24071 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
24072 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24073 ** system call named zName.
24075 static int unixSetSystemCall(
24076 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
24077 const char *zName, /* Name of system call to override */
24078 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
24080 unsigned int i;
24081 int rc = SQLITE_NOTFOUND;
24083 UNUSED_PARAMETER(pNotUsed);
24084 if( zName==0 ){
24085 /* If no zName is given, restore all system calls to their default
24086 ** settings and return NULL
24088 rc = SQLITE_OK;
24089 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24090 if( aSyscall[i].pDefault ){
24091 aSyscall[i].pCurrent = aSyscall[i].pDefault;
24094 }else{
24095 /* If zName is specified, operate on only the one system call
24096 ** specified.
24098 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24099 if( strcmp(zName, aSyscall[i].zName)==0 ){
24100 if( aSyscall[i].pDefault==0 ){
24101 aSyscall[i].pDefault = aSyscall[i].pCurrent;
24103 rc = SQLITE_OK;
24104 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
24105 aSyscall[i].pCurrent = pNewFunc;
24106 break;
24110 return rc;
24114 ** Return the value of a system call. Return NULL if zName is not a
24115 ** recognized system call name. NULL is also returned if the system call
24116 ** is currently undefined.
24118 static sqlite3_syscall_ptr unixGetSystemCall(
24119 sqlite3_vfs *pNotUsed,
24120 const char *zName
24122 unsigned int i;
24124 UNUSED_PARAMETER(pNotUsed);
24125 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
24126 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
24128 return 0;
24132 ** Return the name of the first system call after zName. If zName==NULL
24133 ** then return the name of the first system call. Return NULL if zName
24134 ** is the last system call or if zName is not the name of a valid
24135 ** system call.
24137 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
24138 int i = -1;
24140 UNUSED_PARAMETER(p);
24141 if( zName ){
24142 for(i=0; i<ArraySize(aSyscall)-1; i++){
24143 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
24146 for(i++; i<ArraySize(aSyscall); i++){
24147 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
24149 return 0;
24153 ** Do not accept any file descriptor less than this value, in order to avoid
24154 ** opening database file using file descriptors that are commonly used for
24155 ** standard input, output, and error.
24157 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
24158 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
24159 #endif
24162 ** Invoke open(). Do so multiple times, until it either succeeds or
24163 ** fails for some reason other than EINTR.
24165 ** If the file creation mode "m" is 0 then set it to the default for
24166 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
24167 ** 0644) as modified by the system umask. If m is not 0, then
24168 ** make the file creation mode be exactly m ignoring the umask.
24170 ** The m parameter will be non-zero only when creating -wal, -journal,
24171 ** and -shm files. We want those files to have *exactly* the same
24172 ** permissions as their original database, unadulterated by the umask.
24173 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
24174 ** transaction crashes and leaves behind hot journals, then any
24175 ** process that is able to write to the database will also be able to
24176 ** recover the hot journals.
24178 static int robust_open(const char *z, int f, mode_t m){
24179 int fd;
24180 mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
24181 while(1){
24182 #if defined(O_CLOEXEC)
24183 fd = osOpen(z,f|O_CLOEXEC,m2);
24184 #else
24185 fd = osOpen(z,f,m2);
24186 #endif
24187 if( fd<0 ){
24188 if( errno==EINTR ) continue;
24189 break;
24191 if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
24192 osClose(fd);
24193 sqlite3_log(SQLITE_WARNING,
24194 "attempt to open \"%s\" as file descriptor %d", z, fd);
24195 fd = -1;
24196 if( osOpen("/dev/null", f, m)<0 ) break;
24198 if( fd>=0 ){
24199 if( m!=0 ){
24200 struct stat statbuf;
24201 if( osFstat(fd, &statbuf)==0
24202 && statbuf.st_size==0
24203 && (statbuf.st_mode&0777)!=m
24205 osFchmod(fd, m);
24208 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
24209 osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
24210 #endif
24212 return fd;
24216 ** Helper functions to obtain and relinquish the global mutex. The
24217 ** global mutex is used to protect the unixInodeInfo and
24218 ** vxworksFileId objects used by this file, all of which may be
24219 ** shared by multiple threads.
24221 ** Function unixMutexHeld() is used to assert() that the global mutex
24222 ** is held when required. This function is only used as part of assert()
24223 ** statements. e.g.
24225 ** unixEnterMutex()
24226 ** assert( unixMutexHeld() );
24227 ** unixEnterLeave()
24229 static void unixEnterMutex(void){
24230 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24232 static void unixLeaveMutex(void){
24233 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24235 #ifdef SQLITE_DEBUG
24236 static int unixMutexHeld(void) {
24237 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
24239 #endif
24242 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24244 ** Helper function for printing out trace information from debugging
24245 ** binaries. This returns the string represetation of the supplied
24246 ** integer lock-type.
24248 static const char *azFileLock(int eFileLock){
24249 switch( eFileLock ){
24250 case NO_LOCK: return "NONE";
24251 case SHARED_LOCK: return "SHARED";
24252 case RESERVED_LOCK: return "RESERVED";
24253 case PENDING_LOCK: return "PENDING";
24254 case EXCLUSIVE_LOCK: return "EXCLUSIVE";
24256 return "ERROR";
24258 #endif
24260 #ifdef SQLITE_LOCK_TRACE
24262 ** Print out information about all locking operations.
24264 ** This routine is used for troubleshooting locks on multithreaded
24265 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
24266 ** command-line option on the compiler. This code is normally
24267 ** turned off.
24269 static int lockTrace(int fd, int op, struct flock *p){
24270 char *zOpName, *zType;
24271 int s;
24272 int savedErrno;
24273 if( op==F_GETLK ){
24274 zOpName = "GETLK";
24275 }else if( op==F_SETLK ){
24276 zOpName = "SETLK";
24277 }else{
24278 s = osFcntl(fd, op, p);
24279 sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
24280 return s;
24282 if( p->l_type==F_RDLCK ){
24283 zType = "RDLCK";
24284 }else if( p->l_type==F_WRLCK ){
24285 zType = "WRLCK";
24286 }else if( p->l_type==F_UNLCK ){
24287 zType = "UNLCK";
24288 }else{
24289 assert( 0 );
24291 assert( p->l_whence==SEEK_SET );
24292 s = osFcntl(fd, op, p);
24293 savedErrno = errno;
24294 sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
24295 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
24296 (int)p->l_pid, s);
24297 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
24298 struct flock l2;
24299 l2 = *p;
24300 osFcntl(fd, F_GETLK, &l2);
24301 if( l2.l_type==F_RDLCK ){
24302 zType = "RDLCK";
24303 }else if( l2.l_type==F_WRLCK ){
24304 zType = "WRLCK";
24305 }else if( l2.l_type==F_UNLCK ){
24306 zType = "UNLCK";
24307 }else{
24308 assert( 0 );
24310 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
24311 zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
24313 errno = savedErrno;
24314 return s;
24316 #undef osFcntl
24317 #define osFcntl lockTrace
24318 #endif /* SQLITE_LOCK_TRACE */
24321 ** Retry ftruncate() calls that fail due to EINTR
24323 static int robust_ftruncate(int h, sqlite3_int64 sz){
24324 int rc;
24325 do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
24326 return rc;
24330 ** This routine translates a standard POSIX errno code into something
24331 ** useful to the clients of the sqlite3 functions. Specifically, it is
24332 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
24333 ** and a variety of "please close the file descriptor NOW" errors into
24334 ** SQLITE_IOERR
24336 ** Errors during initialization of locks, or file system support for locks,
24337 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
24339 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
24340 switch (posixError) {
24341 #if 0
24342 /* At one point this code was not commented out. In theory, this branch
24343 ** should never be hit, as this function should only be called after
24344 ** a locking-related function (i.e. fcntl()) has returned non-zero with
24345 ** the value of errno as the first argument. Since a system call has failed,
24346 ** errno should be non-zero.
24348 ** Despite this, if errno really is zero, we still don't want to return
24349 ** SQLITE_OK. The system call failed, and *some* SQLite error should be
24350 ** propagated back to the caller. Commenting this branch out means errno==0
24351 ** will be handled by the "default:" case below.
24353 case 0:
24354 return SQLITE_OK;
24355 #endif
24357 case EAGAIN:
24358 case ETIMEDOUT:
24359 case EBUSY:
24360 case EINTR:
24361 case ENOLCK:
24362 /* random NFS retry error, unless during file system support
24363 * introspection, in which it actually means what it says */
24364 return SQLITE_BUSY;
24366 case EACCES:
24367 /* EACCES is like EAGAIN during locking operations, but not any other time*/
24368 if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
24369 (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
24370 (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
24371 (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
24372 return SQLITE_BUSY;
24374 /* else fall through */
24375 case EPERM:
24376 return SQLITE_PERM;
24378 /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
24379 ** this module never makes such a call. And the code in SQLite itself
24380 ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
24381 ** this case is also commented out. If the system does set errno to EDEADLK,
24382 ** the default SQLITE_IOERR_XXX code will be returned. */
24383 #if 0
24384 case EDEADLK:
24385 return SQLITE_IOERR_BLOCKED;
24386 #endif
24388 #if EOPNOTSUPP!=ENOTSUP
24389 case EOPNOTSUPP:
24390 /* something went terribly awry, unless during file system support
24391 * introspection, in which it actually means what it says */
24392 #endif
24393 #ifdef ENOTSUP
24394 case ENOTSUP:
24395 /* invalid fd, unless during file system support introspection, in which
24396 * it actually means what it says */
24397 #endif
24398 case EIO:
24399 case EBADF:
24400 case EINVAL:
24401 case ENOTCONN:
24402 case ENODEV:
24403 case ENXIO:
24404 case ENOENT:
24405 #ifdef ESTALE /* ESTALE is not defined on Interix systems */
24406 case ESTALE:
24407 #endif
24408 case ENOSYS:
24409 /* these should force the client to close the file and reconnect */
24411 default:
24412 return sqliteIOErr;
24417 /******************************************************************************
24418 ****************** Begin Unique File ID Utility Used By VxWorks ***************
24420 ** On most versions of unix, we can get a unique ID for a file by concatenating
24421 ** the device number and the inode number. But this does not work on VxWorks.
24422 ** On VxWorks, a unique file id must be based on the canonical filename.
24424 ** A pointer to an instance of the following structure can be used as a
24425 ** unique file ID in VxWorks. Each instance of this structure contains
24426 ** a copy of the canonical filename. There is also a reference count.
24427 ** The structure is reclaimed when the number of pointers to it drops to
24428 ** zero.
24430 ** There are never very many files open at one time and lookups are not
24431 ** a performance-critical path, so it is sufficient to put these
24432 ** structures on a linked list.
24434 struct vxworksFileId {
24435 struct vxworksFileId *pNext; /* Next in a list of them all */
24436 int nRef; /* Number of references to this one */
24437 int nName; /* Length of the zCanonicalName[] string */
24438 char *zCanonicalName; /* Canonical filename */
24441 #if OS_VXWORKS
24443 ** All unique filenames are held on a linked list headed by this
24444 ** variable:
24446 static struct vxworksFileId *vxworksFileList = 0;
24449 ** Simplify a filename into its canonical form
24450 ** by making the following changes:
24452 ** * removing any trailing and duplicate /
24453 ** * convert /./ into just /
24454 ** * convert /A/../ where A is any simple name into just /
24456 ** Changes are made in-place. Return the new name length.
24458 ** The original filename is in z[0..n-1]. Return the number of
24459 ** characters in the simplified name.
24461 static int vxworksSimplifyName(char *z, int n){
24462 int i, j;
24463 while( n>1 && z[n-1]=='/' ){ n--; }
24464 for(i=j=0; i<n; i++){
24465 if( z[i]=='/' ){
24466 if( z[i+1]=='/' ) continue;
24467 if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
24468 i += 1;
24469 continue;
24471 if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
24472 while( j>0 && z[j-1]!='/' ){ j--; }
24473 if( j>0 ){ j--; }
24474 i += 2;
24475 continue;
24478 z[j++] = z[i];
24480 z[j] = 0;
24481 return j;
24485 ** Find a unique file ID for the given absolute pathname. Return
24486 ** a pointer to the vxworksFileId object. This pointer is the unique
24487 ** file ID.
24489 ** The nRef field of the vxworksFileId object is incremented before
24490 ** the object is returned. A new vxworksFileId object is created
24491 ** and added to the global list if necessary.
24493 ** If a memory allocation error occurs, return NULL.
24495 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
24496 struct vxworksFileId *pNew; /* search key and new file ID */
24497 struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
24498 int n; /* Length of zAbsoluteName string */
24500 assert( zAbsoluteName[0]=='/' );
24501 n = (int)strlen(zAbsoluteName);
24502 pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
24503 if( pNew==0 ) return 0;
24504 pNew->zCanonicalName = (char*)&pNew[1];
24505 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
24506 n = vxworksSimplifyName(pNew->zCanonicalName, n);
24508 /* Search for an existing entry that matching the canonical name.
24509 ** If found, increment the reference count and return a pointer to
24510 ** the existing file ID.
24512 unixEnterMutex();
24513 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
24514 if( pCandidate->nName==n
24515 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
24517 sqlite3_free(pNew);
24518 pCandidate->nRef++;
24519 unixLeaveMutex();
24520 return pCandidate;
24524 /* No match was found. We will make a new file ID */
24525 pNew->nRef = 1;
24526 pNew->nName = n;
24527 pNew->pNext = vxworksFileList;
24528 vxworksFileList = pNew;
24529 unixLeaveMutex();
24530 return pNew;
24534 ** Decrement the reference count on a vxworksFileId object. Free
24535 ** the object when the reference count reaches zero.
24537 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24538 unixEnterMutex();
24539 assert( pId->nRef>0 );
24540 pId->nRef--;
24541 if( pId->nRef==0 ){
24542 struct vxworksFileId **pp;
24543 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24544 assert( *pp==pId );
24545 *pp = pId->pNext;
24546 sqlite3_free(pId);
24548 unixLeaveMutex();
24550 #endif /* OS_VXWORKS */
24551 /*************** End of Unique File ID Utility Used By VxWorks ****************
24552 ******************************************************************************/
24555 /******************************************************************************
24556 *************************** Posix Advisory Locking ****************************
24558 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
24559 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24560 ** sets or clears a lock, that operation overrides any prior locks set
24561 ** by the same process. It does not explicitly say so, but this implies
24562 ** that it overrides locks set by the same process using a different
24563 ** file descriptor. Consider this test case:
24565 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24566 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24568 ** Suppose ./file1 and ./file2 are really the same file (because
24569 ** one is a hard or symbolic link to the other) then if you set
24570 ** an exclusive lock on fd1, then try to get an exclusive lock
24571 ** on fd2, it works. I would have expected the second lock to
24572 ** fail since there was already a lock on the file due to fd1.
24573 ** But not so. Since both locks came from the same process, the
24574 ** second overrides the first, even though they were on different
24575 ** file descriptors opened on different file names.
24577 ** This means that we cannot use POSIX locks to synchronize file access
24578 ** among competing threads of the same process. POSIX locks will work fine
24579 ** to synchronize access for threads in separate processes, but not
24580 ** threads within the same process.
24582 ** To work around the problem, SQLite has to manage file locks internally
24583 ** on its own. Whenever a new database is opened, we have to find the
24584 ** specific inode of the database file (the inode is determined by the
24585 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24586 ** and check for locks already existing on that inode. When locks are
24587 ** created or removed, we have to look at our own internal record of the
24588 ** locks to see if another thread has previously set a lock on that same
24589 ** inode.
24591 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24592 ** For VxWorks, we have to use the alternative unique ID system based on
24593 ** canonical filename and implemented in the previous division.)
24595 ** The sqlite3_file structure for POSIX is no longer just an integer file
24596 ** descriptor. It is now a structure that holds the integer file
24597 ** descriptor and a pointer to a structure that describes the internal
24598 ** locks on the corresponding inode. There is one locking structure
24599 ** per inode, so if the same inode is opened twice, both unixFile structures
24600 ** point to the same locking structure. The locking structure keeps
24601 ** a reference count (so we will know when to delete it) and a "cnt"
24602 ** field that tells us its internal lock status. cnt==0 means the
24603 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
24604 ** cnt>0 means there are cnt shared locks on the file.
24606 ** Any attempt to lock or unlock a file first checks the locking
24607 ** structure. The fcntl() system call is only invoked to set a
24608 ** POSIX lock if the internal lock structure transitions between
24609 ** a locked and an unlocked state.
24611 ** But wait: there are yet more problems with POSIX advisory locks.
24613 ** If you close a file descriptor that points to a file that has locks,
24614 ** all locks on that file that are owned by the current process are
24615 ** released. To work around this problem, each unixInodeInfo object
24616 ** maintains a count of the number of pending locks on tha inode.
24617 ** When an attempt is made to close an unixFile, if there are
24618 ** other unixFile open on the same inode that are holding locks, the call
24619 ** to close() the file descriptor is deferred until all of the locks clear.
24620 ** The unixInodeInfo structure keeps a list of file descriptors that need to
24621 ** be closed and that list is walked (and cleared) when the last lock
24622 ** clears.
24624 ** Yet another problem: LinuxThreads do not play well with posix locks.
24626 ** Many older versions of linux use the LinuxThreads library which is
24627 ** not posix compliant. Under LinuxThreads, a lock created by thread
24628 ** A cannot be modified or overridden by a different thread B.
24629 ** Only thread A can modify the lock. Locking behavior is correct
24630 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
24631 ** on linux - with NPTL a lock created by thread A can override locks
24632 ** in thread B. But there is no way to know at compile-time which
24633 ** threading library is being used. So there is no way to know at
24634 ** compile-time whether or not thread A can override locks on thread B.
24635 ** One has to do a run-time check to discover the behavior of the
24636 ** current process.
24638 ** SQLite used to support LinuxThreads. But support for LinuxThreads
24639 ** was dropped beginning with version 3.7.0. SQLite will still work with
24640 ** LinuxThreads provided that (1) there is no more than one connection
24641 ** per database file in the same process and (2) database connections
24642 ** do not move across threads.
24646 ** An instance of the following structure serves as the key used
24647 ** to locate a particular unixInodeInfo object.
24649 struct unixFileId {
24650 dev_t dev; /* Device number */
24651 #if OS_VXWORKS
24652 struct vxworksFileId *pId; /* Unique file ID for vxworks. */
24653 #else
24654 ino_t ino; /* Inode number */
24655 #endif
24659 ** An instance of the following structure is allocated for each open
24660 ** inode. Or, on LinuxThreads, there is one of these structures for
24661 ** each inode opened by each thread.
24663 ** A single inode can have multiple file descriptors, so each unixFile
24664 ** structure contains a pointer to an instance of this object and this
24665 ** object keeps a count of the number of unixFile pointing to it.
24667 struct unixInodeInfo {
24668 struct unixFileId fileId; /* The lookup key */
24669 int nShared; /* Number of SHARED locks held */
24670 unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
24671 unsigned char bProcessLock; /* An exclusive process lock is held */
24672 int nRef; /* Number of pointers to this structure */
24673 unixShmNode *pShmNode; /* Shared memory associated with this inode */
24674 int nLock; /* Number of outstanding file locks */
24675 UnixUnusedFd *pUnused; /* Unused file descriptors to close */
24676 unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
24677 unixInodeInfo *pPrev; /* .... doubly linked */
24678 #if SQLITE_ENABLE_LOCKING_STYLE
24679 unsigned long long sharedByte; /* for AFP simulated shared lock */
24680 #endif
24681 #if OS_VXWORKS
24682 sem_t *pSem; /* Named POSIX semaphore */
24683 char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
24684 #endif
24688 ** A lists of all unixInodeInfo objects.
24690 static unixInodeInfo *inodeList = 0;
24694 ** This function - unixLogError_x(), is only ever called via the macro
24695 ** unixLogError().
24697 ** It is invoked after an error occurs in an OS function and errno has been
24698 ** set. It logs a message using sqlite3_log() containing the current value of
24699 ** errno and, if possible, the human-readable equivalent from strerror() or
24700 ** strerror_r().
24702 ** The first argument passed to the macro should be the error code that
24703 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
24704 ** The two subsequent arguments should be the name of the OS function that
24705 ** failed (e.g. "unlink", "open") and the associated file-system path,
24706 ** if any.
24708 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
24709 static int unixLogErrorAtLine(
24710 int errcode, /* SQLite error code */
24711 const char *zFunc, /* Name of OS function that failed */
24712 const char *zPath, /* File path associated with error */
24713 int iLine /* Source line number where error occurred */
24715 char *zErr; /* Message from strerror() or equivalent */
24716 int iErrno = errno; /* Saved syscall error number */
24718 /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24719 ** the strerror() function to obtain the human-readable error message
24720 ** equivalent to errno. Otherwise, use strerror_r().
24722 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24723 char aErr[80];
24724 memset(aErr, 0, sizeof(aErr));
24725 zErr = aErr;
24727 /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24728 ** assume that the system provides the GNU version of strerror_r() that
24729 ** returns a pointer to a buffer containing the error message. That pointer
24730 ** may point to aErr[], or it may point to some static storage somewhere.
24731 ** Otherwise, assume that the system provides the POSIX version of
24732 ** strerror_r(), which always writes an error message into aErr[].
24734 ** If the code incorrectly assumes that it is the POSIX version that is
24735 ** available, the error message will often be an empty string. Not a
24736 ** huge problem. Incorrectly concluding that the GNU version is available
24737 ** could lead to a segfault though.
24739 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24740 zErr =
24741 # endif
24742 strerror_r(iErrno, aErr, sizeof(aErr)-1);
24744 #elif SQLITE_THREADSAFE
24745 /* This is a threadsafe build, but strerror_r() is not available. */
24746 zErr = "";
24747 #else
24748 /* Non-threadsafe build, use strerror(). */
24749 zErr = strerror(iErrno);
24750 #endif
24752 if( zPath==0 ) zPath = "";
24753 sqlite3_log(errcode,
24754 "os_unix.c:%d: (%d) %s(%s) - %s",
24755 iLine, iErrno, zFunc, zPath, zErr
24758 return errcode;
24762 ** Close a file descriptor.
24764 ** We assume that close() almost always works, since it is only in a
24765 ** very sick application or on a very sick platform that it might fail.
24766 ** If it does fail, simply leak the file descriptor, but do log the
24767 ** error.
24769 ** Note that it is not safe to retry close() after EINTR since the
24770 ** file descriptor might have already been reused by another thread.
24771 ** So we don't even try to recover from an EINTR. Just log the error
24772 ** and move on.
24774 static void robust_close(unixFile *pFile, int h, int lineno){
24775 if( osClose(h) ){
24776 unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24777 pFile ? pFile->zPath : 0, lineno);
24782 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24784 static void closePendingFds(unixFile *pFile){
24785 unixInodeInfo *pInode = pFile->pInode;
24786 UnixUnusedFd *p;
24787 UnixUnusedFd *pNext;
24788 for(p=pInode->pUnused; p; p=pNext){
24789 pNext = p->pNext;
24790 robust_close(pFile, p->fd, __LINE__);
24791 sqlite3_free(p);
24793 pInode->pUnused = 0;
24797 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24799 ** The mutex entered using the unixEnterMutex() function must be held
24800 ** when this function is called.
24802 static void releaseInodeInfo(unixFile *pFile){
24803 unixInodeInfo *pInode = pFile->pInode;
24804 assert( unixMutexHeld() );
24805 if( ALWAYS(pInode) ){
24806 pInode->nRef--;
24807 if( pInode->nRef==0 ){
24808 assert( pInode->pShmNode==0 );
24809 closePendingFds(pFile);
24810 if( pInode->pPrev ){
24811 assert( pInode->pPrev->pNext==pInode );
24812 pInode->pPrev->pNext = pInode->pNext;
24813 }else{
24814 assert( inodeList==pInode );
24815 inodeList = pInode->pNext;
24817 if( pInode->pNext ){
24818 assert( pInode->pNext->pPrev==pInode );
24819 pInode->pNext->pPrev = pInode->pPrev;
24821 sqlite3_free(pInode);
24827 ** Given a file descriptor, locate the unixInodeInfo object that
24828 ** describes that file descriptor. Create a new one if necessary. The
24829 ** return value might be uninitialized if an error occurs.
24831 ** The mutex entered using the unixEnterMutex() function must be held
24832 ** when this function is called.
24834 ** Return an appropriate error code.
24836 static int findInodeInfo(
24837 unixFile *pFile, /* Unix file with file desc used in the key */
24838 unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
24840 int rc; /* System call return code */
24841 int fd; /* The file descriptor for pFile */
24842 struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
24843 struct stat statbuf; /* Low-level file information */
24844 unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
24846 assert( unixMutexHeld() );
24848 /* Get low-level information about the file that we can used to
24849 ** create a unique name for the file.
24851 fd = pFile->h;
24852 rc = osFstat(fd, &statbuf);
24853 if( rc!=0 ){
24854 pFile->lastErrno = errno;
24855 #ifdef EOVERFLOW
24856 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24857 #endif
24858 return SQLITE_IOERR;
24861 #ifdef __APPLE__
24862 /* On OS X on an msdos filesystem, the inode number is reported
24863 ** incorrectly for zero-size files. See ticket #3260. To work
24864 ** around this problem (we consider it a bug in OS X, not SQLite)
24865 ** we always increase the file size to 1 by writing a single byte
24866 ** prior to accessing the inode number. The one byte written is
24867 ** an ASCII 'S' character which also happens to be the first byte
24868 ** in the header of every SQLite database. In this way, if there
24869 ** is a race condition such that another thread has already populated
24870 ** the first page of the database, no damage is done.
24872 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24873 do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24874 if( rc!=1 ){
24875 pFile->lastErrno = errno;
24876 return SQLITE_IOERR;
24878 rc = osFstat(fd, &statbuf);
24879 if( rc!=0 ){
24880 pFile->lastErrno = errno;
24881 return SQLITE_IOERR;
24884 #endif
24886 memset(&fileId, 0, sizeof(fileId));
24887 fileId.dev = statbuf.st_dev;
24888 #if OS_VXWORKS
24889 fileId.pId = pFile->pId;
24890 #else
24891 fileId.ino = statbuf.st_ino;
24892 #endif
24893 pInode = inodeList;
24894 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24895 pInode = pInode->pNext;
24897 if( pInode==0 ){
24898 pInode = sqlite3_malloc( sizeof(*pInode) );
24899 if( pInode==0 ){
24900 return SQLITE_NOMEM;
24902 memset(pInode, 0, sizeof(*pInode));
24903 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24904 pInode->nRef = 1;
24905 pInode->pNext = inodeList;
24906 pInode->pPrev = 0;
24907 if( inodeList ) inodeList->pPrev = pInode;
24908 inodeList = pInode;
24909 }else{
24910 pInode->nRef++;
24912 *ppInode = pInode;
24913 return SQLITE_OK;
24917 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
24919 static int fileHasMoved(unixFile *pFile){
24920 struct stat buf;
24921 return pFile->pInode!=0 &&
24922 (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
24927 ** Check a unixFile that is a database. Verify the following:
24929 ** (1) There is exactly one hard link on the file
24930 ** (2) The file is not a symbolic link
24931 ** (3) The file has not been renamed or unlinked
24933 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
24935 static void verifyDbFile(unixFile *pFile){
24936 struct stat buf;
24937 int rc;
24938 if( pFile->ctrlFlags & UNIXFILE_WARNED ){
24939 /* One or more of the following warnings have already been issued. Do not
24940 ** repeat them so as not to clutter the error log */
24941 return;
24943 rc = osFstat(pFile->h, &buf);
24944 if( rc!=0 ){
24945 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
24946 pFile->ctrlFlags |= UNIXFILE_WARNED;
24947 return;
24949 if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
24950 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
24951 pFile->ctrlFlags |= UNIXFILE_WARNED;
24952 return;
24954 if( buf.st_nlink>1 ){
24955 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
24956 pFile->ctrlFlags |= UNIXFILE_WARNED;
24957 return;
24959 if( fileHasMoved(pFile) ){
24960 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
24961 pFile->ctrlFlags |= UNIXFILE_WARNED;
24962 return;
24968 ** This routine checks if there is a RESERVED lock held on the specified
24969 ** file by this or any other process. If such a lock is held, set *pResOut
24970 ** to a non-zero value otherwise *pResOut is set to zero. The return value
24971 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24973 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24974 int rc = SQLITE_OK;
24975 int reserved = 0;
24976 unixFile *pFile = (unixFile*)id;
24978 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24980 assert( pFile );
24981 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24983 /* Check if a thread in this process holds such a lock */
24984 if( pFile->pInode->eFileLock>SHARED_LOCK ){
24985 reserved = 1;
24988 /* Otherwise see if some other process holds it.
24990 #ifndef __DJGPP__
24991 if( !reserved && !pFile->pInode->bProcessLock ){
24992 struct flock lock;
24993 lock.l_whence = SEEK_SET;
24994 lock.l_start = RESERVED_BYTE;
24995 lock.l_len = 1;
24996 lock.l_type = F_WRLCK;
24997 if( osFcntl(pFile->h, F_GETLK, &lock) ){
24998 rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24999 pFile->lastErrno = errno;
25000 } else if( lock.l_type!=F_UNLCK ){
25001 reserved = 1;
25004 #endif
25006 unixLeaveMutex();
25007 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25009 *pResOut = reserved;
25010 return rc;
25014 ** Attempt to set a system-lock on the file pFile. The lock is
25015 ** described by pLock.
25017 ** If the pFile was opened read/write from unix-excl, then the only lock
25018 ** ever obtained is an exclusive lock, and it is obtained exactly once
25019 ** the first time any lock is attempted. All subsequent system locking
25020 ** operations become no-ops. Locking operations still happen internally,
25021 ** in order to coordinate access between separate database connections
25022 ** within this process, but all of that is handled in memory and the
25023 ** operating system does not participate.
25025 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25026 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25027 ** and is read-only.
25029 ** Zero is returned if the call completes successfully, or -1 if a call
25030 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25032 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25033 int rc;
25034 unixInodeInfo *pInode = pFile->pInode;
25035 assert( unixMutexHeld() );
25036 assert( pInode!=0 );
25037 if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25038 && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25040 if( pInode->bProcessLock==0 ){
25041 struct flock lock;
25042 assert( pInode->nLock==0 );
25043 lock.l_whence = SEEK_SET;
25044 lock.l_start = SHARED_FIRST;
25045 lock.l_len = SHARED_SIZE;
25046 lock.l_type = F_WRLCK;
25047 rc = osFcntl(pFile->h, F_SETLK, &lock);
25048 if( rc<0 ) return rc;
25049 pInode->bProcessLock = 1;
25050 pInode->nLock++;
25051 }else{
25052 rc = 0;
25054 }else{
25055 rc = osFcntl(pFile->h, F_SETLK, pLock);
25057 return rc;
25061 ** Lock the file with the lock specified by parameter eFileLock - one
25062 ** of the following:
25064 ** (1) SHARED_LOCK
25065 ** (2) RESERVED_LOCK
25066 ** (3) PENDING_LOCK
25067 ** (4) EXCLUSIVE_LOCK
25069 ** Sometimes when requesting one lock state, additional lock states
25070 ** are inserted in between. The locking might fail on one of the later
25071 ** transitions leaving the lock state different from what it started but
25072 ** still short of its goal. The following chart shows the allowed
25073 ** transitions and the inserted intermediate states:
25075 ** UNLOCKED -> SHARED
25076 ** SHARED -> RESERVED
25077 ** SHARED -> (PENDING) -> EXCLUSIVE
25078 ** RESERVED -> (PENDING) -> EXCLUSIVE
25079 ** PENDING -> EXCLUSIVE
25081 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25082 ** routine to lower a locking level.
25084 static int unixLock(sqlite3_file *id, int eFileLock){
25085 /* The following describes the implementation of the various locks and
25086 ** lock transitions in terms of the POSIX advisory shared and exclusive
25087 ** lock primitives (called read-locks and write-locks below, to avoid
25088 ** confusion with SQLite lock names). The algorithms are complicated
25089 ** slightly in order to be compatible with windows systems simultaneously
25090 ** accessing the same database file, in case that is ever required.
25092 ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25093 ** byte', each single bytes at well known offsets, and the 'shared byte
25094 ** range', a range of 510 bytes at a well known offset.
25096 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25097 ** byte'. If this is successful, a random byte from the 'shared byte
25098 ** range' is read-locked and the lock on the 'pending byte' released.
25100 ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25101 ** A RESERVED lock is implemented by grabbing a write-lock on the
25102 ** 'reserved byte'.
25104 ** A process may only obtain a PENDING lock after it has obtained a
25105 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25106 ** on the 'pending byte'. This ensures that no new SHARED locks can be
25107 ** obtained, but existing SHARED locks are allowed to persist. A process
25108 ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25109 ** This property is used by the algorithm for rolling back a journal file
25110 ** after a crash.
25112 ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25113 ** implemented by obtaining a write-lock on the entire 'shared byte
25114 ** range'. Since all other locks require a read-lock on one of the bytes
25115 ** within this range, this ensures that no other locks are held on the
25116 ** database.
25118 ** The reason a single byte cannot be used instead of the 'shared byte
25119 ** range' is that some versions of windows do not support read-locks. By
25120 ** locking a random byte from a range, concurrent SHARED locks may exist
25121 ** even if the locking primitive used is always a write-lock.
25123 int rc = SQLITE_OK;
25124 unixFile *pFile = (unixFile*)id;
25125 unixInodeInfo *pInode;
25126 struct flock lock;
25127 int tErrno = 0;
25129 assert( pFile );
25130 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25131 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25132 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
25134 /* If there is already a lock of this type or more restrictive on the
25135 ** unixFile, do nothing. Don't use the end_lock: exit path, as
25136 ** unixEnterMutex() hasn't been called yet.
25138 if( pFile->eFileLock>=eFileLock ){
25139 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
25140 azFileLock(eFileLock)));
25141 return SQLITE_OK;
25144 /* Make sure the locking sequence is correct.
25145 ** (1) We never move from unlocked to anything higher than shared lock.
25146 ** (2) SQLite never explicitly requests a pendig lock.
25147 ** (3) A shared lock is always held when a reserve lock is requested.
25149 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25150 assert( eFileLock!=PENDING_LOCK );
25151 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25153 /* This mutex is needed because pFile->pInode is shared across threads
25155 unixEnterMutex();
25156 pInode = pFile->pInode;
25158 /* If some thread using this PID has a lock via a different unixFile*
25159 ** handle that precludes the requested lock, return BUSY.
25161 if( (pFile->eFileLock!=pInode->eFileLock &&
25162 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25164 rc = SQLITE_BUSY;
25165 goto end_lock;
25168 /* If a SHARED lock is requested, and some thread using this PID already
25169 ** has a SHARED or RESERVED lock, then increment reference counts and
25170 ** return SQLITE_OK.
25172 if( eFileLock==SHARED_LOCK &&
25173 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25174 assert( eFileLock==SHARED_LOCK );
25175 assert( pFile->eFileLock==0 );
25176 assert( pInode->nShared>0 );
25177 pFile->eFileLock = SHARED_LOCK;
25178 pInode->nShared++;
25179 pInode->nLock++;
25180 goto end_lock;
25184 /* A PENDING lock is needed before acquiring a SHARED lock and before
25185 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
25186 ** be released.
25188 lock.l_len = 1L;
25189 lock.l_whence = SEEK_SET;
25190 if( eFileLock==SHARED_LOCK
25191 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25193 lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
25194 lock.l_start = PENDING_BYTE;
25195 if( unixFileLock(pFile, &lock) ){
25196 tErrno = errno;
25197 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25198 if( rc!=SQLITE_BUSY ){
25199 pFile->lastErrno = tErrno;
25201 goto end_lock;
25206 /* If control gets to this point, then actually go ahead and make
25207 ** operating system calls for the specified lock.
25209 if( eFileLock==SHARED_LOCK ){
25210 assert( pInode->nShared==0 );
25211 assert( pInode->eFileLock==0 );
25212 assert( rc==SQLITE_OK );
25214 /* Now get the read-lock */
25215 lock.l_start = SHARED_FIRST;
25216 lock.l_len = SHARED_SIZE;
25217 if( unixFileLock(pFile, &lock) ){
25218 tErrno = errno;
25219 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25222 /* Drop the temporary PENDING lock */
25223 lock.l_start = PENDING_BYTE;
25224 lock.l_len = 1L;
25225 lock.l_type = F_UNLCK;
25226 if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
25227 /* This could happen with a network mount */
25228 tErrno = errno;
25229 rc = SQLITE_IOERR_UNLOCK;
25232 if( rc ){
25233 if( rc!=SQLITE_BUSY ){
25234 pFile->lastErrno = tErrno;
25236 goto end_lock;
25237 }else{
25238 pFile->eFileLock = SHARED_LOCK;
25239 pInode->nLock++;
25240 pInode->nShared = 1;
25242 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25243 /* We are trying for an exclusive lock but another thread in this
25244 ** same process is still holding a shared lock. */
25245 rc = SQLITE_BUSY;
25246 }else{
25247 /* The request was for a RESERVED or EXCLUSIVE lock. It is
25248 ** assumed that there is a SHARED or greater lock on the file
25249 ** already.
25251 assert( 0!=pFile->eFileLock );
25252 lock.l_type = F_WRLCK;
25254 assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
25255 if( eFileLock==RESERVED_LOCK ){
25256 lock.l_start = RESERVED_BYTE;
25257 lock.l_len = 1L;
25258 }else{
25259 lock.l_start = SHARED_FIRST;
25260 lock.l_len = SHARED_SIZE;
25263 if( unixFileLock(pFile, &lock) ){
25264 tErrno = errno;
25265 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25266 if( rc!=SQLITE_BUSY ){
25267 pFile->lastErrno = tErrno;
25273 #ifdef SQLITE_DEBUG
25274 /* Set up the transaction-counter change checking flags when
25275 ** transitioning from a SHARED to a RESERVED lock. The change
25276 ** from SHARED to RESERVED marks the beginning of a normal
25277 ** write operation (not a hot journal rollback).
25279 if( rc==SQLITE_OK
25280 && pFile->eFileLock<=SHARED_LOCK
25281 && eFileLock==RESERVED_LOCK
25283 pFile->transCntrChng = 0;
25284 pFile->dbUpdate = 0;
25285 pFile->inNormalWrite = 1;
25287 #endif
25290 if( rc==SQLITE_OK ){
25291 pFile->eFileLock = eFileLock;
25292 pInode->eFileLock = eFileLock;
25293 }else if( eFileLock==EXCLUSIVE_LOCK ){
25294 pFile->eFileLock = PENDING_LOCK;
25295 pInode->eFileLock = PENDING_LOCK;
25298 end_lock:
25299 unixLeaveMutex();
25300 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
25301 rc==SQLITE_OK ? "ok" : "failed"));
25302 return rc;
25306 ** Add the file descriptor used by file handle pFile to the corresponding
25307 ** pUnused list.
25309 static void setPendingFd(unixFile *pFile){
25310 unixInodeInfo *pInode = pFile->pInode;
25311 UnixUnusedFd *p = pFile->pUnused;
25312 p->pNext = pInode->pUnused;
25313 pInode->pUnused = p;
25314 pFile->h = -1;
25315 pFile->pUnused = 0;
25319 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25320 ** must be either NO_LOCK or SHARED_LOCK.
25322 ** If the locking level of the file descriptor is already at or below
25323 ** the requested locking level, this routine is a no-op.
25325 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
25326 ** the byte range is divided into 2 parts and the first part is unlocked then
25327 ** set to a read lock, then the other part is simply unlocked. This works
25328 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
25329 ** remove the write lock on a region when a read lock is set.
25331 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
25332 unixFile *pFile = (unixFile*)id;
25333 unixInodeInfo *pInode;
25334 struct flock lock;
25335 int rc = SQLITE_OK;
25337 assert( pFile );
25338 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
25339 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
25340 getpid()));
25342 assert( eFileLock<=SHARED_LOCK );
25343 if( pFile->eFileLock<=eFileLock ){
25344 return SQLITE_OK;
25346 unixEnterMutex();
25347 pInode = pFile->pInode;
25348 assert( pInode->nShared!=0 );
25349 if( pFile->eFileLock>SHARED_LOCK ){
25350 assert( pInode->eFileLock==pFile->eFileLock );
25352 #ifdef SQLITE_DEBUG
25353 /* When reducing a lock such that other processes can start
25354 ** reading the database file again, make sure that the
25355 ** transaction counter was updated if any part of the database
25356 ** file changed. If the transaction counter is not updated,
25357 ** other connections to the same file might not realize that
25358 ** the file has changed and hence might not know to flush their
25359 ** cache. The use of a stale cache can lead to database corruption.
25361 pFile->inNormalWrite = 0;
25362 #endif
25364 /* downgrading to a shared lock on NFS involves clearing the write lock
25365 ** before establishing the readlock - to avoid a race condition we downgrade
25366 ** the lock in 2 blocks, so that part of the range will be covered by a
25367 ** write lock until the rest is covered by a read lock:
25368 ** 1: [WWWWW]
25369 ** 2: [....W]
25370 ** 3: [RRRRW]
25371 ** 4: [RRRR.]
25373 if( eFileLock==SHARED_LOCK ){
25375 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
25376 (void)handleNFSUnlock;
25377 assert( handleNFSUnlock==0 );
25378 #endif
25379 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25380 if( handleNFSUnlock ){
25381 int tErrno; /* Error code from system call errors */
25382 off_t divSize = SHARED_SIZE - 1;
25384 lock.l_type = F_UNLCK;
25385 lock.l_whence = SEEK_SET;
25386 lock.l_start = SHARED_FIRST;
25387 lock.l_len = divSize;
25388 if( unixFileLock(pFile, &lock)==(-1) ){
25389 tErrno = errno;
25390 rc = SQLITE_IOERR_UNLOCK;
25391 if( IS_LOCK_ERROR(rc) ){
25392 pFile->lastErrno = tErrno;
25394 goto end_unlock;
25396 lock.l_type = F_RDLCK;
25397 lock.l_whence = SEEK_SET;
25398 lock.l_start = SHARED_FIRST;
25399 lock.l_len = divSize;
25400 if( unixFileLock(pFile, &lock)==(-1) ){
25401 tErrno = errno;
25402 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
25403 if( IS_LOCK_ERROR(rc) ){
25404 pFile->lastErrno = tErrno;
25406 goto end_unlock;
25408 lock.l_type = F_UNLCK;
25409 lock.l_whence = SEEK_SET;
25410 lock.l_start = SHARED_FIRST+divSize;
25411 lock.l_len = SHARED_SIZE-divSize;
25412 if( unixFileLock(pFile, &lock)==(-1) ){
25413 tErrno = errno;
25414 rc = SQLITE_IOERR_UNLOCK;
25415 if( IS_LOCK_ERROR(rc) ){
25416 pFile->lastErrno = tErrno;
25418 goto end_unlock;
25420 }else
25421 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25423 lock.l_type = F_RDLCK;
25424 lock.l_whence = SEEK_SET;
25425 lock.l_start = SHARED_FIRST;
25426 lock.l_len = SHARED_SIZE;
25427 if( unixFileLock(pFile, &lock) ){
25428 /* In theory, the call to unixFileLock() cannot fail because another
25429 ** process is holding an incompatible lock. If it does, this
25430 ** indicates that the other process is not following the locking
25431 ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
25432 ** SQLITE_BUSY would confuse the upper layer (in practice it causes
25433 ** an assert to fail). */
25434 rc = SQLITE_IOERR_RDLOCK;
25435 pFile->lastErrno = errno;
25436 goto end_unlock;
25440 lock.l_type = F_UNLCK;
25441 lock.l_whence = SEEK_SET;
25442 lock.l_start = PENDING_BYTE;
25443 lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
25444 if( unixFileLock(pFile, &lock)==0 ){
25445 pInode->eFileLock = SHARED_LOCK;
25446 }else{
25447 rc = SQLITE_IOERR_UNLOCK;
25448 pFile->lastErrno = errno;
25449 goto end_unlock;
25452 if( eFileLock==NO_LOCK ){
25453 /* Decrement the shared lock counter. Release the lock using an
25454 ** OS call only when all threads in this same process have released
25455 ** the lock.
25457 pInode->nShared--;
25458 if( pInode->nShared==0 ){
25459 lock.l_type = F_UNLCK;
25460 lock.l_whence = SEEK_SET;
25461 lock.l_start = lock.l_len = 0L;
25462 if( unixFileLock(pFile, &lock)==0 ){
25463 pInode->eFileLock = NO_LOCK;
25464 }else{
25465 rc = SQLITE_IOERR_UNLOCK;
25466 pFile->lastErrno = errno;
25467 pInode->eFileLock = NO_LOCK;
25468 pFile->eFileLock = NO_LOCK;
25472 /* Decrement the count of locks against this same file. When the
25473 ** count reaches zero, close any other file descriptors whose close
25474 ** was deferred because of outstanding locks.
25476 pInode->nLock--;
25477 assert( pInode->nLock>=0 );
25478 if( pInode->nLock==0 ){
25479 closePendingFds(pFile);
25483 end_unlock:
25484 unixLeaveMutex();
25485 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
25486 return rc;
25490 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25491 ** must be either NO_LOCK or SHARED_LOCK.
25493 ** If the locking level of the file descriptor is already at or below
25494 ** the requested locking level, this routine is a no-op.
25496 static int unixUnlock(sqlite3_file *id, int eFileLock){
25497 #if SQLITE_MAX_MMAP_SIZE>0
25498 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
25499 #endif
25500 return posixUnlock(id, eFileLock, 0);
25503 #if SQLITE_MAX_MMAP_SIZE>0
25504 static int unixMapfile(unixFile *pFd, i64 nByte);
25505 static void unixUnmapfile(unixFile *pFd);
25506 #endif
25509 ** This function performs the parts of the "close file" operation
25510 ** common to all locking schemes. It closes the directory and file
25511 ** handles, if they are valid, and sets all fields of the unixFile
25512 ** structure to 0.
25514 ** It is *not* necessary to hold the mutex when this routine is called,
25515 ** even on VxWorks. A mutex will be acquired on VxWorks by the
25516 ** vxworksReleaseFileId() routine.
25518 static int closeUnixFile(sqlite3_file *id){
25519 unixFile *pFile = (unixFile*)id;
25520 #if SQLITE_MAX_MMAP_SIZE>0
25521 unixUnmapfile(pFile);
25522 #endif
25523 if( pFile->h>=0 ){
25524 robust_close(pFile, pFile->h, __LINE__);
25525 pFile->h = -1;
25527 #if OS_VXWORKS
25528 if( pFile->pId ){
25529 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
25530 osUnlink(pFile->pId->zCanonicalName);
25532 vxworksReleaseFileId(pFile->pId);
25533 pFile->pId = 0;
25535 #endif
25536 OSTRACE(("CLOSE %-3d\n", pFile->h));
25537 OpenCounter(-1);
25538 sqlite3_free(pFile->pUnused);
25539 memset(pFile, 0, sizeof(unixFile));
25540 return SQLITE_OK;
25544 ** Close a file.
25546 static int unixClose(sqlite3_file *id){
25547 int rc = SQLITE_OK;
25548 unixFile *pFile = (unixFile *)id;
25549 verifyDbFile(pFile);
25550 unixUnlock(id, NO_LOCK);
25551 unixEnterMutex();
25553 /* unixFile.pInode is always valid here. Otherwise, a different close
25554 ** routine (e.g. nolockClose()) would be called instead.
25556 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25557 if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25558 /* If there are outstanding locks, do not actually close the file just
25559 ** yet because that would clear those locks. Instead, add the file
25560 ** descriptor to pInode->pUnused list. It will be automatically closed
25561 ** when the last lock is cleared.
25563 setPendingFd(pFile);
25565 releaseInodeInfo(pFile);
25566 rc = closeUnixFile(id);
25567 unixLeaveMutex();
25568 return rc;
25571 /************** End of the posix advisory lock implementation *****************
25572 ******************************************************************************/
25574 /******************************************************************************
25575 ****************************** No-op Locking **********************************
25577 ** Of the various locking implementations available, this is by far the
25578 ** simplest: locking is ignored. No attempt is made to lock the database
25579 ** file for reading or writing.
25581 ** This locking mode is appropriate for use on read-only databases
25582 ** (ex: databases that are burned into CD-ROM, for example.) It can
25583 ** also be used if the application employs some external mechanism to
25584 ** prevent simultaneous access of the same database by two or more
25585 ** database connections. But there is a serious risk of database
25586 ** corruption if this locking mode is used in situations where multiple
25587 ** database connections are accessing the same database file at the same
25588 ** time and one or more of those connections are writing.
25591 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25592 UNUSED_PARAMETER(NotUsed);
25593 *pResOut = 0;
25594 return SQLITE_OK;
25596 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25597 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25598 return SQLITE_OK;
25600 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25601 UNUSED_PARAMETER2(NotUsed, NotUsed2);
25602 return SQLITE_OK;
25606 ** Close the file.
25608 static int nolockClose(sqlite3_file *id) {
25609 return closeUnixFile(id);
25612 /******************* End of the no-op lock implementation *********************
25613 ******************************************************************************/
25615 /******************************************************************************
25616 ************************* Begin dot-file Locking ******************************
25618 ** The dotfile locking implementation uses the existence of separate lock
25619 ** files (really a directory) to control access to the database. This works
25620 ** on just about every filesystem imaginable. But there are serious downsides:
25622 ** (1) There is zero concurrency. A single reader blocks all other
25623 ** connections from reading or writing the database.
25625 ** (2) An application crash or power loss can leave stale lock files
25626 ** sitting around that need to be cleared manually.
25628 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25629 ** other locking strategy is available.
25631 ** Dotfile locking works by creating a subdirectory in the same directory as
25632 ** the database and with the same name but with a ".lock" extension added.
25633 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
25634 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25638 ** The file suffix added to the data base filename in order to create the
25639 ** lock directory.
25641 #define DOTLOCK_SUFFIX ".lock"
25644 ** This routine checks if there is a RESERVED lock held on the specified
25645 ** file by this or any other process. If such a lock is held, set *pResOut
25646 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25647 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25649 ** In dotfile locking, either a lock exists or it does not. So in this
25650 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
25651 ** is held on the file and false if the file is unlocked.
25653 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25654 int rc = SQLITE_OK;
25655 int reserved = 0;
25656 unixFile *pFile = (unixFile*)id;
25658 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25660 assert( pFile );
25662 /* Check if a thread in this process holds such a lock */
25663 if( pFile->eFileLock>SHARED_LOCK ){
25664 /* Either this connection or some other connection in the same process
25665 ** holds a lock on the file. No need to check further. */
25666 reserved = 1;
25667 }else{
25668 /* The lock is held if and only if the lockfile exists */
25669 const char *zLockFile = (const char*)pFile->lockingContext;
25670 reserved = osAccess(zLockFile, 0)==0;
25672 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
25673 *pResOut = reserved;
25674 return rc;
25678 ** Lock the file with the lock specified by parameter eFileLock - one
25679 ** of the following:
25681 ** (1) SHARED_LOCK
25682 ** (2) RESERVED_LOCK
25683 ** (3) PENDING_LOCK
25684 ** (4) EXCLUSIVE_LOCK
25686 ** Sometimes when requesting one lock state, additional lock states
25687 ** are inserted in between. The locking might fail on one of the later
25688 ** transitions leaving the lock state different from what it started but
25689 ** still short of its goal. The following chart shows the allowed
25690 ** transitions and the inserted intermediate states:
25692 ** UNLOCKED -> SHARED
25693 ** SHARED -> RESERVED
25694 ** SHARED -> (PENDING) -> EXCLUSIVE
25695 ** RESERVED -> (PENDING) -> EXCLUSIVE
25696 ** PENDING -> EXCLUSIVE
25698 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25699 ** routine to lower a locking level.
25701 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
25702 ** But we track the other locking levels internally.
25704 static int dotlockLock(sqlite3_file *id, int eFileLock) {
25705 unixFile *pFile = (unixFile*)id;
25706 char *zLockFile = (char *)pFile->lockingContext;
25707 int rc = SQLITE_OK;
25710 /* If we have any lock, then the lock file already exists. All we have
25711 ** to do is adjust our internal record of the lock level.
25713 if( pFile->eFileLock > NO_LOCK ){
25714 pFile->eFileLock = eFileLock;
25715 /* Always update the timestamp on the old file */
25716 #ifdef HAVE_UTIME
25717 utime(zLockFile, NULL);
25718 #else
25719 utimes(zLockFile, NULL);
25720 #endif
25721 return SQLITE_OK;
25724 /* grab an exclusive lock */
25725 rc = osMkdir(zLockFile, 0777);
25726 if( rc<0 ){
25727 /* failed to open/create the lock directory */
25728 int tErrno = errno;
25729 if( EEXIST == tErrno ){
25730 rc = SQLITE_BUSY;
25731 } else {
25732 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25733 if( IS_LOCK_ERROR(rc) ){
25734 pFile->lastErrno = tErrno;
25737 return rc;
25740 /* got it, set the type and return ok */
25741 pFile->eFileLock = eFileLock;
25742 return rc;
25746 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25747 ** must be either NO_LOCK or SHARED_LOCK.
25749 ** If the locking level of the file descriptor is already at or below
25750 ** the requested locking level, this routine is a no-op.
25752 ** When the locking level reaches NO_LOCK, delete the lock file.
25754 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
25755 unixFile *pFile = (unixFile*)id;
25756 char *zLockFile = (char *)pFile->lockingContext;
25757 int rc;
25759 assert( pFile );
25760 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
25761 pFile->eFileLock, getpid()));
25762 assert( eFileLock<=SHARED_LOCK );
25764 /* no-op if possible */
25765 if( pFile->eFileLock==eFileLock ){
25766 return SQLITE_OK;
25769 /* To downgrade to shared, simply update our internal notion of the
25770 ** lock state. No need to mess with the file on disk.
25772 if( eFileLock==SHARED_LOCK ){
25773 pFile->eFileLock = SHARED_LOCK;
25774 return SQLITE_OK;
25777 /* To fully unlock the database, delete the lock file */
25778 assert( eFileLock==NO_LOCK );
25779 rc = osRmdir(zLockFile);
25780 if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25781 if( rc<0 ){
25782 int tErrno = errno;
25783 rc = 0;
25784 if( ENOENT != tErrno ){
25785 rc = SQLITE_IOERR_UNLOCK;
25787 if( IS_LOCK_ERROR(rc) ){
25788 pFile->lastErrno = tErrno;
25790 return rc;
25792 pFile->eFileLock = NO_LOCK;
25793 return SQLITE_OK;
25797 ** Close a file. Make sure the lock has been released before closing.
25799 static int dotlockClose(sqlite3_file *id) {
25800 int rc = SQLITE_OK;
25801 if( id ){
25802 unixFile *pFile = (unixFile*)id;
25803 dotlockUnlock(id, NO_LOCK);
25804 sqlite3_free(pFile->lockingContext);
25805 rc = closeUnixFile(id);
25807 return rc;
25809 /****************** End of the dot-file lock implementation *******************
25810 ******************************************************************************/
25812 /******************************************************************************
25813 ************************** Begin flock Locking ********************************
25815 ** Use the flock() system call to do file locking.
25817 ** flock() locking is like dot-file locking in that the various
25818 ** fine-grain locking levels supported by SQLite are collapsed into
25819 ** a single exclusive lock. In other words, SHARED, RESERVED, and
25820 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
25821 ** still works when you do this, but concurrency is reduced since
25822 ** only a single process can be reading the database at a time.
25824 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25825 ** compiling for VXWORKS.
25827 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25830 ** Retry flock() calls that fail with EINTR
25832 #ifdef EINTR
25833 static int robust_flock(int fd, int op){
25834 int rc;
25835 do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25836 return rc;
25838 #else
25839 # define robust_flock(a,b) flock(a,b)
25840 #endif
25844 ** This routine checks if there is a RESERVED lock held on the specified
25845 ** file by this or any other process. If such a lock is held, set *pResOut
25846 ** to a non-zero value otherwise *pResOut is set to zero. The return value
25847 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25849 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25850 int rc = SQLITE_OK;
25851 int reserved = 0;
25852 unixFile *pFile = (unixFile*)id;
25854 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25856 assert( pFile );
25858 /* Check if a thread in this process holds such a lock */
25859 if( pFile->eFileLock>SHARED_LOCK ){
25860 reserved = 1;
25863 /* Otherwise see if some other process holds it. */
25864 if( !reserved ){
25865 /* attempt to get the lock */
25866 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25867 if( !lrc ){
25868 /* got the lock, unlock it */
25869 lrc = robust_flock(pFile->h, LOCK_UN);
25870 if ( lrc ) {
25871 int tErrno = errno;
25872 /* unlock failed with an error */
25873 lrc = SQLITE_IOERR_UNLOCK;
25874 if( IS_LOCK_ERROR(lrc) ){
25875 pFile->lastErrno = tErrno;
25876 rc = lrc;
25879 } else {
25880 int tErrno = errno;
25881 reserved = 1;
25882 /* someone else might have it reserved */
25883 lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25884 if( IS_LOCK_ERROR(lrc) ){
25885 pFile->lastErrno = tErrno;
25886 rc = lrc;
25890 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25892 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25893 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25894 rc = SQLITE_OK;
25895 reserved=1;
25897 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25898 *pResOut = reserved;
25899 return rc;
25903 ** Lock the file with the lock specified by parameter eFileLock - one
25904 ** of the following:
25906 ** (1) SHARED_LOCK
25907 ** (2) RESERVED_LOCK
25908 ** (3) PENDING_LOCK
25909 ** (4) EXCLUSIVE_LOCK
25911 ** Sometimes when requesting one lock state, additional lock states
25912 ** are inserted in between. The locking might fail on one of the later
25913 ** transitions leaving the lock state different from what it started but
25914 ** still short of its goal. The following chart shows the allowed
25915 ** transitions and the inserted intermediate states:
25917 ** UNLOCKED -> SHARED
25918 ** SHARED -> RESERVED
25919 ** SHARED -> (PENDING) -> EXCLUSIVE
25920 ** RESERVED -> (PENDING) -> EXCLUSIVE
25921 ** PENDING -> EXCLUSIVE
25923 ** flock() only really support EXCLUSIVE locks. We track intermediate
25924 ** lock states in the sqlite3_file structure, but all locks SHARED or
25925 ** above are really EXCLUSIVE locks and exclude all other processes from
25926 ** access the file.
25928 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
25929 ** routine to lower a locking level.
25931 static int flockLock(sqlite3_file *id, int eFileLock) {
25932 int rc = SQLITE_OK;
25933 unixFile *pFile = (unixFile*)id;
25935 assert( pFile );
25937 /* if we already have a lock, it is exclusive.
25938 ** Just adjust level and punt on outta here. */
25939 if (pFile->eFileLock > NO_LOCK) {
25940 pFile->eFileLock = eFileLock;
25941 return SQLITE_OK;
25944 /* grab an exclusive lock */
25946 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25947 int tErrno = errno;
25948 /* didn't get, must be busy */
25949 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25950 if( IS_LOCK_ERROR(rc) ){
25951 pFile->lastErrno = tErrno;
25953 } else {
25954 /* got it, set the type and return ok */
25955 pFile->eFileLock = eFileLock;
25957 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
25958 rc==SQLITE_OK ? "ok" : "failed"));
25959 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25960 if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25961 rc = SQLITE_BUSY;
25963 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25964 return rc;
25969 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
25970 ** must be either NO_LOCK or SHARED_LOCK.
25972 ** If the locking level of the file descriptor is already at or below
25973 ** the requested locking level, this routine is a no-op.
25975 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25976 unixFile *pFile = (unixFile*)id;
25978 assert( pFile );
25979 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25980 pFile->eFileLock, getpid()));
25981 assert( eFileLock<=SHARED_LOCK );
25983 /* no-op if possible */
25984 if( pFile->eFileLock==eFileLock ){
25985 return SQLITE_OK;
25988 /* shared can just be set because we always have an exclusive */
25989 if (eFileLock==SHARED_LOCK) {
25990 pFile->eFileLock = eFileLock;
25991 return SQLITE_OK;
25994 /* no, really, unlock. */
25995 if( robust_flock(pFile->h, LOCK_UN) ){
25996 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25997 return SQLITE_OK;
25998 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25999 return SQLITE_IOERR_UNLOCK;
26000 }else{
26001 pFile->eFileLock = NO_LOCK;
26002 return SQLITE_OK;
26007 ** Close a file.
26009 static int flockClose(sqlite3_file *id) {
26010 int rc = SQLITE_OK;
26011 if( id ){
26012 flockUnlock(id, NO_LOCK);
26013 rc = closeUnixFile(id);
26015 return rc;
26018 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26020 /******************* End of the flock lock implementation *********************
26021 ******************************************************************************/
26023 /******************************************************************************
26024 ************************ Begin Named Semaphore Locking ************************
26026 ** Named semaphore locking is only supported on VxWorks.
26028 ** Semaphore locking is like dot-lock and flock in that it really only
26029 ** supports EXCLUSIVE locking. Only a single process can read or write
26030 ** the database file at a time. This reduces potential concurrency, but
26031 ** makes the lock implementation much easier.
26033 #if OS_VXWORKS
26036 ** This routine checks if there is a RESERVED lock held on the specified
26037 ** file by this or any other process. If such a lock is held, set *pResOut
26038 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26039 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26041 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26042 int rc = SQLITE_OK;
26043 int reserved = 0;
26044 unixFile *pFile = (unixFile*)id;
26046 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26048 assert( pFile );
26050 /* Check if a thread in this process holds such a lock */
26051 if( pFile->eFileLock>SHARED_LOCK ){
26052 reserved = 1;
26055 /* Otherwise see if some other process holds it. */
26056 if( !reserved ){
26057 sem_t *pSem = pFile->pInode->pSem;
26058 struct stat statBuf;
26060 if( sem_trywait(pSem)==-1 ){
26061 int tErrno = errno;
26062 if( EAGAIN != tErrno ){
26063 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26064 pFile->lastErrno = tErrno;
26065 } else {
26066 /* someone else has the lock when we are in NO_LOCK */
26067 reserved = (pFile->eFileLock < SHARED_LOCK);
26069 }else{
26070 /* we could have it if we want it */
26071 sem_post(pSem);
26074 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26076 *pResOut = reserved;
26077 return rc;
26081 ** Lock the file with the lock specified by parameter eFileLock - one
26082 ** of the following:
26084 ** (1) SHARED_LOCK
26085 ** (2) RESERVED_LOCK
26086 ** (3) PENDING_LOCK
26087 ** (4) EXCLUSIVE_LOCK
26089 ** Sometimes when requesting one lock state, additional lock states
26090 ** are inserted in between. The locking might fail on one of the later
26091 ** transitions leaving the lock state different from what it started but
26092 ** still short of its goal. The following chart shows the allowed
26093 ** transitions and the inserted intermediate states:
26095 ** UNLOCKED -> SHARED
26096 ** SHARED -> RESERVED
26097 ** SHARED -> (PENDING) -> EXCLUSIVE
26098 ** RESERVED -> (PENDING) -> EXCLUSIVE
26099 ** PENDING -> EXCLUSIVE
26101 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
26102 ** lock states in the sqlite3_file structure, but all locks SHARED or
26103 ** above are really EXCLUSIVE locks and exclude all other processes from
26104 ** access the file.
26106 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26107 ** routine to lower a locking level.
26109 static int semLock(sqlite3_file *id, int eFileLock) {
26110 unixFile *pFile = (unixFile*)id;
26111 int fd;
26112 sem_t *pSem = pFile->pInode->pSem;
26113 int rc = SQLITE_OK;
26115 /* if we already have a lock, it is exclusive.
26116 ** Just adjust level and punt on outta here. */
26117 if (pFile->eFileLock > NO_LOCK) {
26118 pFile->eFileLock = eFileLock;
26119 rc = SQLITE_OK;
26120 goto sem_end_lock;
26123 /* lock semaphore now but bail out when already locked. */
26124 if( sem_trywait(pSem)==-1 ){
26125 rc = SQLITE_BUSY;
26126 goto sem_end_lock;
26129 /* got it, set the type and return ok */
26130 pFile->eFileLock = eFileLock;
26132 sem_end_lock:
26133 return rc;
26137 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26138 ** must be either NO_LOCK or SHARED_LOCK.
26140 ** If the locking level of the file descriptor is already at or below
26141 ** the requested locking level, this routine is a no-op.
26143 static int semUnlock(sqlite3_file *id, int eFileLock) {
26144 unixFile *pFile = (unixFile*)id;
26145 sem_t *pSem = pFile->pInode->pSem;
26147 assert( pFile );
26148 assert( pSem );
26149 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26150 pFile->eFileLock, getpid()));
26151 assert( eFileLock<=SHARED_LOCK );
26153 /* no-op if possible */
26154 if( pFile->eFileLock==eFileLock ){
26155 return SQLITE_OK;
26158 /* shared can just be set because we always have an exclusive */
26159 if (eFileLock==SHARED_LOCK) {
26160 pFile->eFileLock = eFileLock;
26161 return SQLITE_OK;
26164 /* no, really unlock. */
26165 if ( sem_post(pSem)==-1 ) {
26166 int rc, tErrno = errno;
26167 rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26168 if( IS_LOCK_ERROR(rc) ){
26169 pFile->lastErrno = tErrno;
26171 return rc;
26173 pFile->eFileLock = NO_LOCK;
26174 return SQLITE_OK;
26178 ** Close a file.
26180 static int semClose(sqlite3_file *id) {
26181 if( id ){
26182 unixFile *pFile = (unixFile*)id;
26183 semUnlock(id, NO_LOCK);
26184 assert( pFile );
26185 unixEnterMutex();
26186 releaseInodeInfo(pFile);
26187 unixLeaveMutex();
26188 closeUnixFile(id);
26190 return SQLITE_OK;
26193 #endif /* OS_VXWORKS */
26195 ** Named semaphore locking is only available on VxWorks.
26197 *************** End of the named semaphore lock implementation ****************
26198 ******************************************************************************/
26201 /******************************************************************************
26202 *************************** Begin AFP Locking *********************************
26204 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
26205 ** on Apple Macintosh computers - both OS9 and OSX.
26207 ** Third-party implementations of AFP are available. But this code here
26208 ** only works on OSX.
26211 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26213 ** The afpLockingContext structure contains all afp lock specific state
26215 typedef struct afpLockingContext afpLockingContext;
26216 struct afpLockingContext {
26217 int reserved;
26218 const char *dbPath; /* Name of the open file */
26221 struct ByteRangeLockPB2
26223 unsigned long long offset; /* offset to first byte to lock */
26224 unsigned long long length; /* nbr of bytes to lock */
26225 unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
26226 unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
26227 unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
26228 int fd; /* file desc to assoc this lock with */
26231 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
26234 ** This is a utility for setting or clearing a bit-range lock on an
26235 ** AFP filesystem.
26237 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
26239 static int afpSetLock(
26240 const char *path, /* Name of the file to be locked or unlocked */
26241 unixFile *pFile, /* Open file descriptor on path */
26242 unsigned long long offset, /* First byte to be locked */
26243 unsigned long long length, /* Number of bytes to lock */
26244 int setLockFlag /* True to set lock. False to clear lock */
26246 struct ByteRangeLockPB2 pb;
26247 int err;
26249 pb.unLockFlag = setLockFlag ? 0 : 1;
26250 pb.startEndFlag = 0;
26251 pb.offset = offset;
26252 pb.length = length;
26253 pb.fd = pFile->h;
26255 OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
26256 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
26257 offset, length));
26258 err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
26259 if ( err==-1 ) {
26260 int rc;
26261 int tErrno = errno;
26262 OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
26263 path, tErrno, strerror(tErrno)));
26264 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
26265 rc = SQLITE_BUSY;
26266 #else
26267 rc = sqliteErrorFromPosixError(tErrno,
26268 setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
26269 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
26270 if( IS_LOCK_ERROR(rc) ){
26271 pFile->lastErrno = tErrno;
26273 return rc;
26274 } else {
26275 return SQLITE_OK;
26280 ** This routine checks if there is a RESERVED lock held on the specified
26281 ** file by this or any other process. If such a lock is held, set *pResOut
26282 ** to a non-zero value otherwise *pResOut is set to zero. The return value
26283 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26285 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
26286 int rc = SQLITE_OK;
26287 int reserved = 0;
26288 unixFile *pFile = (unixFile*)id;
26289 afpLockingContext *context;
26291 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26293 assert( pFile );
26294 context = (afpLockingContext *) pFile->lockingContext;
26295 if( context->reserved ){
26296 *pResOut = 1;
26297 return SQLITE_OK;
26299 unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26301 /* Check if a thread in this process holds such a lock */
26302 if( pFile->pInode->eFileLock>SHARED_LOCK ){
26303 reserved = 1;
26306 /* Otherwise see if some other process holds it.
26308 if( !reserved ){
26309 /* lock the RESERVED byte */
26310 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26311 if( SQLITE_OK==lrc ){
26312 /* if we succeeded in taking the reserved lock, unlock it to restore
26313 ** the original state */
26314 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26315 } else {
26316 /* if we failed to get the lock then someone else must have it */
26317 reserved = 1;
26319 if( IS_LOCK_ERROR(lrc) ){
26320 rc=lrc;
26324 unixLeaveMutex();
26325 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
26327 *pResOut = reserved;
26328 return rc;
26332 ** Lock the file with the lock specified by parameter eFileLock - one
26333 ** of the following:
26335 ** (1) SHARED_LOCK
26336 ** (2) RESERVED_LOCK
26337 ** (3) PENDING_LOCK
26338 ** (4) EXCLUSIVE_LOCK
26340 ** Sometimes when requesting one lock state, additional lock states
26341 ** are inserted in between. The locking might fail on one of the later
26342 ** transitions leaving the lock state different from what it started but
26343 ** still short of its goal. The following chart shows the allowed
26344 ** transitions and the inserted intermediate states:
26346 ** UNLOCKED -> SHARED
26347 ** SHARED -> RESERVED
26348 ** SHARED -> (PENDING) -> EXCLUSIVE
26349 ** RESERVED -> (PENDING) -> EXCLUSIVE
26350 ** PENDING -> EXCLUSIVE
26352 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
26353 ** routine to lower a locking level.
26355 static int afpLock(sqlite3_file *id, int eFileLock){
26356 int rc = SQLITE_OK;
26357 unixFile *pFile = (unixFile*)id;
26358 unixInodeInfo *pInode = pFile->pInode;
26359 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26361 assert( pFile );
26362 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
26363 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26364 azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
26366 /* If there is already a lock of this type or more restrictive on the
26367 ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
26368 ** unixEnterMutex() hasn't been called yet.
26370 if( pFile->eFileLock>=eFileLock ){
26371 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
26372 azFileLock(eFileLock)));
26373 return SQLITE_OK;
26376 /* Make sure the locking sequence is correct
26377 ** (1) We never move from unlocked to anything higher than shared lock.
26378 ** (2) SQLite never explicitly requests a pendig lock.
26379 ** (3) A shared lock is always held when a reserve lock is requested.
26381 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26382 assert( eFileLock!=PENDING_LOCK );
26383 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26385 /* This mutex is needed because pFile->pInode is shared across threads
26387 unixEnterMutex();
26388 pInode = pFile->pInode;
26390 /* If some thread using this PID has a lock via a different unixFile*
26391 ** handle that precludes the requested lock, return BUSY.
26393 if( (pFile->eFileLock!=pInode->eFileLock &&
26394 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26396 rc = SQLITE_BUSY;
26397 goto afp_end_lock;
26400 /* If a SHARED lock is requested, and some thread using this PID already
26401 ** has a SHARED or RESERVED lock, then increment reference counts and
26402 ** return SQLITE_OK.
26404 if( eFileLock==SHARED_LOCK &&
26405 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26406 assert( eFileLock==SHARED_LOCK );
26407 assert( pFile->eFileLock==0 );
26408 assert( pInode->nShared>0 );
26409 pFile->eFileLock = SHARED_LOCK;
26410 pInode->nShared++;
26411 pInode->nLock++;
26412 goto afp_end_lock;
26415 /* A PENDING lock is needed before acquiring a SHARED lock and before
26416 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
26417 ** be released.
26419 if( eFileLock==SHARED_LOCK
26420 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26422 int failed;
26423 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
26424 if (failed) {
26425 rc = failed;
26426 goto afp_end_lock;
26430 /* If control gets to this point, then actually go ahead and make
26431 ** operating system calls for the specified lock.
26433 if( eFileLock==SHARED_LOCK ){
26434 int lrc1, lrc2, lrc1Errno = 0;
26435 long lk, mask;
26437 assert( pInode->nShared==0 );
26438 assert( pInode->eFileLock==0 );
26440 mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
26441 /* Now get the read-lock SHARED_LOCK */
26442 /* note that the quality of the randomness doesn't matter that much */
26443 lk = random();
26444 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
26445 lrc1 = afpSetLock(context->dbPath, pFile,
26446 SHARED_FIRST+pInode->sharedByte, 1, 1);
26447 if( IS_LOCK_ERROR(lrc1) ){
26448 lrc1Errno = pFile->lastErrno;
26450 /* Drop the temporary PENDING lock */
26451 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26453 if( IS_LOCK_ERROR(lrc1) ) {
26454 pFile->lastErrno = lrc1Errno;
26455 rc = lrc1;
26456 goto afp_end_lock;
26457 } else if( IS_LOCK_ERROR(lrc2) ){
26458 rc = lrc2;
26459 goto afp_end_lock;
26460 } else if( lrc1 != SQLITE_OK ) {
26461 rc = lrc1;
26462 } else {
26463 pFile->eFileLock = SHARED_LOCK;
26464 pInode->nLock++;
26465 pInode->nShared = 1;
26467 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26468 /* We are trying for an exclusive lock but another thread in this
26469 ** same process is still holding a shared lock. */
26470 rc = SQLITE_BUSY;
26471 }else{
26472 /* The request was for a RESERVED or EXCLUSIVE lock. It is
26473 ** assumed that there is a SHARED or greater lock on the file
26474 ** already.
26476 int failed = 0;
26477 assert( 0!=pFile->eFileLock );
26478 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
26479 /* Acquire a RESERVED lock */
26480 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
26481 if( !failed ){
26482 context->reserved = 1;
26485 if (!failed && eFileLock == EXCLUSIVE_LOCK) {
26486 /* Acquire an EXCLUSIVE lock */
26488 /* Remove the shared lock before trying the range. we'll need to
26489 ** reestablish the shared lock if we can't get the afpUnlock
26491 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
26492 pInode->sharedByte, 1, 0)) ){
26493 int failed2 = SQLITE_OK;
26494 /* now attemmpt to get the exclusive lock range */
26495 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
26496 SHARED_SIZE, 1);
26497 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
26498 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
26499 /* Can't reestablish the shared lock. Sqlite can't deal, this is
26500 ** a critical I/O error
26502 rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
26503 SQLITE_IOERR_LOCK;
26504 goto afp_end_lock;
26506 }else{
26507 rc = failed;
26510 if( failed ){
26511 rc = failed;
26515 if( rc==SQLITE_OK ){
26516 pFile->eFileLock = eFileLock;
26517 pInode->eFileLock = eFileLock;
26518 }else if( eFileLock==EXCLUSIVE_LOCK ){
26519 pFile->eFileLock = PENDING_LOCK;
26520 pInode->eFileLock = PENDING_LOCK;
26523 afp_end_lock:
26524 unixLeaveMutex();
26525 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
26526 rc==SQLITE_OK ? "ok" : "failed"));
26527 return rc;
26531 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26532 ** must be either NO_LOCK or SHARED_LOCK.
26534 ** If the locking level of the file descriptor is already at or below
26535 ** the requested locking level, this routine is a no-op.
26537 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26538 int rc = SQLITE_OK;
26539 unixFile *pFile = (unixFile*)id;
26540 unixInodeInfo *pInode;
26541 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26542 int skipShared = 0;
26543 #ifdef SQLITE_TEST
26544 int h = pFile->h;
26545 #endif
26547 assert( pFile );
26548 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26549 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26550 getpid()));
26552 assert( eFileLock<=SHARED_LOCK );
26553 if( pFile->eFileLock<=eFileLock ){
26554 return SQLITE_OK;
26556 unixEnterMutex();
26557 pInode = pFile->pInode;
26558 assert( pInode->nShared!=0 );
26559 if( pFile->eFileLock>SHARED_LOCK ){
26560 assert( pInode->eFileLock==pFile->eFileLock );
26561 SimulateIOErrorBenign(1);
26562 SimulateIOError( h=(-1) )
26563 SimulateIOErrorBenign(0);
26565 #ifdef SQLITE_DEBUG
26566 /* When reducing a lock such that other processes can start
26567 ** reading the database file again, make sure that the
26568 ** transaction counter was updated if any part of the database
26569 ** file changed. If the transaction counter is not updated,
26570 ** other connections to the same file might not realize that
26571 ** the file has changed and hence might not know to flush their
26572 ** cache. The use of a stale cache can lead to database corruption.
26574 assert( pFile->inNormalWrite==0
26575 || pFile->dbUpdate==0
26576 || pFile->transCntrChng==1 );
26577 pFile->inNormalWrite = 0;
26578 #endif
26580 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26581 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26582 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26583 /* only re-establish the shared lock if necessary */
26584 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26585 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26586 } else {
26587 skipShared = 1;
26590 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26591 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26593 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26594 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26595 if( !rc ){
26596 context->reserved = 0;
26599 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26600 pInode->eFileLock = SHARED_LOCK;
26603 if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26605 /* Decrement the shared lock counter. Release the lock using an
26606 ** OS call only when all threads in this same process have released
26607 ** the lock.
26609 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26610 pInode->nShared--;
26611 if( pInode->nShared==0 ){
26612 SimulateIOErrorBenign(1);
26613 SimulateIOError( h=(-1) )
26614 SimulateIOErrorBenign(0);
26615 if( !skipShared ){
26616 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26618 if( !rc ){
26619 pInode->eFileLock = NO_LOCK;
26620 pFile->eFileLock = NO_LOCK;
26623 if( rc==SQLITE_OK ){
26624 pInode->nLock--;
26625 assert( pInode->nLock>=0 );
26626 if( pInode->nLock==0 ){
26627 closePendingFds(pFile);
26632 unixLeaveMutex();
26633 if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26634 return rc;
26638 ** Close a file & cleanup AFP specific locking context
26640 static int afpClose(sqlite3_file *id) {
26641 int rc = SQLITE_OK;
26642 if( id ){
26643 unixFile *pFile = (unixFile*)id;
26644 afpUnlock(id, NO_LOCK);
26645 unixEnterMutex();
26646 if( pFile->pInode && pFile->pInode->nLock ){
26647 /* If there are outstanding locks, do not actually close the file just
26648 ** yet because that would clear those locks. Instead, add the file
26649 ** descriptor to pInode->aPending. It will be automatically closed when
26650 ** the last lock is cleared.
26652 setPendingFd(pFile);
26654 releaseInodeInfo(pFile);
26655 sqlite3_free(pFile->lockingContext);
26656 rc = closeUnixFile(id);
26657 unixLeaveMutex();
26659 return rc;
26662 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26664 ** The code above is the AFP lock implementation. The code is specific
26665 ** to MacOSX and does not work on other unix platforms. No alternative
26666 ** is available. If you don't compile for a mac, then the "unix-afp"
26667 ** VFS is not available.
26669 ********************* End of the AFP lock implementation **********************
26670 ******************************************************************************/
26672 /******************************************************************************
26673 *************************** Begin NFS Locking ********************************/
26675 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26677 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
26678 ** must be either NO_LOCK or SHARED_LOCK.
26680 ** If the locking level of the file descriptor is already at or below
26681 ** the requested locking level, this routine is a no-op.
26683 static int nfsUnlock(sqlite3_file *id, int eFileLock){
26684 return posixUnlock(id, eFileLock, 1);
26687 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26689 ** The code above is the NFS lock implementation. The code is specific
26690 ** to MacOSX and does not work on other unix platforms. No alternative
26691 ** is available.
26693 ********************* End of the NFS lock implementation **********************
26694 ******************************************************************************/
26696 /******************************************************************************
26697 **************** Non-locking sqlite3_file methods *****************************
26699 ** The next division contains implementations for all methods of the
26700 ** sqlite3_file object other than the locking methods. The locking
26701 ** methods were defined in divisions above (one locking method per
26702 ** division). Those methods that are common to all locking modes
26703 ** are gather together into this division.
26707 ** Seek to the offset passed as the second argument, then read cnt
26708 ** bytes into pBuf. Return the number of bytes actually read.
26710 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
26711 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
26712 ** one system to another. Since SQLite does not define USE_PREAD
26713 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
26714 ** See tickets #2741 and #2681.
26716 ** To avoid stomping the errno value on a failed read the lastErrno value
26717 ** is set before returning.
26719 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
26720 int got;
26721 int prior = 0;
26722 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26723 i64 newOffset;
26724 #endif
26725 TIMER_START;
26726 assert( cnt==(cnt&0x1ffff) );
26727 assert( id->h>2 );
26728 cnt &= 0x1ffff;
26730 #if defined(USE_PREAD)
26731 got = osPread(id->h, pBuf, cnt, offset);
26732 SimulateIOError( got = -1 );
26733 #elif defined(USE_PREAD64)
26734 got = osPread64(id->h, pBuf, cnt, offset);
26735 SimulateIOError( got = -1 );
26736 #else
26737 newOffset = lseek(id->h, offset, SEEK_SET);
26738 SimulateIOError( newOffset-- );
26739 if( newOffset!=offset ){
26740 if( newOffset == -1 ){
26741 ((unixFile*)id)->lastErrno = errno;
26742 }else{
26743 ((unixFile*)id)->lastErrno = 0;
26745 return -1;
26747 got = osRead(id->h, pBuf, cnt);
26748 #endif
26749 if( got==cnt ) break;
26750 if( got<0 ){
26751 if( errno==EINTR ){ got = 1; continue; }
26752 prior = 0;
26753 ((unixFile*)id)->lastErrno = errno;
26754 break;
26755 }else if( got>0 ){
26756 cnt -= got;
26757 offset += got;
26758 prior += got;
26759 pBuf = (void*)(got + (char*)pBuf);
26761 }while( got>0 );
26762 TIMER_END;
26763 OSTRACE(("READ %-3d %5d %7lld %llu\n",
26764 id->h, got+prior, offset-prior, TIMER_ELAPSED));
26765 return got+prior;
26769 ** Read data from a file into a buffer. Return SQLITE_OK if all
26770 ** bytes were read successfully and SQLITE_IOERR if anything goes
26771 ** wrong.
26773 static int unixRead(
26774 sqlite3_file *id,
26775 void *pBuf,
26776 int amt,
26777 sqlite3_int64 offset
26779 unixFile *pFile = (unixFile *)id;
26780 int got;
26781 assert( id );
26782 assert( offset>=0 );
26783 assert( amt>0 );
26785 /* If this is a database file (not a journal, master-journal or temp
26786 ** file), the bytes in the locking range should never be read or written. */
26787 #if 0
26788 assert( pFile->pUnused==0
26789 || offset>=PENDING_BYTE+512
26790 || offset+amt<=PENDING_BYTE
26792 #endif
26794 #if SQLITE_MAX_MMAP_SIZE>0
26795 /* Deal with as much of this read request as possible by transfering
26796 ** data from the memory mapping using memcpy(). */
26797 if( offset<pFile->mmapSize ){
26798 if( offset+amt <= pFile->mmapSize ){
26799 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
26800 return SQLITE_OK;
26801 }else{
26802 int nCopy = pFile->mmapSize - offset;
26803 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
26804 pBuf = &((u8 *)pBuf)[nCopy];
26805 amt -= nCopy;
26806 offset += nCopy;
26809 #endif
26811 got = seekAndRead(pFile, offset, pBuf, amt);
26812 if( got==amt ){
26813 return SQLITE_OK;
26814 }else if( got<0 ){
26815 /* lastErrno set by seekAndRead */
26816 return SQLITE_IOERR_READ;
26817 }else{
26818 pFile->lastErrno = 0; /* not a system error */
26819 /* Unread parts of the buffer must be zero-filled */
26820 memset(&((char*)pBuf)[got], 0, amt-got);
26821 return SQLITE_IOERR_SHORT_READ;
26826 ** Attempt to seek the file-descriptor passed as the first argument to
26827 ** absolute offset iOff, then attempt to write nBuf bytes of data from
26828 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
26829 ** return the actual number of bytes written (which may be less than
26830 ** nBuf).
26832 static int seekAndWriteFd(
26833 int fd, /* File descriptor to write to */
26834 i64 iOff, /* File offset to begin writing at */
26835 const void *pBuf, /* Copy data from this buffer to the file */
26836 int nBuf, /* Size of buffer pBuf in bytes */
26837 int *piErrno /* OUT: Error number if error occurs */
26839 int rc = 0; /* Value returned by system call */
26841 assert( nBuf==(nBuf&0x1ffff) );
26842 assert( fd>2 );
26843 nBuf &= 0x1ffff;
26844 TIMER_START;
26846 #if defined(USE_PREAD)
26847 do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
26848 #elif defined(USE_PREAD64)
26849 do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
26850 #else
26852 i64 iSeek = lseek(fd, iOff, SEEK_SET);
26853 SimulateIOError( iSeek-- );
26855 if( iSeek!=iOff ){
26856 if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
26857 return -1;
26859 rc = osWrite(fd, pBuf, nBuf);
26860 }while( rc<0 && errno==EINTR );
26861 #endif
26863 TIMER_END;
26864 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
26866 if( rc<0 && piErrno ) *piErrno = errno;
26867 return rc;
26872 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
26873 ** Return the number of bytes actually read. Update the offset.
26875 ** To avoid stomping the errno value on a failed write the lastErrno value
26876 ** is set before returning.
26878 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26879 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
26884 ** Write data from a buffer into a file. Return SQLITE_OK on success
26885 ** or some other error code on failure.
26887 static int unixWrite(
26888 sqlite3_file *id,
26889 const void *pBuf,
26890 int amt,
26891 sqlite3_int64 offset
26893 unixFile *pFile = (unixFile*)id;
26894 int wrote = 0;
26895 assert( id );
26896 assert( amt>0 );
26898 /* If this is a database file (not a journal, master-journal or temp
26899 ** file), the bytes in the locking range should never be read or written. */
26900 #if 0
26901 assert( pFile->pUnused==0
26902 || offset>=PENDING_BYTE+512
26903 || offset+amt<=PENDING_BYTE
26905 #endif
26907 #ifdef SQLITE_DEBUG
26908 /* If we are doing a normal write to a database file (as opposed to
26909 ** doing a hot-journal rollback or a write to some file other than a
26910 ** normal database file) then record the fact that the database
26911 ** has changed. If the transaction counter is modified, record that
26912 ** fact too.
26914 if( pFile->inNormalWrite ){
26915 pFile->dbUpdate = 1; /* The database has been modified */
26916 if( offset<=24 && offset+amt>=27 ){
26917 int rc;
26918 char oldCntr[4];
26919 SimulateIOErrorBenign(1);
26920 rc = seekAndRead(pFile, 24, oldCntr, 4);
26921 SimulateIOErrorBenign(0);
26922 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26923 pFile->transCntrChng = 1; /* The transaction counter has changed */
26927 #endif
26929 #if SQLITE_MAX_MMAP_SIZE>0
26930 /* Deal with as much of this write request as possible by transfering
26931 ** data from the memory mapping using memcpy(). */
26932 if( offset<pFile->mmapSize ){
26933 if( offset+amt <= pFile->mmapSize ){
26934 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
26935 return SQLITE_OK;
26936 }else{
26937 int nCopy = pFile->mmapSize - offset;
26938 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
26939 pBuf = &((u8 *)pBuf)[nCopy];
26940 amt -= nCopy;
26941 offset += nCopy;
26944 #endif
26946 while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26947 amt -= wrote;
26948 offset += wrote;
26949 pBuf = &((char*)pBuf)[wrote];
26951 SimulateIOError(( wrote=(-1), amt=1 ));
26952 SimulateDiskfullError(( wrote=0, amt=1 ));
26954 if( amt>0 ){
26955 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26956 /* lastErrno set by seekAndWrite */
26957 return SQLITE_IOERR_WRITE;
26958 }else{
26959 pFile->lastErrno = 0; /* not a system error */
26960 return SQLITE_FULL;
26964 return SQLITE_OK;
26967 #ifdef SQLITE_TEST
26969 ** Count the number of fullsyncs and normal syncs. This is used to test
26970 ** that syncs and fullsyncs are occurring at the right times.
26972 SQLITE_API int sqlite3_sync_count = 0;
26973 SQLITE_API int sqlite3_fullsync_count = 0;
26974 #endif
26977 ** We do not trust systems to provide a working fdatasync(). Some do.
26978 ** Others do no. To be safe, we will stick with the (slightly slower)
26979 ** fsync(). If you know that your system does support fdatasync() correctly,
26980 ** then simply compile with -Dfdatasync=fdatasync
26982 #if !defined(fdatasync)
26983 # define fdatasync fsync
26984 #endif
26987 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26988 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
26989 ** only available on Mac OS X. But that could change.
26991 #ifdef F_FULLFSYNC
26992 # define HAVE_FULLFSYNC 1
26993 #else
26994 # define HAVE_FULLFSYNC 0
26995 #endif
26999 ** The fsync() system call does not work as advertised on many
27000 ** unix systems. The following procedure is an attempt to make
27001 ** it work better.
27003 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
27004 ** for testing when we want to run through the test suite quickly.
27005 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27006 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27007 ** or power failure will likely corrupt the database file.
27009 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27010 ** The idea behind dataOnly is that it should only write the file content
27011 ** to disk, not the inode. We only set dataOnly if the file size is
27012 ** unchanged since the file size is part of the inode. However,
27013 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27014 ** file size has changed. The only real difference between fdatasync()
27015 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27016 ** inode if the mtime or owner or other inode attributes have changed.
27017 ** We only care about the file size, not the other file attributes, so
27018 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27019 ** So, we always use fdatasync() if it is available, regardless of
27020 ** the value of the dataOnly flag.
27022 static int full_fsync(int fd, int fullSync, int dataOnly){
27023 int rc;
27025 /* The following "ifdef/elif/else/" block has the same structure as
27026 ** the one below. It is replicated here solely to avoid cluttering
27027 ** up the real code with the UNUSED_PARAMETER() macros.
27029 #ifdef SQLITE_NO_SYNC
27030 UNUSED_PARAMETER(fd);
27031 UNUSED_PARAMETER(fullSync);
27032 UNUSED_PARAMETER(dataOnly);
27033 #elif HAVE_FULLFSYNC
27034 UNUSED_PARAMETER(dataOnly);
27035 #else
27036 UNUSED_PARAMETER(fullSync);
27037 UNUSED_PARAMETER(dataOnly);
27038 #endif
27040 /* Record the number of times that we do a normal fsync() and
27041 ** FULLSYNC. This is used during testing to verify that this procedure
27042 ** gets called with the correct arguments.
27044 #ifdef SQLITE_TEST
27045 if( fullSync ) sqlite3_fullsync_count++;
27046 sqlite3_sync_count++;
27047 #endif
27049 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27050 ** no-op
27052 #ifdef SQLITE_NO_SYNC
27053 rc = SQLITE_OK;
27054 #elif HAVE_FULLFSYNC
27055 if( fullSync ){
27056 rc = osFcntl(fd, F_FULLFSYNC, 0);
27057 }else{
27058 rc = 1;
27060 /* If the FULLFSYNC failed, fall back to attempting an fsync().
27061 ** It shouldn't be possible for fullfsync to fail on the local
27062 ** file system (on OSX), so failure indicates that FULLFSYNC
27063 ** isn't supported for this file system. So, attempt an fsync
27064 ** and (for now) ignore the overhead of a superfluous fcntl call.
27065 ** It'd be better to detect fullfsync support once and avoid
27066 ** the fcntl call every time sync is called.
27068 if( rc ) rc = fsync(fd);
27070 #elif defined(__APPLE__)
27071 /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27072 ** so currently we default to the macro that redefines fdatasync to fsync
27074 rc = fsync(fd);
27075 #else
27076 rc = fdatasync(fd);
27077 #if OS_VXWORKS
27078 if( rc==-1 && errno==ENOTSUP ){
27079 rc = fsync(fd);
27081 #endif /* OS_VXWORKS */
27082 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27084 if( OS_VXWORKS && rc!= -1 ){
27085 rc = 0;
27087 return rc;
27091 ** Open a file descriptor to the directory containing file zFilename.
27092 ** If successful, *pFd is set to the opened file descriptor and
27093 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27094 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27095 ** value.
27097 ** The directory file descriptor is used for only one thing - to
27098 ** fsync() a directory to make sure file creation and deletion events
27099 ** are flushed to disk. Such fsyncs are not needed on newer
27100 ** journaling filesystems, but are required on older filesystems.
27102 ** This routine can be overridden using the xSetSysCall interface.
27103 ** The ability to override this routine was added in support of the
27104 ** chromium sandbox. Opening a directory is a security risk (we are
27105 ** told) so making it overrideable allows the chromium sandbox to
27106 ** replace this routine with a harmless no-op. To make this routine
27107 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27108 ** *pFd set to a negative number.
27110 ** If SQLITE_OK is returned, the caller is responsible for closing
27111 ** the file descriptor *pFd using close().
27113 static int openDirectory(const char *zFilename, int *pFd){
27114 int ii;
27115 int fd = -1;
27116 char zDirname[MAX_PATHNAME+1];
27118 sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27119 for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27120 if( ii>0 ){
27121 zDirname[ii] = '\0';
27122 fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27123 if( fd>=0 ){
27124 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27127 *pFd = fd;
27128 return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27132 ** Make sure all writes to a particular file are committed to disk.
27134 ** If dataOnly==0 then both the file itself and its metadata (file
27135 ** size, access time, etc) are synced. If dataOnly!=0 then only the
27136 ** file data is synced.
27138 ** Under Unix, also make sure that the directory entry for the file
27139 ** has been created by fsync-ing the directory that contains the file.
27140 ** If we do not do this and we encounter a power failure, the directory
27141 ** entry for the journal might not exist after we reboot. The next
27142 ** SQLite to access the file will not know that the journal exists (because
27143 ** the directory entry for the journal was never created) and the transaction
27144 ** will not roll back - possibly leading to database corruption.
27146 static int unixSync(sqlite3_file *id, int flags){
27147 int rc;
27148 unixFile *pFile = (unixFile*)id;
27150 int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27151 int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27153 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27154 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27155 || (flags&0x0F)==SQLITE_SYNC_FULL
27158 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27159 ** line is to test that doing so does not cause any problems.
27161 SimulateDiskfullError( return SQLITE_FULL );
27163 assert( pFile );
27164 OSTRACE(("SYNC %-3d\n", pFile->h));
27165 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27166 SimulateIOError( rc=1 );
27167 if( rc ){
27168 pFile->lastErrno = errno;
27169 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27172 /* Also fsync the directory containing the file if the DIRSYNC flag
27173 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
27174 ** are unable to fsync a directory, so ignore errors on the fsync.
27176 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27177 int dirfd;
27178 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27179 HAVE_FULLFSYNC, isFullsync));
27180 rc = osOpenDirectory(pFile->zPath, &dirfd);
27181 if( rc==SQLITE_OK && dirfd>=0 ){
27182 full_fsync(dirfd, 0, 0);
27183 robust_close(pFile, dirfd, __LINE__);
27184 }else if( rc==SQLITE_CANTOPEN ){
27185 rc = SQLITE_OK;
27187 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27189 return rc;
27193 ** Truncate an open file to a specified size
27195 static int unixTruncate(sqlite3_file *id, i64 nByte){
27196 unixFile *pFile = (unixFile *)id;
27197 int rc;
27198 assert( pFile );
27199 SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27201 /* If the user has configured a chunk-size for this file, truncate the
27202 ** file so that it consists of an integer number of chunks (i.e. the
27203 ** actual file size after the operation may be larger than the requested
27204 ** size).
27206 if( pFile->szChunk>0 ){
27207 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27210 rc = robust_ftruncate(pFile->h, (off_t)nByte);
27211 if( rc ){
27212 pFile->lastErrno = errno;
27213 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27214 }else{
27215 #ifdef SQLITE_DEBUG
27216 /* If we are doing a normal write to a database file (as opposed to
27217 ** doing a hot-journal rollback or a write to some file other than a
27218 ** normal database file) and we truncate the file to zero length,
27219 ** that effectively updates the change counter. This might happen
27220 ** when restoring a database using the backup API from a zero-length
27221 ** source.
27223 if( pFile->inNormalWrite && nByte==0 ){
27224 pFile->transCntrChng = 1;
27226 #endif
27228 #if SQLITE_MAX_MMAP_SIZE>0
27229 /* If the file was just truncated to a size smaller than the currently
27230 ** mapped region, reduce the effective mapping size as well. SQLite will
27231 ** use read() and write() to access data beyond this point from now on.
27233 if( nByte<pFile->mmapSize ){
27234 pFile->mmapSize = nByte;
27236 #endif
27238 return SQLITE_OK;
27243 ** Determine the current size of a file in bytes
27245 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27246 int rc;
27247 struct stat buf;
27248 assert( id );
27249 rc = osFstat(((unixFile*)id)->h, &buf);
27250 SimulateIOError( rc=1 );
27251 if( rc!=0 ){
27252 ((unixFile*)id)->lastErrno = errno;
27253 return SQLITE_IOERR_FSTAT;
27255 *pSize = buf.st_size;
27257 /* When opening a zero-size database, the findInodeInfo() procedure
27258 ** writes a single byte into that file in order to work around a bug
27259 ** in the OS-X msdos filesystem. In order to avoid problems with upper
27260 ** layers, we need to report this file size as zero even though it is
27261 ** really 1. Ticket #3260.
27263 if( *pSize==1 ) *pSize = 0;
27266 return SQLITE_OK;
27269 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27271 ** Handler for proxy-locking file-control verbs. Defined below in the
27272 ** proxying locking division.
27274 static int proxyFileControl(sqlite3_file*,int,void*);
27275 #endif
27278 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
27279 ** file-control operation. Enlarge the database to nBytes in size
27280 ** (rounded up to the next chunk-size). If the database is already
27281 ** nBytes or larger, this routine is a no-op.
27283 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
27284 if( pFile->szChunk>0 ){
27285 i64 nSize; /* Required file size */
27286 struct stat buf; /* Used to hold return values of fstat() */
27288 if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
27290 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
27291 if( nSize>(i64)buf.st_size ){
27293 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
27294 /* The code below is handling the return value of osFallocate()
27295 ** correctly. posix_fallocate() is defined to "returns zero on success,
27296 ** or an error number on failure". See the manpage for details. */
27297 int err;
27299 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
27300 }while( err==EINTR );
27301 if( err ) return SQLITE_IOERR_WRITE;
27302 #else
27303 /* If the OS does not have posix_fallocate(), fake it. First use
27304 ** ftruncate() to set the file size, then write a single byte to
27305 ** the last byte in each block within the extended region. This
27306 ** is the same technique used by glibc to implement posix_fallocate()
27307 ** on systems that do not have a real fallocate() system call.
27309 int nBlk = buf.st_blksize; /* File-system block size */
27310 i64 iWrite; /* Next offset to write to */
27312 if( robust_ftruncate(pFile->h, nSize) ){
27313 pFile->lastErrno = errno;
27314 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27316 iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
27317 while( iWrite<nSize ){
27318 int nWrite = seekAndWrite(pFile, iWrite, "", 1);
27319 if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
27320 iWrite += nBlk;
27322 #endif
27326 #if SQLITE_MAX_MMAP_SIZE>0
27327 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
27328 int rc;
27329 if( pFile->szChunk<=0 ){
27330 if( robust_ftruncate(pFile->h, nByte) ){
27331 pFile->lastErrno = errno;
27332 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27336 rc = unixMapfile(pFile, nByte);
27337 return rc;
27339 #endif
27341 return SQLITE_OK;
27345 ** If *pArg is inititially negative then this is a query. Set *pArg to
27346 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
27348 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
27350 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
27351 if( *pArg<0 ){
27352 *pArg = (pFile->ctrlFlags & mask)!=0;
27353 }else if( (*pArg)==0 ){
27354 pFile->ctrlFlags &= ~mask;
27355 }else{
27356 pFile->ctrlFlags |= mask;
27360 /* Forward declaration */
27361 static int unixGetTempname(int nBuf, char *zBuf);
27364 ** Information and control of an open file handle.
27366 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
27367 unixFile *pFile = (unixFile*)id;
27368 switch( op ){
27369 case SQLITE_FCNTL_LOCKSTATE: {
27370 *(int*)pArg = pFile->eFileLock;
27371 return SQLITE_OK;
27373 case SQLITE_LAST_ERRNO: {
27374 *(int*)pArg = pFile->lastErrno;
27375 return SQLITE_OK;
27377 case SQLITE_FCNTL_CHUNK_SIZE: {
27378 pFile->szChunk = *(int *)pArg;
27379 return SQLITE_OK;
27381 case SQLITE_FCNTL_SIZE_HINT: {
27382 int rc;
27383 SimulateIOErrorBenign(1);
27384 rc = fcntlSizeHint(pFile, *(i64 *)pArg);
27385 SimulateIOErrorBenign(0);
27386 return rc;
27388 case SQLITE_FCNTL_PERSIST_WAL: {
27389 unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
27390 return SQLITE_OK;
27392 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
27393 unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
27394 return SQLITE_OK;
27396 case SQLITE_FCNTL_VFSNAME: {
27397 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
27398 return SQLITE_OK;
27400 case SQLITE_FCNTL_TEMPFILENAME: {
27401 char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
27402 if( zTFile ){
27403 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
27404 *(char**)pArg = zTFile;
27406 return SQLITE_OK;
27408 case SQLITE_FCNTL_HAS_MOVED: {
27409 *(int*)pArg = fileHasMoved(pFile);
27410 return SQLITE_OK;
27412 #if SQLITE_MAX_MMAP_SIZE>0
27413 case SQLITE_FCNTL_MMAP_SIZE: {
27414 i64 newLimit = *(i64*)pArg;
27415 int rc = SQLITE_OK;
27416 if( newLimit>sqlite3GlobalConfig.mxMmap ){
27417 newLimit = sqlite3GlobalConfig.mxMmap;
27419 *(i64*)pArg = pFile->mmapSizeMax;
27420 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
27421 pFile->mmapSizeMax = newLimit;
27422 if( pFile->mmapSize>0 ){
27423 unixUnmapfile(pFile);
27424 rc = unixMapfile(pFile, -1);
27427 return rc;
27429 #endif
27430 #ifdef SQLITE_DEBUG
27431 /* The pager calls this method to signal that it has done
27432 ** a rollback and that the database is therefore unchanged and
27433 ** it hence it is OK for the transaction change counter to be
27434 ** unchanged.
27436 case SQLITE_FCNTL_DB_UNCHANGED: {
27437 ((unixFile*)id)->dbUpdate = 0;
27438 return SQLITE_OK;
27440 #endif
27441 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27442 case SQLITE_SET_LOCKPROXYFILE:
27443 case SQLITE_GET_LOCKPROXYFILE: {
27444 return proxyFileControl(id,op,pArg);
27446 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
27448 return SQLITE_NOTFOUND;
27452 ** Return the sector size in bytes of the underlying block device for
27453 ** the specified file. This is almost always 512 bytes, but may be
27454 ** larger for some devices.
27456 ** SQLite code assumes this function cannot fail. It also assumes that
27457 ** if two files are created in the same file-system directory (i.e.
27458 ** a database and its journal file) that the sector size will be the
27459 ** same for both.
27461 #ifndef __QNXNTO__
27462 static int unixSectorSize(sqlite3_file *NotUsed){
27463 UNUSED_PARAMETER(NotUsed);
27464 return SQLITE_DEFAULT_SECTOR_SIZE;
27466 #endif
27469 ** The following version of unixSectorSize() is optimized for QNX.
27471 #ifdef __QNXNTO__
27472 #include <sys/dcmd_blk.h>
27473 #include <sys/statvfs.h>
27474 static int unixSectorSize(sqlite3_file *id){
27475 unixFile *pFile = (unixFile*)id;
27476 if( pFile->sectorSize == 0 ){
27477 struct statvfs fsInfo;
27479 /* Set defaults for non-supported filesystems */
27480 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
27481 pFile->deviceCharacteristics = 0;
27482 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
27483 return pFile->sectorSize;
27486 if( !strcmp(fsInfo.f_basetype, "tmp") ) {
27487 pFile->sectorSize = fsInfo.f_bsize;
27488 pFile->deviceCharacteristics =
27489 SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
27490 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
27491 ** the write succeeds */
27492 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
27493 ** so it is ordered */
27495 }else if( strstr(fsInfo.f_basetype, "etfs") ){
27496 pFile->sectorSize = fsInfo.f_bsize;
27497 pFile->deviceCharacteristics =
27498 /* etfs cluster size writes are atomic */
27499 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
27500 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
27501 ** the write succeeds */
27502 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
27503 ** so it is ordered */
27505 }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
27506 pFile->sectorSize = fsInfo.f_bsize;
27507 pFile->deviceCharacteristics =
27508 SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
27509 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
27510 ** the write succeeds */
27511 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
27512 ** so it is ordered */
27514 }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
27515 pFile->sectorSize = fsInfo.f_bsize;
27516 pFile->deviceCharacteristics =
27517 /* full bitset of atomics from max sector size and smaller */
27518 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
27519 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
27520 ** so it is ordered */
27522 }else if( strstr(fsInfo.f_basetype, "dos") ){
27523 pFile->sectorSize = fsInfo.f_bsize;
27524 pFile->deviceCharacteristics =
27525 /* full bitset of atomics from max sector size and smaller */
27526 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
27527 SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
27528 ** so it is ordered */
27530 }else{
27531 pFile->deviceCharacteristics =
27532 SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
27533 SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
27534 ** the write succeeds */
27538 /* Last chance verification. If the sector size isn't a multiple of 512
27539 ** then it isn't valid.*/
27540 if( pFile->sectorSize % 512 != 0 ){
27541 pFile->deviceCharacteristics = 0;
27542 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
27544 return pFile->sectorSize;
27546 #endif /* __QNXNTO__ */
27549 ** Return the device characteristics for the file.
27551 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
27552 ** However, that choice is contraversial since technically the underlying
27553 ** file system does not always provide powersafe overwrites. (In other
27554 ** words, after a power-loss event, parts of the file that were never
27555 ** written might end up being altered.) However, non-PSOW behavior is very,
27556 ** very rare. And asserting PSOW makes a large reduction in the amount
27557 ** of required I/O for journaling, since a lot of padding is eliminated.
27558 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
27559 ** available to turn it off and URI query parameter available to turn it off.
27561 static int unixDeviceCharacteristics(sqlite3_file *id){
27562 unixFile *p = (unixFile*)id;
27563 int rc = 0;
27564 #ifdef __QNXNTO__
27565 if( p->sectorSize==0 ) unixSectorSize(id);
27566 rc = p->deviceCharacteristics;
27567 #endif
27568 if( p->ctrlFlags & UNIXFILE_PSOW ){
27569 rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
27571 return rc;
27574 #ifndef SQLITE_OMIT_WAL
27578 ** Object used to represent an shared memory buffer.
27580 ** When multiple threads all reference the same wal-index, each thread
27581 ** has its own unixShm object, but they all point to a single instance
27582 ** of this unixShmNode object. In other words, each wal-index is opened
27583 ** only once per process.
27585 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27586 ** We could coalesce this object into unixInodeInfo, but that would mean
27587 ** every open file that does not use shared memory (in other words, most
27588 ** open files) would have to carry around this extra information. So
27589 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27590 ** and the unixShmNode object is created only when needed.
27592 ** unixMutexHeld() must be true when creating or destroying
27593 ** this object or while reading or writing the following fields:
27595 ** nRef
27597 ** The following fields are read-only after the object is created:
27599 ** fid
27600 ** zFilename
27602 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27603 ** unixMutexHeld() is true when reading or writing any other field
27604 ** in this structure.
27606 struct unixShmNode {
27607 unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
27608 sqlite3_mutex *mutex; /* Mutex to access this object */
27609 char *zFilename; /* Name of the mmapped file */
27610 int h; /* Open file descriptor */
27611 int szRegion; /* Size of shared-memory regions */
27612 u16 nRegion; /* Size of array apRegion */
27613 u8 isReadonly; /* True if read-only */
27614 char **apRegion; /* Array of mapped shared-memory regions */
27615 int nRef; /* Number of unixShm objects pointing to this */
27616 unixShm *pFirst; /* All unixShm objects pointing to this */
27617 #ifdef SQLITE_DEBUG
27618 u8 exclMask; /* Mask of exclusive locks held */
27619 u8 sharedMask; /* Mask of shared locks held */
27620 u8 nextShmId; /* Next available unixShm.id value */
27621 #endif
27625 ** Structure used internally by this VFS to record the state of an
27626 ** open shared memory connection.
27628 ** The following fields are initialized when this object is created and
27629 ** are read-only thereafter:
27631 ** unixShm.pFile
27632 ** unixShm.id
27634 ** All other fields are read/write. The unixShm.pFile->mutex must be held
27635 ** while accessing any read/write fields.
27637 struct unixShm {
27638 unixShmNode *pShmNode; /* The underlying unixShmNode object */
27639 unixShm *pNext; /* Next unixShm with the same unixShmNode */
27640 u8 hasMutex; /* True if holding the unixShmNode mutex */
27641 u8 id; /* Id of this connection within its unixShmNode */
27642 u16 sharedMask; /* Mask of shared locks held */
27643 u16 exclMask; /* Mask of exclusive locks held */
27647 ** Constants used for locking
27649 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
27650 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
27653 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27655 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27656 ** otherwise.
27658 static int unixShmSystemLock(
27659 unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27660 int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
27661 int ofst, /* First byte of the locking range */
27662 int n /* Number of bytes to lock */
27664 struct flock f; /* The posix advisory locking structure */
27665 int rc = SQLITE_OK; /* Result code form fcntl() */
27667 /* Access to the unixShmNode object is serialized by the caller */
27668 assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27670 /* Shared locks never span more than one byte */
27671 assert( n==1 || lockType!=F_RDLCK );
27673 /* Locks are within range */
27674 assert( n>=1 && n<SQLITE_SHM_NLOCK );
27676 if( pShmNode->h>=0 ){
27677 /* Initialize the locking parameters */
27678 memset(&f, 0, sizeof(f));
27679 f.l_type = lockType;
27680 f.l_whence = SEEK_SET;
27681 f.l_start = ofst;
27682 f.l_len = n;
27684 rc = osFcntl(pShmNode->h, F_SETLK, &f);
27685 rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27688 /* Update the global lock state and do debug tracing */
27689 #ifdef SQLITE_DEBUG
27690 { u16 mask;
27691 OSTRACE(("SHM-LOCK "));
27692 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
27693 if( rc==SQLITE_OK ){
27694 if( lockType==F_UNLCK ){
27695 OSTRACE(("unlock %d ok", ofst));
27696 pShmNode->exclMask &= ~mask;
27697 pShmNode->sharedMask &= ~mask;
27698 }else if( lockType==F_RDLCK ){
27699 OSTRACE(("read-lock %d ok", ofst));
27700 pShmNode->exclMask &= ~mask;
27701 pShmNode->sharedMask |= mask;
27702 }else{
27703 assert( lockType==F_WRLCK );
27704 OSTRACE(("write-lock %d ok", ofst));
27705 pShmNode->exclMask |= mask;
27706 pShmNode->sharedMask &= ~mask;
27708 }else{
27709 if( lockType==F_UNLCK ){
27710 OSTRACE(("unlock %d failed", ofst));
27711 }else if( lockType==F_RDLCK ){
27712 OSTRACE(("read-lock failed"));
27713 }else{
27714 assert( lockType==F_WRLCK );
27715 OSTRACE(("write-lock %d failed", ofst));
27718 OSTRACE((" - afterwards %03x,%03x\n",
27719 pShmNode->sharedMask, pShmNode->exclMask));
27721 #endif
27723 return rc;
27728 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27730 ** This is not a VFS shared-memory method; it is a utility function called
27731 ** by VFS shared-memory methods.
27733 static void unixShmPurge(unixFile *pFd){
27734 unixShmNode *p = pFd->pInode->pShmNode;
27735 assert( unixMutexHeld() );
27736 if( p && p->nRef==0 ){
27737 int i;
27738 assert( p->pInode==pFd->pInode );
27739 sqlite3_mutex_free(p->mutex);
27740 for(i=0; i<p->nRegion; i++){
27741 if( p->h>=0 ){
27742 osMunmap(p->apRegion[i], p->szRegion);
27743 }else{
27744 sqlite3_free(p->apRegion[i]);
27747 sqlite3_free(p->apRegion);
27748 if( p->h>=0 ){
27749 robust_close(pFd, p->h, __LINE__);
27750 p->h = -1;
27752 p->pInode->pShmNode = 0;
27753 sqlite3_free(p);
27758 ** Open a shared-memory area associated with open database file pDbFd.
27759 ** This particular implementation uses mmapped files.
27761 ** The file used to implement shared-memory is in the same directory
27762 ** as the open database file and has the same name as the open database
27763 ** file with the "-shm" suffix added. For example, if the database file
27764 ** is "/home/user1/config.db" then the file that is created and mmapped
27765 ** for shared memory will be called "/home/user1/config.db-shm".
27767 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27768 ** some other tmpfs mount. But if a file in a different directory
27769 ** from the database file is used, then differing access permissions
27770 ** or a chroot() might cause two different processes on the same
27771 ** database to end up using different files for shared memory -
27772 ** meaning that their memory would not really be shared - resulting
27773 ** in database corruption. Nevertheless, this tmpfs file usage
27774 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27775 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
27776 ** option results in an incompatible build of SQLite; builds of SQLite
27777 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27778 ** same database file at the same time, database corruption will likely
27779 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27780 ** "unsupported" and may go away in a future SQLite release.
27782 ** When opening a new shared-memory file, if no other instances of that
27783 ** file are currently open, in this process or in other processes, then
27784 ** the file must be truncated to zero length or have its header cleared.
27786 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27787 ** that means that an exclusive lock is held on the database file and
27788 ** that no other processes are able to read or write the database. In
27789 ** that case, we do not really need shared memory. No shared memory
27790 ** file is created. The shared memory will be simulated with heap memory.
27792 static int unixOpenSharedMemory(unixFile *pDbFd){
27793 struct unixShm *p = 0; /* The connection to be opened */
27794 struct unixShmNode *pShmNode; /* The underlying mmapped file */
27795 int rc; /* Result code */
27796 unixInodeInfo *pInode; /* The inode of fd */
27797 char *zShmFilename; /* Name of the file used for SHM */
27798 int nShmFilename; /* Size of the SHM filename in bytes */
27800 /* Allocate space for the new unixShm object. */
27801 p = sqlite3_malloc( sizeof(*p) );
27802 if( p==0 ) return SQLITE_NOMEM;
27803 memset(p, 0, sizeof(*p));
27804 assert( pDbFd->pShm==0 );
27806 /* Check to see if a unixShmNode object already exists. Reuse an existing
27807 ** one if present. Create a new one if necessary.
27809 unixEnterMutex();
27810 pInode = pDbFd->pInode;
27811 pShmNode = pInode->pShmNode;
27812 if( pShmNode==0 ){
27813 struct stat sStat; /* fstat() info for database file */
27815 /* Call fstat() to figure out the permissions on the database file. If
27816 ** a new *-shm file is created, an attempt will be made to create it
27817 ** with the same permissions.
27819 if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27820 rc = SQLITE_IOERR_FSTAT;
27821 goto shm_open_err;
27824 #ifdef SQLITE_SHM_DIRECTORY
27825 nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
27826 #else
27827 nShmFilename = 6 + (int)strlen(pDbFd->zPath);
27828 #endif
27829 pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27830 if( pShmNode==0 ){
27831 rc = SQLITE_NOMEM;
27832 goto shm_open_err;
27834 memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
27835 zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27836 #ifdef SQLITE_SHM_DIRECTORY
27837 sqlite3_snprintf(nShmFilename, zShmFilename,
27838 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27839 (u32)sStat.st_ino, (u32)sStat.st_dev);
27840 #else
27841 sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27842 sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
27843 #endif
27844 pShmNode->h = -1;
27845 pDbFd->pInode->pShmNode = pShmNode;
27846 pShmNode->pInode = pDbFd->pInode;
27847 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27848 if( pShmNode->mutex==0 ){
27849 rc = SQLITE_NOMEM;
27850 goto shm_open_err;
27853 if( pInode->bProcessLock==0 ){
27854 int openFlags = O_RDWR | O_CREAT;
27855 if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
27856 openFlags = O_RDONLY;
27857 pShmNode->isReadonly = 1;
27859 pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
27860 if( pShmNode->h<0 ){
27861 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27862 goto shm_open_err;
27865 /* If this process is running as root, make sure that the SHM file
27866 ** is owned by the same user that owns the original database. Otherwise,
27867 ** the original owner will not be able to connect.
27869 osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
27871 /* Check to see if another process is holding the dead-man switch.
27872 ** If not, truncate the file to zero length.
27874 rc = SQLITE_OK;
27875 if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27876 if( robust_ftruncate(pShmNode->h, 0) ){
27877 rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27880 if( rc==SQLITE_OK ){
27881 rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27883 if( rc ) goto shm_open_err;
27887 /* Make the new connection a child of the unixShmNode */
27888 p->pShmNode = pShmNode;
27889 #ifdef SQLITE_DEBUG
27890 p->id = pShmNode->nextShmId++;
27891 #endif
27892 pShmNode->nRef++;
27893 pDbFd->pShm = p;
27894 unixLeaveMutex();
27896 /* The reference count on pShmNode has already been incremented under
27897 ** the cover of the unixEnterMutex() mutex and the pointer from the
27898 ** new (struct unixShm) object to the pShmNode has been set. All that is
27899 ** left to do is to link the new object into the linked list starting
27900 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
27901 ** mutex.
27903 sqlite3_mutex_enter(pShmNode->mutex);
27904 p->pNext = pShmNode->pFirst;
27905 pShmNode->pFirst = p;
27906 sqlite3_mutex_leave(pShmNode->mutex);
27907 return SQLITE_OK;
27909 /* Jump here on any error */
27910 shm_open_err:
27911 unixShmPurge(pDbFd); /* This call frees pShmNode if required */
27912 sqlite3_free(p);
27913 unixLeaveMutex();
27914 return rc;
27918 ** This function is called to obtain a pointer to region iRegion of the
27919 ** shared-memory associated with the database file fd. Shared-memory regions
27920 ** are numbered starting from zero. Each shared-memory region is szRegion
27921 ** bytes in size.
27923 ** If an error occurs, an error code is returned and *pp is set to NULL.
27925 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27926 ** region has not been allocated (by any client, including one running in a
27927 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
27928 ** bExtend is non-zero and the requested shared-memory region has not yet
27929 ** been allocated, it is allocated by this function.
27931 ** If the shared-memory region has already been allocated or is allocated by
27932 ** this call as described above, then it is mapped into this processes
27933 ** address space (if it is not already), *pp is set to point to the mapped
27934 ** memory and SQLITE_OK returned.
27936 static int unixShmMap(
27937 sqlite3_file *fd, /* Handle open on database file */
27938 int iRegion, /* Region to retrieve */
27939 int szRegion, /* Size of regions */
27940 int bExtend, /* True to extend file if necessary */
27941 void volatile **pp /* OUT: Mapped memory */
27943 unixFile *pDbFd = (unixFile*)fd;
27944 unixShm *p;
27945 unixShmNode *pShmNode;
27946 int rc = SQLITE_OK;
27948 /* If the shared-memory file has not yet been opened, open it now. */
27949 if( pDbFd->pShm==0 ){
27950 rc = unixOpenSharedMemory(pDbFd);
27951 if( rc!=SQLITE_OK ) return rc;
27954 p = pDbFd->pShm;
27955 pShmNode = p->pShmNode;
27956 sqlite3_mutex_enter(pShmNode->mutex);
27957 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27958 assert( pShmNode->pInode==pDbFd->pInode );
27959 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27960 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27962 if( pShmNode->nRegion<=iRegion ){
27963 char **apNew; /* New apRegion[] array */
27964 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
27965 struct stat sStat; /* Used by fstat() */
27967 pShmNode->szRegion = szRegion;
27969 if( pShmNode->h>=0 ){
27970 /* The requested region is not mapped into this processes address space.
27971 ** Check to see if it has been allocated (i.e. if the wal-index file is
27972 ** large enough to contain the requested region).
27974 if( osFstat(pShmNode->h, &sStat) ){
27975 rc = SQLITE_IOERR_SHMSIZE;
27976 goto shmpage_out;
27979 if( sStat.st_size<nByte ){
27980 /* The requested memory region does not exist. If bExtend is set to
27981 ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27983 if( !bExtend ){
27984 goto shmpage_out;
27987 /* Alternatively, if bExtend is true, extend the file. Do this by
27988 ** writing a single byte to the end of each (OS) page being
27989 ** allocated or extended. Technically, we need only write to the
27990 ** last page in order to extend the file. But writing to all new
27991 ** pages forces the OS to allocate them immediately, which reduces
27992 ** the chances of SIGBUS while accessing the mapped region later on.
27994 else{
27995 static const int pgsz = 4096;
27996 int iPg;
27998 /* Write to the last byte of each newly allocated or extended page */
27999 assert( (nByte % pgsz)==0 );
28000 for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
28001 if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
28002 const char *zFile = pShmNode->zFilename;
28003 rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
28004 goto shmpage_out;
28011 /* Map the requested memory region into this processes address space. */
28012 apNew = (char **)sqlite3_realloc(
28013 pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28015 if( !apNew ){
28016 rc = SQLITE_IOERR_NOMEM;
28017 goto shmpage_out;
28019 pShmNode->apRegion = apNew;
28020 while(pShmNode->nRegion<=iRegion){
28021 void *pMem;
28022 if( pShmNode->h>=0 ){
28023 pMem = osMmap(0, szRegion,
28024 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
28025 MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
28027 if( pMem==MAP_FAILED ){
28028 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
28029 goto shmpage_out;
28031 }else{
28032 pMem = sqlite3_malloc(szRegion);
28033 if( pMem==0 ){
28034 rc = SQLITE_NOMEM;
28035 goto shmpage_out;
28037 memset(pMem, 0, szRegion);
28039 pShmNode->apRegion[pShmNode->nRegion] = pMem;
28040 pShmNode->nRegion++;
28044 shmpage_out:
28045 if( pShmNode->nRegion>iRegion ){
28046 *pp = pShmNode->apRegion[iRegion];
28047 }else{
28048 *pp = 0;
28050 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
28051 sqlite3_mutex_leave(pShmNode->mutex);
28052 return rc;
28056 ** Change the lock state for a shared-memory segment.
28058 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28059 ** different here than in posix. In xShmLock(), one can go from unlocked
28060 ** to shared and back or from unlocked to exclusive and back. But one may
28061 ** not go from shared to exclusive or from exclusive to shared.
28063 static int unixShmLock(
28064 sqlite3_file *fd, /* Database file holding the shared memory */
28065 int ofst, /* First lock to acquire or release */
28066 int n, /* Number of locks to acquire or release */
28067 int flags /* What to do with the lock */
28069 unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
28070 unixShm *p = pDbFd->pShm; /* The shared memory being locked */
28071 unixShm *pX; /* For looping over all siblings */
28072 unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
28073 int rc = SQLITE_OK; /* Result code */
28074 u16 mask; /* Mask of locks to take or release */
28076 assert( pShmNode==pDbFd->pInode->pShmNode );
28077 assert( pShmNode->pInode==pDbFd->pInode );
28078 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28079 assert( n>=1 );
28080 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28081 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28082 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28083 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28084 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28085 assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28086 assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28088 mask = (1<<(ofst+n)) - (1<<ofst);
28089 assert( n>1 || mask==(1<<ofst) );
28090 sqlite3_mutex_enter(pShmNode->mutex);
28091 if( flags & SQLITE_SHM_UNLOCK ){
28092 u16 allMask = 0; /* Mask of locks held by siblings */
28094 /* See if any siblings hold this same lock */
28095 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28096 if( pX==p ) continue;
28097 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28098 allMask |= pX->sharedMask;
28101 /* Unlock the system-level locks */
28102 if( (mask & allMask)==0 ){
28103 rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28104 }else{
28105 rc = SQLITE_OK;
28108 /* Undo the local locks */
28109 if( rc==SQLITE_OK ){
28110 p->exclMask &= ~mask;
28111 p->sharedMask &= ~mask;
28113 }else if( flags & SQLITE_SHM_SHARED ){
28114 u16 allShared = 0; /* Union of locks held by connections other than "p" */
28116 /* Find out which shared locks are already held by sibling connections.
28117 ** If any sibling already holds an exclusive lock, go ahead and return
28118 ** SQLITE_BUSY.
28120 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28121 if( (pX->exclMask & mask)!=0 ){
28122 rc = SQLITE_BUSY;
28123 break;
28125 allShared |= pX->sharedMask;
28128 /* Get shared locks at the system level, if necessary */
28129 if( rc==SQLITE_OK ){
28130 if( (allShared & mask)==0 ){
28131 rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28132 }else{
28133 rc = SQLITE_OK;
28137 /* Get the local shared locks */
28138 if( rc==SQLITE_OK ){
28139 p->sharedMask |= mask;
28141 }else{
28142 /* Make sure no sibling connections hold locks that will block this
28143 ** lock. If any do, return SQLITE_BUSY right away.
28145 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28146 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28147 rc = SQLITE_BUSY;
28148 break;
28152 /* Get the exclusive locks at the system level. Then if successful
28153 ** also mark the local connection as being locked.
28155 if( rc==SQLITE_OK ){
28156 rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28157 if( rc==SQLITE_OK ){
28158 assert( (p->sharedMask & mask)==0 );
28159 p->exclMask |= mask;
28163 sqlite3_mutex_leave(pShmNode->mutex);
28164 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28165 p->id, getpid(), p->sharedMask, p->exclMask));
28166 return rc;
28170 ** Implement a memory barrier or memory fence on shared memory.
28172 ** All loads and stores begun before the barrier must complete before
28173 ** any load or store begun after the barrier.
28175 static void unixShmBarrier(
28176 sqlite3_file *fd /* Database file holding the shared memory */
28178 UNUSED_PARAMETER(fd);
28179 unixEnterMutex();
28180 unixLeaveMutex();
28184 ** Close a connection to shared-memory. Delete the underlying
28185 ** storage if deleteFlag is true.
28187 ** If there is no shared memory associated with the connection then this
28188 ** routine is a harmless no-op.
28190 static int unixShmUnmap(
28191 sqlite3_file *fd, /* The underlying database file */
28192 int deleteFlag /* Delete shared-memory if true */
28194 unixShm *p; /* The connection to be closed */
28195 unixShmNode *pShmNode; /* The underlying shared-memory file */
28196 unixShm **pp; /* For looping over sibling connections */
28197 unixFile *pDbFd; /* The underlying database file */
28199 pDbFd = (unixFile*)fd;
28200 p = pDbFd->pShm;
28201 if( p==0 ) return SQLITE_OK;
28202 pShmNode = p->pShmNode;
28204 assert( pShmNode==pDbFd->pInode->pShmNode );
28205 assert( pShmNode->pInode==pDbFd->pInode );
28207 /* Remove connection p from the set of connections associated
28208 ** with pShmNode */
28209 sqlite3_mutex_enter(pShmNode->mutex);
28210 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28211 *pp = p->pNext;
28213 /* Free the connection p */
28214 sqlite3_free(p);
28215 pDbFd->pShm = 0;
28216 sqlite3_mutex_leave(pShmNode->mutex);
28218 /* If pShmNode->nRef has reached 0, then close the underlying
28219 ** shared-memory file, too */
28220 unixEnterMutex();
28221 assert( pShmNode->nRef>0 );
28222 pShmNode->nRef--;
28223 if( pShmNode->nRef==0 ){
28224 if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28225 unixShmPurge(pDbFd);
28227 unixLeaveMutex();
28229 return SQLITE_OK;
28233 #else
28234 # define unixShmMap 0
28235 # define unixShmLock 0
28236 # define unixShmBarrier 0
28237 # define unixShmUnmap 0
28238 #endif /* #ifndef SQLITE_OMIT_WAL */
28240 #if SQLITE_MAX_MMAP_SIZE>0
28242 ** If it is currently memory mapped, unmap file pFd.
28244 static void unixUnmapfile(unixFile *pFd){
28245 assert( pFd->nFetchOut==0 );
28246 if( pFd->pMapRegion ){
28247 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
28248 pFd->pMapRegion = 0;
28249 pFd->mmapSize = 0;
28250 pFd->mmapSizeActual = 0;
28255 ** Return the system page size.
28257 static int unixGetPagesize(void){
28258 #if HAVE_MREMAP
28259 return 512;
28260 #elif defined(_BSD_SOURCE)
28261 return getpagesize();
28262 #else
28263 return (int)sysconf(_SC_PAGESIZE);
28264 #endif
28268 ** Attempt to set the size of the memory mapping maintained by file
28269 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
28271 ** If successful, this function sets the following variables:
28273 ** unixFile.pMapRegion
28274 ** unixFile.mmapSize
28275 ** unixFile.mmapSizeActual
28277 ** If unsuccessful, an error message is logged via sqlite3_log() and
28278 ** the three variables above are zeroed. In this case SQLite should
28279 ** continue accessing the database using the xRead() and xWrite()
28280 ** methods.
28282 static void unixRemapfile(
28283 unixFile *pFd, /* File descriptor object */
28284 i64 nNew /* Required mapping size */
28286 const char *zErr = "mmap";
28287 int h = pFd->h; /* File descriptor open on db file */
28288 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
28289 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
28290 u8 *pNew = 0; /* Location of new mapping */
28291 int flags = PROT_READ; /* Flags to pass to mmap() */
28293 assert( pFd->nFetchOut==0 );
28294 assert( nNew>pFd->mmapSize );
28295 assert( nNew<=pFd->mmapSizeMax );
28296 assert( nNew>0 );
28297 assert( pFd->mmapSizeActual>=pFd->mmapSize );
28298 assert( MAP_FAILED!=0 );
28300 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
28302 if( pOrig ){
28303 const int szSyspage = unixGetPagesize();
28304 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
28305 u8 *pReq = &pOrig[nReuse];
28307 /* Unmap any pages of the existing mapping that cannot be reused. */
28308 if( nReuse!=nOrig ){
28309 osMunmap(pReq, nOrig-nReuse);
28312 #if HAVE_MREMAP
28313 pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
28314 zErr = "mremap";
28315 #else
28316 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
28317 if( pNew!=MAP_FAILED ){
28318 if( pNew!=pReq ){
28319 osMunmap(pNew, nNew - nReuse);
28320 pNew = 0;
28321 }else{
28322 pNew = pOrig;
28325 #endif
28327 /* The attempt to extend the existing mapping failed. Free it. */
28328 if( pNew==MAP_FAILED || pNew==0 ){
28329 osMunmap(pOrig, nReuse);
28333 /* If pNew is still NULL, try to create an entirely new mapping. */
28334 if( pNew==0 ){
28335 pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
28338 if( pNew==MAP_FAILED ){
28339 pNew = 0;
28340 nNew = 0;
28341 unixLogError(SQLITE_OK, zErr, pFd->zPath);
28343 /* If the mmap() above failed, assume that all subsequent mmap() calls
28344 ** will probably fail too. Fall back to using xRead/xWrite exclusively
28345 ** in this case. */
28346 pFd->mmapSizeMax = 0;
28348 pFd->pMapRegion = (void *)pNew;
28349 pFd->mmapSize = pFd->mmapSizeActual = nNew;
28353 ** Memory map or remap the file opened by file-descriptor pFd (if the file
28354 ** is already mapped, the existing mapping is replaced by the new). Or, if
28355 ** there already exists a mapping for this file, and there are still
28356 ** outstanding xFetch() references to it, this function is a no-op.
28358 ** If parameter nByte is non-negative, then it is the requested size of
28359 ** the mapping to create. Otherwise, if nByte is less than zero, then the
28360 ** requested size is the size of the file on disk. The actual size of the
28361 ** created mapping is either the requested size or the value configured
28362 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
28364 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
28365 ** recreated as a result of outstanding references) or an SQLite error
28366 ** code otherwise.
28368 static int unixMapfile(unixFile *pFd, i64 nByte){
28369 i64 nMap = nByte;
28370 int rc;
28372 assert( nMap>=0 || pFd->nFetchOut==0 );
28373 if( pFd->nFetchOut>0 ) return SQLITE_OK;
28375 if( nMap<0 ){
28376 struct stat statbuf; /* Low-level file information */
28377 rc = osFstat(pFd->h, &statbuf);
28378 if( rc!=SQLITE_OK ){
28379 return SQLITE_IOERR_FSTAT;
28381 nMap = statbuf.st_size;
28383 if( nMap>pFd->mmapSizeMax ){
28384 nMap = pFd->mmapSizeMax;
28387 if( nMap!=pFd->mmapSize ){
28388 if( nMap>0 ){
28389 unixRemapfile(pFd, nMap);
28390 }else{
28391 unixUnmapfile(pFd);
28395 return SQLITE_OK;
28397 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
28400 ** If possible, return a pointer to a mapping of file fd starting at offset
28401 ** iOff. The mapping must be valid for at least nAmt bytes.
28403 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
28404 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
28405 ** Finally, if an error does occur, return an SQLite error code. The final
28406 ** value of *pp is undefined in this case.
28408 ** If this function does return a pointer, the caller must eventually
28409 ** release the reference by calling unixUnfetch().
28411 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
28412 #if SQLITE_MAX_MMAP_SIZE>0
28413 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
28414 #endif
28415 *pp = 0;
28417 #if SQLITE_MAX_MMAP_SIZE>0
28418 if( pFd->mmapSizeMax>0 ){
28419 if( pFd->pMapRegion==0 ){
28420 int rc = unixMapfile(pFd, -1);
28421 if( rc!=SQLITE_OK ) return rc;
28423 if( pFd->mmapSize >= iOff+nAmt ){
28424 *pp = &((u8 *)pFd->pMapRegion)[iOff];
28425 pFd->nFetchOut++;
28428 #endif
28429 return SQLITE_OK;
28433 ** If the third argument is non-NULL, then this function releases a
28434 ** reference obtained by an earlier call to unixFetch(). The second
28435 ** argument passed to this function must be the same as the corresponding
28436 ** argument that was passed to the unixFetch() invocation.
28438 ** Or, if the third argument is NULL, then this function is being called
28439 ** to inform the VFS layer that, according to POSIX, any existing mapping
28440 ** may now be invalid and should be unmapped.
28442 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
28443 #if SQLITE_MAX_MMAP_SIZE>0
28444 unixFile *pFd = (unixFile *)fd; /* The underlying database file */
28445 UNUSED_PARAMETER(iOff);
28447 /* If p==0 (unmap the entire file) then there must be no outstanding
28448 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
28449 ** then there must be at least one outstanding. */
28450 assert( (p==0)==(pFd->nFetchOut==0) );
28452 /* If p!=0, it must match the iOff value. */
28453 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
28455 if( p ){
28456 pFd->nFetchOut--;
28457 }else{
28458 unixUnmapfile(pFd);
28461 assert( pFd->nFetchOut>=0 );
28462 #else
28463 UNUSED_PARAMETER(fd);
28464 UNUSED_PARAMETER(p);
28465 UNUSED_PARAMETER(iOff);
28466 #endif
28467 return SQLITE_OK;
28471 ** Here ends the implementation of all sqlite3_file methods.
28473 ********************** End sqlite3_file Methods *******************************
28474 ******************************************************************************/
28477 ** This division contains definitions of sqlite3_io_methods objects that
28478 ** implement various file locking strategies. It also contains definitions
28479 ** of "finder" functions. A finder-function is used to locate the appropriate
28480 ** sqlite3_io_methods object for a particular database file. The pAppData
28481 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28482 ** the correct finder-function for that VFS.
28484 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28485 ** object. The only interesting finder-function is autolockIoFinder, which
28486 ** looks at the filesystem type and tries to guess the best locking
28487 ** strategy from that.
28489 ** For finder-funtion F, two objects are created:
28491 ** (1) The real finder-function named "FImpt()".
28493 ** (2) A constant pointer to this function named just "F".
28496 ** A pointer to the F pointer is used as the pAppData value for VFS
28497 ** objects. We have to do this instead of letting pAppData point
28498 ** directly at the finder-function since C90 rules prevent a void*
28499 ** from be cast into a function pointer.
28502 ** Each instance of this macro generates two objects:
28504 ** * A constant sqlite3_io_methods object call METHOD that has locking
28505 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28507 ** * An I/O method finder function called FINDER that returns a pointer
28508 ** to the METHOD object in the previous bullet.
28510 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
28511 static const sqlite3_io_methods METHOD = { \
28512 VERSION, /* iVersion */ \
28513 CLOSE, /* xClose */ \
28514 unixRead, /* xRead */ \
28515 unixWrite, /* xWrite */ \
28516 unixTruncate, /* xTruncate */ \
28517 unixSync, /* xSync */ \
28518 unixFileSize, /* xFileSize */ \
28519 LOCK, /* xLock */ \
28520 UNLOCK, /* xUnlock */ \
28521 CKLOCK, /* xCheckReservedLock */ \
28522 unixFileControl, /* xFileControl */ \
28523 unixSectorSize, /* xSectorSize */ \
28524 unixDeviceCharacteristics, /* xDeviceCapabilities */ \
28525 unixShmMap, /* xShmMap */ \
28526 unixShmLock, /* xShmLock */ \
28527 unixShmBarrier, /* xShmBarrier */ \
28528 unixShmUnmap, /* xShmUnmap */ \
28529 unixFetch, /* xFetch */ \
28530 unixUnfetch, /* xUnfetch */ \
28531 }; \
28532 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
28533 UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
28534 return &METHOD; \
28536 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
28537 = FINDER##Impl;
28540 ** Here are all of the sqlite3_io_methods objects for each of the
28541 ** locking strategies. Functions that return pointers to these methods
28542 ** are also created.
28544 IOMETHODS(
28545 posixIoFinder, /* Finder function name */
28546 posixIoMethods, /* sqlite3_io_methods object name */
28547 3, /* shared memory and mmap are enabled */
28548 unixClose, /* xClose method */
28549 unixLock, /* xLock method */
28550 unixUnlock, /* xUnlock method */
28551 unixCheckReservedLock /* xCheckReservedLock method */
28553 IOMETHODS(
28554 nolockIoFinder, /* Finder function name */
28555 nolockIoMethods, /* sqlite3_io_methods object name */
28556 1, /* shared memory is disabled */
28557 nolockClose, /* xClose method */
28558 nolockLock, /* xLock method */
28559 nolockUnlock, /* xUnlock method */
28560 nolockCheckReservedLock /* xCheckReservedLock method */
28562 IOMETHODS(
28563 dotlockIoFinder, /* Finder function name */
28564 dotlockIoMethods, /* sqlite3_io_methods object name */
28565 1, /* shared memory is disabled */
28566 dotlockClose, /* xClose method */
28567 dotlockLock, /* xLock method */
28568 dotlockUnlock, /* xUnlock method */
28569 dotlockCheckReservedLock /* xCheckReservedLock method */
28572 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28573 IOMETHODS(
28574 flockIoFinder, /* Finder function name */
28575 flockIoMethods, /* sqlite3_io_methods object name */
28576 1, /* shared memory is disabled */
28577 flockClose, /* xClose method */
28578 flockLock, /* xLock method */
28579 flockUnlock, /* xUnlock method */
28580 flockCheckReservedLock /* xCheckReservedLock method */
28582 #endif
28584 #if OS_VXWORKS
28585 IOMETHODS(
28586 semIoFinder, /* Finder function name */
28587 semIoMethods, /* sqlite3_io_methods object name */
28588 1, /* shared memory is disabled */
28589 semClose, /* xClose method */
28590 semLock, /* xLock method */
28591 semUnlock, /* xUnlock method */
28592 semCheckReservedLock /* xCheckReservedLock method */
28594 #endif
28596 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28597 IOMETHODS(
28598 afpIoFinder, /* Finder function name */
28599 afpIoMethods, /* sqlite3_io_methods object name */
28600 1, /* shared memory is disabled */
28601 afpClose, /* xClose method */
28602 afpLock, /* xLock method */
28603 afpUnlock, /* xUnlock method */
28604 afpCheckReservedLock /* xCheckReservedLock method */
28606 #endif
28609 ** The proxy locking method is a "super-method" in the sense that it
28610 ** opens secondary file descriptors for the conch and lock files and
28611 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28612 ** secondary files. For this reason, the division that implements
28613 ** proxy locking is located much further down in the file. But we need
28614 ** to go ahead and define the sqlite3_io_methods and finder function
28615 ** for proxy locking here. So we forward declare the I/O methods.
28617 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28618 static int proxyClose(sqlite3_file*);
28619 static int proxyLock(sqlite3_file*, int);
28620 static int proxyUnlock(sqlite3_file*, int);
28621 static int proxyCheckReservedLock(sqlite3_file*, int*);
28622 IOMETHODS(
28623 proxyIoFinder, /* Finder function name */
28624 proxyIoMethods, /* sqlite3_io_methods object name */
28625 1, /* shared memory is disabled */
28626 proxyClose, /* xClose method */
28627 proxyLock, /* xLock method */
28628 proxyUnlock, /* xUnlock method */
28629 proxyCheckReservedLock /* xCheckReservedLock method */
28631 #endif
28633 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28634 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28635 IOMETHODS(
28636 nfsIoFinder, /* Finder function name */
28637 nfsIoMethods, /* sqlite3_io_methods object name */
28638 1, /* shared memory is disabled */
28639 unixClose, /* xClose method */
28640 unixLock, /* xLock method */
28641 nfsUnlock, /* xUnlock method */
28642 unixCheckReservedLock /* xCheckReservedLock method */
28644 #endif
28646 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28648 ** This "finder" function attempts to determine the best locking strategy
28649 ** for the database file "filePath". It then returns the sqlite3_io_methods
28650 ** object that implements that strategy.
28652 ** This is for MacOSX only.
28654 static const sqlite3_io_methods *autolockIoFinderImpl(
28655 const char *filePath, /* name of the database file */
28656 unixFile *pNew /* open file object for the database file */
28658 static const struct Mapping {
28659 const char *zFilesystem; /* Filesystem type name */
28660 const sqlite3_io_methods *pMethods; /* Appropriate locking method */
28661 } aMap[] = {
28662 { "hfs", &posixIoMethods },
28663 { "ufs", &posixIoMethods },
28664 { "afpfs", &afpIoMethods },
28665 { "smbfs", &afpIoMethods },
28666 { "webdav", &nolockIoMethods },
28667 { 0, 0 }
28669 int i;
28670 struct statfs fsInfo;
28671 struct flock lockInfo;
28673 if( !filePath ){
28674 /* If filePath==NULL that means we are dealing with a transient file
28675 ** that does not need to be locked. */
28676 return &nolockIoMethods;
28678 if( statfs(filePath, &fsInfo) != -1 ){
28679 if( fsInfo.f_flags & MNT_RDONLY ){
28680 return &nolockIoMethods;
28682 for(i=0; aMap[i].zFilesystem; i++){
28683 if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28684 return aMap[i].pMethods;
28689 /* Default case. Handles, amongst others, "nfs".
28690 ** Test byte-range lock using fcntl(). If the call succeeds,
28691 ** assume that the file-system supports POSIX style locks.
28693 lockInfo.l_len = 1;
28694 lockInfo.l_start = 0;
28695 lockInfo.l_whence = SEEK_SET;
28696 lockInfo.l_type = F_RDLCK;
28697 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28698 if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28699 return &nfsIoMethods;
28700 } else {
28701 return &posixIoMethods;
28703 }else{
28704 return &dotlockIoMethods;
28707 static const sqlite3_io_methods
28708 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28710 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28712 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28714 ** This "finder" function attempts to determine the best locking strategy
28715 ** for the database file "filePath". It then returns the sqlite3_io_methods
28716 ** object that implements that strategy.
28718 ** This is for VXWorks only.
28720 static const sqlite3_io_methods *autolockIoFinderImpl(
28721 const char *filePath, /* name of the database file */
28722 unixFile *pNew /* the open file object */
28724 struct flock lockInfo;
28726 if( !filePath ){
28727 /* If filePath==NULL that means we are dealing with a transient file
28728 ** that does not need to be locked. */
28729 return &nolockIoMethods;
28732 /* Test if fcntl() is supported and use POSIX style locks.
28733 ** Otherwise fall back to the named semaphore method.
28735 lockInfo.l_len = 1;
28736 lockInfo.l_start = 0;
28737 lockInfo.l_whence = SEEK_SET;
28738 lockInfo.l_type = F_RDLCK;
28739 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28740 return &posixIoMethods;
28741 }else{
28742 return &semIoMethods;
28745 static const sqlite3_io_methods
28746 *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28748 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28751 ** An abstract type for a pointer to a IO method finder function:
28753 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28756 /****************************************************************************
28757 **************************** sqlite3_vfs methods ****************************
28759 ** This division contains the implementation of methods on the
28760 ** sqlite3_vfs object.
28764 ** Initialize the contents of the unixFile structure pointed to by pId.
28766 static int fillInUnixFile(
28767 sqlite3_vfs *pVfs, /* Pointer to vfs object */
28768 int h, /* Open file descriptor of file being opened */
28769 sqlite3_file *pId, /* Write to the unixFile structure here */
28770 const char *zFilename, /* Name of the file being opened */
28771 int ctrlFlags /* Zero or more UNIXFILE_* values */
28773 const sqlite3_io_methods *pLockingStyle;
28774 unixFile *pNew = (unixFile *)pId;
28775 int rc = SQLITE_OK;
28777 assert( pNew->pInode==NULL );
28779 /* Usually the path zFilename should not be a relative pathname. The
28780 ** exception is when opening the proxy "conch" file in builds that
28781 ** include the special Apple locking styles.
28783 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28784 assert( zFilename==0 || zFilename[0]=='/'
28785 || pVfs->pAppData==(void*)&autolockIoFinder );
28786 #else
28787 assert( zFilename==0 || zFilename[0]=='/' );
28788 #endif
28790 /* No locking occurs in temporary files */
28791 assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
28793 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
28794 pNew->h = h;
28795 pNew->pVfs = pVfs;
28796 pNew->zPath = zFilename;
28797 pNew->ctrlFlags = (u8)ctrlFlags;
28798 #if SQLITE_MAX_MMAP_SIZE>0
28799 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28800 #endif
28801 if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28802 "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28803 pNew->ctrlFlags |= UNIXFILE_PSOW;
28805 if( strcmp(pVfs->zName,"unix-excl")==0 ){
28806 pNew->ctrlFlags |= UNIXFILE_EXCL;
28809 #if OS_VXWORKS
28810 pNew->pId = vxworksFindFileId(zFilename);
28811 if( pNew->pId==0 ){
28812 ctrlFlags |= UNIXFILE_NOLOCK;
28813 rc = SQLITE_NOMEM;
28815 #endif
28817 if( ctrlFlags & UNIXFILE_NOLOCK ){
28818 pLockingStyle = &nolockIoMethods;
28819 }else{
28820 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28821 #if SQLITE_ENABLE_LOCKING_STYLE
28822 /* Cache zFilename in the locking context (AFP and dotlock override) for
28823 ** proxyLock activation is possible (remote proxy is based on db name)
28824 ** zFilename remains valid until file is closed, to support */
28825 pNew->lockingContext = (void*)zFilename;
28826 #endif
28829 if( pLockingStyle == &posixIoMethods
28830 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28831 || pLockingStyle == &nfsIoMethods
28832 #endif
28834 unixEnterMutex();
28835 rc = findInodeInfo(pNew, &pNew->pInode);
28836 if( rc!=SQLITE_OK ){
28837 /* If an error occurred in findInodeInfo(), close the file descriptor
28838 ** immediately, before releasing the mutex. findInodeInfo() may fail
28839 ** in two scenarios:
28841 ** (a) A call to fstat() failed.
28842 ** (b) A malloc failed.
28844 ** Scenario (b) may only occur if the process is holding no other
28845 ** file descriptors open on the same file. If there were other file
28846 ** descriptors on this file, then no malloc would be required by
28847 ** findInodeInfo(). If this is the case, it is quite safe to close
28848 ** handle h - as it is guaranteed that no posix locks will be released
28849 ** by doing so.
28851 ** If scenario (a) caused the error then things are not so safe. The
28852 ** implicit assumption here is that if fstat() fails, things are in
28853 ** such bad shape that dropping a lock or two doesn't matter much.
28855 robust_close(pNew, h, __LINE__);
28856 h = -1;
28858 unixLeaveMutex();
28861 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28862 else if( pLockingStyle == &afpIoMethods ){
28863 /* AFP locking uses the file path so it needs to be included in
28864 ** the afpLockingContext.
28866 afpLockingContext *pCtx;
28867 pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28868 if( pCtx==0 ){
28869 rc = SQLITE_NOMEM;
28870 }else{
28871 /* NB: zFilename exists and remains valid until the file is closed
28872 ** according to requirement F11141. So we do not need to make a
28873 ** copy of the filename. */
28874 pCtx->dbPath = zFilename;
28875 pCtx->reserved = 0;
28876 srandomdev();
28877 unixEnterMutex();
28878 rc = findInodeInfo(pNew, &pNew->pInode);
28879 if( rc!=SQLITE_OK ){
28880 sqlite3_free(pNew->lockingContext);
28881 robust_close(pNew, h, __LINE__);
28882 h = -1;
28884 unixLeaveMutex();
28887 #endif
28889 else if( pLockingStyle == &dotlockIoMethods ){
28890 /* Dotfile locking uses the file path so it needs to be included in
28891 ** the dotlockLockingContext
28893 char *zLockFile;
28894 int nFilename;
28895 assert( zFilename!=0 );
28896 nFilename = (int)strlen(zFilename) + 6;
28897 zLockFile = (char *)sqlite3_malloc(nFilename);
28898 if( zLockFile==0 ){
28899 rc = SQLITE_NOMEM;
28900 }else{
28901 sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28903 pNew->lockingContext = zLockFile;
28906 #if OS_VXWORKS
28907 else if( pLockingStyle == &semIoMethods ){
28908 /* Named semaphore locking uses the file path so it needs to be
28909 ** included in the semLockingContext
28911 unixEnterMutex();
28912 rc = findInodeInfo(pNew, &pNew->pInode);
28913 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28914 char *zSemName = pNew->pInode->aSemName;
28915 int n;
28916 sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28917 pNew->pId->zCanonicalName);
28918 for( n=1; zSemName[n]; n++ )
28919 if( zSemName[n]=='/' ) zSemName[n] = '_';
28920 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28921 if( pNew->pInode->pSem == SEM_FAILED ){
28922 rc = SQLITE_NOMEM;
28923 pNew->pInode->aSemName[0] = '\0';
28926 unixLeaveMutex();
28928 #endif
28930 pNew->lastErrno = 0;
28931 #if OS_VXWORKS
28932 if( rc!=SQLITE_OK ){
28933 if( h>=0 ) robust_close(pNew, h, __LINE__);
28934 h = -1;
28935 osUnlink(zFilename);
28936 pNew->ctrlFlags |= UNIXFILE_DELETE;
28938 #endif
28939 if( rc!=SQLITE_OK ){
28940 if( h>=0 ) robust_close(pNew, h, __LINE__);
28941 }else{
28942 pNew->pMethod = pLockingStyle;
28943 OpenCounter(+1);
28944 verifyDbFile(pNew);
28946 return rc;
28950 ** Return the name of a directory in which to put temporary files.
28951 ** If no suitable temporary file directory can be found, return NULL.
28953 static const char *unixTempFileDir(void){
28954 static const char *azDirs[] = {
28958 "/var/tmp",
28959 "/usr/tmp",
28960 "/tmp",
28961 0 /* List terminator */
28963 unsigned int i;
28964 struct stat buf;
28965 const char *zDir = 0;
28967 azDirs[0] = sqlite3_temp_directory;
28968 if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
28969 if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
28970 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28971 if( zDir==0 ) continue;
28972 if( osStat(zDir, &buf) ) continue;
28973 if( !S_ISDIR(buf.st_mode) ) continue;
28974 if( osAccess(zDir, 07) ) continue;
28975 break;
28977 return zDir;
28981 ** Create a temporary file name in zBuf. zBuf must be allocated
28982 ** by the calling process and must be big enough to hold at least
28983 ** pVfs->mxPathname bytes.
28985 static int unixGetTempname(int nBuf, char *zBuf){
28986 static const unsigned char zChars[] =
28987 "abcdefghijklmnopqrstuvwxyz"
28988 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28989 "0123456789";
28990 unsigned int i, j;
28991 const char *zDir;
28993 /* It's odd to simulate an io-error here, but really this is just
28994 ** using the io-error infrastructure to test that SQLite handles this
28995 ** function failing.
28997 SimulateIOError( return SQLITE_IOERR );
28999 zDir = unixTempFileDir();
29000 if( zDir==0 ) zDir = ".";
29002 /* Check that the output buffer is large enough for the temporary file
29003 ** name. If it is not, return SQLITE_ERROR.
29005 if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
29006 return SQLITE_ERROR;
29010 sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29011 j = (int)strlen(zBuf);
29012 sqlite3_randomness(15, &zBuf[j]);
29013 for(i=0; i<15; i++, j++){
29014 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29016 zBuf[j] = 0;
29017 zBuf[j+1] = 0;
29018 }while( osAccess(zBuf,0)==0 );
29019 return SQLITE_OK;
29022 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29024 ** Routine to transform a unixFile into a proxy-locking unixFile.
29025 ** Implementation in the proxy-lock division, but used by unixOpen()
29026 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
29028 static int proxyTransformUnixFile(unixFile*, const char*);
29029 #endif
29032 ** Search for an unused file descriptor that was opened on the database
29033 ** file (not a journal or master-journal file) identified by pathname
29034 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29035 ** argument to this function.
29037 ** Such a file descriptor may exist if a database connection was closed
29038 ** but the associated file descriptor could not be closed because some
29039 ** other file descriptor open on the same file is holding a file-lock.
29040 ** Refer to comments in the unixClose() function and the lengthy comment
29041 ** describing "Posix Advisory Locking" at the start of this file for
29042 ** further details. Also, ticket #4018.
29044 ** If a suitable file descriptor is found, then it is returned. If no
29045 ** such file descriptor is located, -1 is returned.
29047 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29048 UnixUnusedFd *pUnused = 0;
29050 /* Do not search for an unused file descriptor on vxworks. Not because
29051 ** vxworks would not benefit from the change (it might, we're not sure),
29052 ** but because no way to test it is currently available. It is better
29053 ** not to risk breaking vxworks support for the sake of such an obscure
29054 ** feature. */
29055 #if !OS_VXWORKS
29056 struct stat sStat; /* Results of stat() call */
29058 /* A stat() call may fail for various reasons. If this happens, it is
29059 ** almost certain that an open() call on the same path will also fail.
29060 ** For this reason, if an error occurs in the stat() call here, it is
29061 ** ignored and -1 is returned. The caller will try to open a new file
29062 ** descriptor on the same path, fail, and return an error to SQLite.
29064 ** Even if a subsequent open() call does succeed, the consequences of
29065 ** not searching for a resusable file descriptor are not dire. */
29066 if( 0==osStat(zPath, &sStat) ){
29067 unixInodeInfo *pInode;
29069 unixEnterMutex();
29070 pInode = inodeList;
29071 while( pInode && (pInode->fileId.dev!=sStat.st_dev
29072 || pInode->fileId.ino!=sStat.st_ino) ){
29073 pInode = pInode->pNext;
29075 if( pInode ){
29076 UnixUnusedFd **pp;
29077 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29078 pUnused = *pp;
29079 if( pUnused ){
29080 *pp = pUnused->pNext;
29083 unixLeaveMutex();
29085 #endif /* if !OS_VXWORKS */
29086 return pUnused;
29090 ** This function is called by unixOpen() to determine the unix permissions
29091 ** to create new files with. If no error occurs, then SQLITE_OK is returned
29092 ** and a value suitable for passing as the third argument to open(2) is
29093 ** written to *pMode. If an IO error occurs, an SQLite error code is
29094 ** returned and the value of *pMode is not modified.
29096 ** In most cases cases, this routine sets *pMode to 0, which will become
29097 ** an indication to robust_open() to create the file using
29098 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
29099 ** But if the file being opened is a WAL or regular journal file, then
29100 ** this function queries the file-system for the permissions on the
29101 ** corresponding database file and sets *pMode to this value. Whenever
29102 ** possible, WAL and journal files are created using the same permissions
29103 ** as the associated database file.
29105 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29106 ** original filename is unavailable. But 8_3_NAMES is only used for
29107 ** FAT filesystems and permissions do not matter there, so just use
29108 ** the default permissions.
29110 static int findCreateFileMode(
29111 const char *zPath, /* Path of file (possibly) being created */
29112 int flags, /* Flags passed as 4th argument to xOpen() */
29113 mode_t *pMode, /* OUT: Permissions to open file with */
29114 uid_t *pUid, /* OUT: uid to set on the file */
29115 gid_t *pGid /* OUT: gid to set on the file */
29117 int rc = SQLITE_OK; /* Return Code */
29118 *pMode = 0;
29119 *pUid = 0;
29120 *pGid = 0;
29121 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29122 char zDb[MAX_PATHNAME+1]; /* Database file path */
29123 int nDb; /* Number of valid bytes in zDb */
29124 struct stat sStat; /* Output of stat() on database file */
29126 /* zPath is a path to a WAL or journal file. The following block derives
29127 ** the path to the associated database file from zPath. This block handles
29128 ** the following naming conventions:
29130 ** "<path to db>-journal"
29131 ** "<path to db>-wal"
29132 ** "<path to db>-journalNN"
29133 ** "<path to db>-walNN"
29135 ** where NN is a decimal number. The NN naming schemes are
29136 ** used by the test_multiplex.c module.
29138 nDb = sqlite3Strlen30(zPath) - 1;
29139 #ifdef SQLITE_ENABLE_8_3_NAMES
29140 while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
29141 if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
29142 #else
29143 while( zPath[nDb]!='-' ){
29144 assert( nDb>0 );
29145 assert( zPath[nDb]!='\n' );
29146 nDb--;
29148 #endif
29149 memcpy(zDb, zPath, nDb);
29150 zDb[nDb] = '\0';
29152 if( 0==osStat(zDb, &sStat) ){
29153 *pMode = sStat.st_mode & 0777;
29154 *pUid = sStat.st_uid;
29155 *pGid = sStat.st_gid;
29156 }else{
29157 rc = SQLITE_IOERR_FSTAT;
29159 }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29160 *pMode = 0600;
29162 return rc;
29166 ** Open the file zPath.
29168 ** Previously, the SQLite OS layer used three functions in place of this
29169 ** one:
29171 ** sqlite3OsOpenReadWrite();
29172 ** sqlite3OsOpenReadOnly();
29173 ** sqlite3OsOpenExclusive();
29175 ** These calls correspond to the following combinations of flags:
29177 ** ReadWrite() -> (READWRITE | CREATE)
29178 ** ReadOnly() -> (READONLY)
29179 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29181 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29182 ** true, the file was configured to be automatically deleted when the
29183 ** file handle closed. To achieve the same effect using this new
29184 ** interface, add the DELETEONCLOSE flag to those specified above for
29185 ** OpenExclusive().
29187 static int unixOpen(
29188 sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
29189 const char *zPath, /* Pathname of file to be opened */
29190 sqlite3_file *pFile, /* The file descriptor to be filled in */
29191 int flags, /* Input flags to control the opening */
29192 int *pOutFlags /* Output flags returned to SQLite core */
29194 unixFile *p = (unixFile *)pFile;
29195 int fd = -1; /* File descriptor returned by open() */
29196 int openFlags = 0; /* Flags to pass to open() */
29197 int eType = flags&0xFFFFFF00; /* Type of file to open */
29198 int noLock; /* True to omit locking primitives */
29199 int rc = SQLITE_OK; /* Function Return Code */
29200 int ctrlFlags = 0; /* UNIXFILE_* flags */
29202 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
29203 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
29204 int isCreate = (flags & SQLITE_OPEN_CREATE);
29205 int isReadonly = (flags & SQLITE_OPEN_READONLY);
29206 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
29207 #if SQLITE_ENABLE_LOCKING_STYLE
29208 int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
29209 #endif
29210 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29211 struct statfs fsInfo;
29212 #endif
29214 /* If creating a master or main-file journal, this function will open
29215 ** a file-descriptor on the directory too. The first time unixSync()
29216 ** is called the directory file descriptor will be fsync()ed and close()d.
29218 int syncDir = (isCreate && (
29219 eType==SQLITE_OPEN_MASTER_JOURNAL
29220 || eType==SQLITE_OPEN_MAIN_JOURNAL
29221 || eType==SQLITE_OPEN_WAL
29224 /* If argument zPath is a NULL pointer, this function is required to open
29225 ** a temporary file. Use this buffer to store the file name in.
29227 char zTmpname[MAX_PATHNAME+2];
29228 const char *zName = zPath;
29230 /* Check the following statements are true:
29232 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
29233 ** (b) if CREATE is set, then READWRITE must also be set, and
29234 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
29235 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
29237 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29238 assert(isCreate==0 || isReadWrite);
29239 assert(isExclusive==0 || isCreate);
29240 assert(isDelete==0 || isCreate);
29242 /* The main DB, main journal, WAL file and master journal are never
29243 ** automatically deleted. Nor are they ever temporary files. */
29244 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29245 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29246 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29247 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29249 /* Assert that the upper layer has set one of the "file-type" flags. */
29250 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
29251 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29252 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
29253 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29256 /* Detect a pid change and reset the PRNG. There is a race condition
29257 ** here such that two or more threads all trying to open databases at
29258 ** the same instant might all reset the PRNG. But multiple resets
29259 ** are harmless.
29261 if( randomnessPid!=getpid() ){
29262 randomnessPid = getpid();
29263 sqlite3_randomness(0,0);
29266 memset(p, 0, sizeof(unixFile));
29268 if( eType==SQLITE_OPEN_MAIN_DB ){
29269 UnixUnusedFd *pUnused;
29270 pUnused = findReusableFd(zName, flags);
29271 if( pUnused ){
29272 fd = pUnused->fd;
29273 }else{
29274 pUnused = sqlite3_malloc(sizeof(*pUnused));
29275 if( !pUnused ){
29276 return SQLITE_NOMEM;
29279 p->pUnused = pUnused;
29281 /* Database filenames are double-zero terminated if they are not
29282 ** URIs with parameters. Hence, they can always be passed into
29283 ** sqlite3_uri_parameter(). */
29284 assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
29286 }else if( !zName ){
29287 /* If zName is NULL, the upper layer is requesting a temp file. */
29288 assert(isDelete && !syncDir);
29289 rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
29290 if( rc!=SQLITE_OK ){
29291 return rc;
29293 zName = zTmpname;
29295 /* Generated temporary filenames are always double-zero terminated
29296 ** for use by sqlite3_uri_parameter(). */
29297 assert( zName[strlen(zName)+1]==0 );
29300 /* Determine the value of the flags parameter passed to POSIX function
29301 ** open(). These must be calculated even if open() is not called, as
29302 ** they may be stored as part of the file handle and used by the
29303 ** 'conch file' locking functions later on. */
29304 if( isReadonly ) openFlags |= O_RDONLY;
29305 if( isReadWrite ) openFlags |= O_RDWR;
29306 if( isCreate ) openFlags |= O_CREAT;
29307 if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29308 openFlags |= (O_LARGEFILE|O_BINARY);
29310 if( fd<0 ){
29311 mode_t openMode; /* Permissions to create file with */
29312 uid_t uid; /* Userid for the file */
29313 gid_t gid; /* Groupid for the file */
29314 rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
29315 if( rc!=SQLITE_OK ){
29316 assert( !p->pUnused );
29317 assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29318 return rc;
29320 fd = robust_open(zName, openFlags, openMode);
29321 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
29322 if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29323 /* Failed to open the file for read/write access. Try read-only. */
29324 flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29325 openFlags &= ~(O_RDWR|O_CREAT);
29326 flags |= SQLITE_OPEN_READONLY;
29327 openFlags |= O_RDONLY;
29328 isReadonly = 1;
29329 fd = robust_open(zName, openFlags, openMode);
29331 if( fd<0 ){
29332 rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29333 goto open_finished;
29336 /* If this process is running as root and if creating a new rollback
29337 ** journal or WAL file, set the ownership of the journal or WAL to be
29338 ** the same as the original database.
29340 if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29341 osFchown(fd, uid, gid);
29344 assert( fd>=0 );
29345 if( pOutFlags ){
29346 *pOutFlags = flags;
29349 if( p->pUnused ){
29350 p->pUnused->fd = fd;
29351 p->pUnused->flags = flags;
29354 if( isDelete ){
29355 #if OS_VXWORKS
29356 zPath = zName;
29357 #else
29358 osUnlink(zName);
29359 #endif
29361 #if SQLITE_ENABLE_LOCKING_STYLE
29362 else{
29363 p->openFlags = openFlags;
29365 #endif
29367 noLock = eType!=SQLITE_OPEN_MAIN_DB;
29370 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29371 if( fstatfs(fd, &fsInfo) == -1 ){
29372 ((unixFile*)pFile)->lastErrno = errno;
29373 robust_close(p, fd, __LINE__);
29374 return SQLITE_IOERR_ACCESS;
29376 if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29377 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29379 #endif
29381 /* Set up appropriate ctrlFlags */
29382 if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
29383 if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
29384 if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
29385 if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
29386 if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
29388 #if SQLITE_ENABLE_LOCKING_STYLE
29389 #if SQLITE_PREFER_PROXY_LOCKING
29390 isAutoProxy = 1;
29391 #endif
29392 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29393 char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29394 int useProxy = 0;
29396 /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29397 ** never use proxy, NULL means use proxy for non-local files only. */
29398 if( envforce!=NULL ){
29399 useProxy = atoi(envforce)>0;
29400 }else{
29401 if( statfs(zPath, &fsInfo) == -1 ){
29402 /* In theory, the close(fd) call is sub-optimal. If the file opened
29403 ** with fd is a database file, and there are other connections open
29404 ** on that file that are currently holding advisory locks on it,
29405 ** then the call to close() will cancel those locks. In practice,
29406 ** we're assuming that statfs() doesn't fail very often. At least
29407 ** not while other file descriptors opened by the same process on
29408 ** the same file are working. */
29409 p->lastErrno = errno;
29410 robust_close(p, fd, __LINE__);
29411 rc = SQLITE_IOERR_ACCESS;
29412 goto open_finished;
29414 useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29416 if( useProxy ){
29417 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
29418 if( rc==SQLITE_OK ){
29419 rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29420 if( rc!=SQLITE_OK ){
29421 /* Use unixClose to clean up the resources added in fillInUnixFile
29422 ** and clear all the structure's references. Specifically,
29423 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29425 unixClose(pFile);
29426 return rc;
29429 goto open_finished;
29432 #endif
29434 rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
29436 open_finished:
29437 if( rc!=SQLITE_OK ){
29438 sqlite3_free(p->pUnused);
29440 return rc;
29445 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29446 ** the directory after deleting the file.
29448 static int unixDelete(
29449 sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
29450 const char *zPath, /* Name of file to be deleted */
29451 int dirSync /* If true, fsync() directory after deleting file */
29453 int rc = SQLITE_OK;
29454 UNUSED_PARAMETER(NotUsed);
29455 SimulateIOError(return SQLITE_IOERR_DELETE);
29456 if( osUnlink(zPath)==(-1) ){
29457 if( errno==ENOENT ){
29458 rc = SQLITE_IOERR_DELETE_NOENT;
29459 }else{
29460 rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29462 return rc;
29464 #ifndef SQLITE_DISABLE_DIRSYNC
29465 if( (dirSync & 1)!=0 ){
29466 int fd;
29467 rc = osOpenDirectory(zPath, &fd);
29468 if( rc==SQLITE_OK ){
29469 #if OS_VXWORKS
29470 if( fsync(fd)==-1 )
29471 #else
29472 if( fsync(fd) )
29473 #endif
29475 rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29477 robust_close(0, fd, __LINE__);
29478 }else if( rc==SQLITE_CANTOPEN ){
29479 rc = SQLITE_OK;
29482 #endif
29483 return rc;
29487 ** Test the existence of or access permissions of file zPath. The
29488 ** test performed depends on the value of flags:
29490 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29491 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29492 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29494 ** Otherwise return 0.
29496 static int unixAccess(
29497 sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
29498 const char *zPath, /* Path of the file to examine */
29499 int flags, /* What do we want to learn about the zPath file? */
29500 int *pResOut /* Write result boolean here */
29502 int amode = 0;
29503 UNUSED_PARAMETER(NotUsed);
29504 SimulateIOError( return SQLITE_IOERR_ACCESS; );
29505 switch( flags ){
29506 case SQLITE_ACCESS_EXISTS:
29507 amode = F_OK;
29508 break;
29509 case SQLITE_ACCESS_READWRITE:
29510 amode = W_OK|R_OK;
29511 break;
29512 case SQLITE_ACCESS_READ:
29513 amode = R_OK;
29514 break;
29516 default:
29517 assert(!"Invalid flags argument");
29519 *pResOut = (osAccess(zPath, amode)==0);
29520 if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29521 struct stat buf;
29522 if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29523 *pResOut = 0;
29526 return SQLITE_OK;
29531 ** Turn a relative pathname into a full pathname. The relative path
29532 ** is stored as a nul-terminated string in the buffer pointed to by
29533 ** zPath.
29535 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29536 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29537 ** this buffer before returning.
29539 static int unixFullPathname(
29540 sqlite3_vfs *pVfs, /* Pointer to vfs object */
29541 const char *zPath, /* Possibly relative input path */
29542 int nOut, /* Size of output buffer in bytes */
29543 char *zOut /* Output buffer */
29546 /* It's odd to simulate an io-error here, but really this is just
29547 ** using the io-error infrastructure to test that SQLite handles this
29548 ** function failing. This function could fail if, for example, the
29549 ** current working directory has been unlinked.
29551 SimulateIOError( return SQLITE_ERROR );
29553 assert( pVfs->mxPathname==MAX_PATHNAME );
29554 UNUSED_PARAMETER(pVfs);
29556 zOut[nOut-1] = '\0';
29557 if( zPath[0]=='/' ){
29558 sqlite3_snprintf(nOut, zOut, "%s", zPath);
29559 }else{
29560 int nCwd;
29561 if( osGetcwd(zOut, nOut-1)==0 ){
29562 return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29564 nCwd = (int)strlen(zOut);
29565 sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29567 return SQLITE_OK;
29571 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29573 ** Interfaces for opening a shared library, finding entry points
29574 ** within the shared library, and closing the shared library.
29576 #include <dlfcn.h>
29577 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29578 UNUSED_PARAMETER(NotUsed);
29579 return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29583 ** SQLite calls this function immediately after a call to unixDlSym() or
29584 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29585 ** message is available, it is written to zBufOut. If no error message
29586 ** is available, zBufOut is left unmodified and SQLite uses a default
29587 ** error message.
29589 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29590 const char *zErr;
29591 UNUSED_PARAMETER(NotUsed);
29592 unixEnterMutex();
29593 zErr = dlerror();
29594 if( zErr ){
29595 sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29597 unixLeaveMutex();
29599 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29601 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29602 ** cast into a pointer to a function. And yet the library dlsym() routine
29603 ** returns a void* which is really a pointer to a function. So how do we
29604 ** use dlsym() with -pedantic-errors?
29606 ** Variable x below is defined to be a pointer to a function taking
29607 ** parameters void* and const char* and returning a pointer to a function.
29608 ** We initialize x by assigning it a pointer to the dlsym() function.
29609 ** (That assignment requires a cast.) Then we call the function that
29610 ** x points to.
29612 ** This work-around is unlikely to work correctly on any system where
29613 ** you really cannot cast a function pointer into void*. But then, on the
29614 ** other hand, dlsym() will not work on such a system either, so we have
29615 ** not really lost anything.
29617 void (*(*x)(void*,const char*))(void);
29618 UNUSED_PARAMETER(NotUsed);
29619 x = (void(*(*)(void*,const char*))(void))dlsym;
29620 return (*x)(p, zSym);
29622 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29623 UNUSED_PARAMETER(NotUsed);
29624 dlclose(pHandle);
29626 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29627 #define unixDlOpen 0
29628 #define unixDlError 0
29629 #define unixDlSym 0
29630 #define unixDlClose 0
29631 #endif
29634 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29636 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29637 UNUSED_PARAMETER(NotUsed);
29638 assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29640 /* We have to initialize zBuf to prevent valgrind from reporting
29641 ** errors. The reports issued by valgrind are incorrect - we would
29642 ** prefer that the randomness be increased by making use of the
29643 ** uninitialized space in zBuf - but valgrind errors tend to worry
29644 ** some users. Rather than argue, it seems easier just to initialize
29645 ** the whole array and silence valgrind, even if that means less randomness
29646 ** in the random seed.
29648 ** When testing, initializing zBuf[] to zero is all we do. That means
29649 ** that we always use the same random number sequence. This makes the
29650 ** tests repeatable.
29652 memset(zBuf, 0, nBuf);
29653 randomnessPid = getpid();
29654 #if !defined(SQLITE_TEST)
29656 int fd, got;
29657 fd = robust_open("/dev/urandom", O_RDONLY, 0);
29658 if( fd<0 ){
29659 time_t t;
29660 time(&t);
29661 memcpy(zBuf, &t, sizeof(t));
29662 memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
29663 assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
29664 nBuf = sizeof(t) + sizeof(randomnessPid);
29665 }else{
29666 do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
29667 robust_close(0, fd, __LINE__);
29670 #endif
29671 return nBuf;
29676 ** Sleep for a little while. Return the amount of time slept.
29677 ** The argument is the number of microseconds we want to sleep.
29678 ** The return value is the number of microseconds of sleep actually
29679 ** requested from the underlying operating system, a number which
29680 ** might be greater than or equal to the argument, but not less
29681 ** than the argument.
29683 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29684 #if OS_VXWORKS
29685 struct timespec sp;
29687 sp.tv_sec = microseconds / 1000000;
29688 sp.tv_nsec = (microseconds % 1000000) * 1000;
29689 nanosleep(&sp, NULL);
29690 UNUSED_PARAMETER(NotUsed);
29691 return microseconds;
29692 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29693 usleep(microseconds);
29694 UNUSED_PARAMETER(NotUsed);
29695 return microseconds;
29696 #else
29697 int seconds = (microseconds+999999)/1000000;
29698 sleep(seconds);
29699 UNUSED_PARAMETER(NotUsed);
29700 return seconds*1000000;
29701 #endif
29705 ** The following variable, if set to a non-zero value, is interpreted as
29706 ** the number of seconds since 1970 and is used to set the result of
29707 ** sqlite3OsCurrentTime() during testing.
29709 #ifdef SQLITE_TEST
29710 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
29711 #endif
29714 ** Find the current time (in Universal Coordinated Time). Write into *piNow
29715 ** the current time and date as a Julian Day number times 86_400_000. In
29716 ** other words, write into *piNow the number of milliseconds since the Julian
29717 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29718 ** proleptic Gregorian calendar.
29720 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
29721 ** cannot be found.
29723 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29724 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29725 int rc = SQLITE_OK;
29726 #if defined(NO_GETTOD)
29727 time_t t;
29728 time(&t);
29729 *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29730 #elif OS_VXWORKS
29731 struct timespec sNow;
29732 clock_gettime(CLOCK_REALTIME, &sNow);
29733 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29734 #else
29735 struct timeval sNow;
29736 if( gettimeofday(&sNow, 0)==0 ){
29737 *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29738 }else{
29739 rc = SQLITE_ERROR;
29741 #endif
29743 #ifdef SQLITE_TEST
29744 if( sqlite3_current_time ){
29745 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29747 #endif
29748 UNUSED_PARAMETER(NotUsed);
29749 return rc;
29753 ** Find the current time (in Universal Coordinated Time). Write the
29754 ** current time and date as a Julian Day number into *prNow and
29755 ** return 0. Return 1 if the time and date cannot be found.
29757 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29758 sqlite3_int64 i = 0;
29759 int rc;
29760 UNUSED_PARAMETER(NotUsed);
29761 rc = unixCurrentTimeInt64(0, &i);
29762 *prNow = i/86400000.0;
29763 return rc;
29767 ** We added the xGetLastError() method with the intention of providing
29768 ** better low-level error messages when operating-system problems come up
29769 ** during SQLite operation. But so far, none of that has been implemented
29770 ** in the core. So this routine is never called. For now, it is merely
29771 ** a place-holder.
29773 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29774 UNUSED_PARAMETER(NotUsed);
29775 UNUSED_PARAMETER(NotUsed2);
29776 UNUSED_PARAMETER(NotUsed3);
29777 return 0;
29782 ************************ End of sqlite3_vfs methods ***************************
29783 ******************************************************************************/
29785 /******************************************************************************
29786 ************************** Begin Proxy Locking ********************************
29788 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
29789 ** other locking methods on secondary lock files. Proxy locking is a
29790 ** meta-layer over top of the primitive locking implemented above. For
29791 ** this reason, the division that implements of proxy locking is deferred
29792 ** until late in the file (here) after all of the other I/O methods have
29793 ** been defined - so that the primitive locking methods are available
29794 ** as services to help with the implementation of proxy locking.
29796 ****
29798 ** The default locking schemes in SQLite use byte-range locks on the
29799 ** database file to coordinate safe, concurrent access by multiple readers
29800 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
29801 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29802 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29803 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29804 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29805 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29806 ** address in the shared range is taken for a SHARED lock, the entire
29807 ** shared range is taken for an EXCLUSIVE lock):
29809 ** PENDING_BYTE 0x40000000
29810 ** RESERVED_BYTE 0x40000001
29811 ** SHARED_RANGE 0x40000002 -> 0x40000200
29813 ** This works well on the local file system, but shows a nearly 100x
29814 ** slowdown in read performance on AFP because the AFP client disables
29815 ** the read cache when byte-range locks are present. Enabling the read
29816 ** cache exposes a cache coherency problem that is present on all OS X
29817 ** supported network file systems. NFS and AFP both observe the
29818 ** close-to-open semantics for ensuring cache coherency
29819 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29820 ** address the requirements for concurrent database access by multiple
29821 ** readers and writers
29822 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29824 ** To address the performance and cache coherency issues, proxy file locking
29825 ** changes the way database access is controlled by limiting access to a
29826 ** single host at a time and moving file locks off of the database file
29827 ** and onto a proxy file on the local file system.
29830 ** Using proxy locks
29831 ** -----------------
29833 ** C APIs
29835 ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29836 ** <proxy_path> | ":auto:");
29837 ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29840 ** SQL pragmas
29842 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29843 ** PRAGMA [database.]lock_proxy_file
29845 ** Specifying ":auto:" means that if there is a conch file with a matching
29846 ** host ID in it, the proxy path in the conch file will be used, otherwise
29847 ** a proxy path based on the user's temp dir
29848 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29849 ** actual proxy file name is generated from the name and path of the
29850 ** database file. For example:
29852 ** For database path "/Users/me/foo.db"
29853 ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29855 ** Once a lock proxy is configured for a database connection, it can not
29856 ** be removed, however it may be switched to a different proxy path via
29857 ** the above APIs (assuming the conch file is not being held by another
29858 ** connection or process).
29861 ** How proxy locking works
29862 ** -----------------------
29864 ** Proxy file locking relies primarily on two new supporting files:
29866 ** * conch file to limit access to the database file to a single host
29867 ** at a time
29869 ** * proxy file to act as a proxy for the advisory locks normally
29870 ** taken on the database
29872 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29873 ** by taking an sqlite-style shared lock on the conch file, reading the
29874 ** contents and comparing the host's unique host ID (see below) and lock
29875 ** proxy path against the values stored in the conch. The conch file is
29876 ** stored in the same directory as the database file and the file name
29877 ** is patterned after the database file name as ".<databasename>-conch".
29878 ** If the conch file does not exist, or it's contents do not match the
29879 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29880 ** lock and the conch file contents is updated with the host ID and proxy
29881 ** path and the lock is downgraded to a shared lock again. If the conch
29882 ** is held by another process (with a shared lock), the exclusive lock
29883 ** will fail and SQLITE_BUSY is returned.
29885 ** The proxy file - a single-byte file used for all advisory file locks
29886 ** normally taken on the database file. This allows for safe sharing
29887 ** of the database file for multiple readers and writers on the same
29888 ** host (the conch ensures that they all use the same local lock file).
29890 ** Requesting the lock proxy does not immediately take the conch, it is
29891 ** only taken when the first request to lock database file is made.
29892 ** This matches the semantics of the traditional locking behavior, where
29893 ** opening a connection to a database file does not take a lock on it.
29894 ** The shared lock and an open file descriptor are maintained until
29895 ** the connection to the database is closed.
29897 ** The proxy file and the lock file are never deleted so they only need
29898 ** to be created the first time they are used.
29900 ** Configuration options
29901 ** ---------------------
29903 ** SQLITE_PREFER_PROXY_LOCKING
29905 ** Database files accessed on non-local file systems are
29906 ** automatically configured for proxy locking, lock files are
29907 ** named automatically using the same logic as
29908 ** PRAGMA lock_proxy_file=":auto:"
29910 ** SQLITE_PROXY_DEBUG
29912 ** Enables the logging of error messages during host id file
29913 ** retrieval and creation
29915 ** LOCKPROXYDIR
29917 ** Overrides the default directory used for lock proxy files that
29918 ** are named automatically via the ":auto:" setting
29920 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29922 ** Permissions to use when creating a directory for storing the
29923 ** lock proxy files, only used when LOCKPROXYDIR is not set.
29926 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29927 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29928 ** force proxy locking to be used for every database file opened, and 0
29929 ** will force automatic proxy locking to be disabled for all database
29930 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29931 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29935 ** Proxy locking is only available on MacOSX
29937 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29940 ** The proxyLockingContext has the path and file structures for the remote
29941 ** and local proxy files in it
29943 typedef struct proxyLockingContext proxyLockingContext;
29944 struct proxyLockingContext {
29945 unixFile *conchFile; /* Open conch file */
29946 char *conchFilePath; /* Name of the conch file */
29947 unixFile *lockProxy; /* Open proxy lock file */
29948 char *lockProxyPath; /* Name of the proxy lock file */
29949 char *dbPath; /* Name of the open file */
29950 int conchHeld; /* 1 if the conch is held, -1 if lockless */
29951 void *oldLockingContext; /* Original lockingcontext to restore on close */
29952 sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
29956 ** The proxy lock file path for the database at dbPath is written into lPath,
29957 ** which must point to valid, writable memory large enough for a maxLen length
29958 ** file path.
29960 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29961 int len;
29962 int dbLen;
29963 int i;
29965 #ifdef LOCKPROXYDIR
29966 len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29967 #else
29968 # ifdef _CS_DARWIN_USER_TEMP_DIR
29970 if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29971 OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
29972 lPath, errno, getpid()));
29973 return SQLITE_IOERR_LOCK;
29975 len = strlcat(lPath, "sqliteplocks", maxLen);
29977 # else
29978 len = strlcpy(lPath, "/tmp/", maxLen);
29979 # endif
29980 #endif
29982 if( lPath[len-1]!='/' ){
29983 len = strlcat(lPath, "/", maxLen);
29986 /* transform the db path to a unique cache name */
29987 dbLen = (int)strlen(dbPath);
29988 for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29989 char c = dbPath[i];
29990 lPath[i+len] = (c=='/')?'_':c;
29992 lPath[i+len]='\0';
29993 strlcat(lPath, ":auto:", maxLen);
29994 OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
29995 return SQLITE_OK;
29999 ** Creates the lock file and any missing directories in lockPath
30001 static int proxyCreateLockPath(const char *lockPath){
30002 int i, len;
30003 char buf[MAXPATHLEN];
30004 int start = 0;
30006 assert(lockPath!=NULL);
30007 /* try to create all the intermediate directories */
30008 len = (int)strlen(lockPath);
30009 buf[0] = lockPath[0];
30010 for( i=1; i<len; i++ ){
30011 if( lockPath[i] == '/' && (i - start > 0) ){
30012 /* only mkdir if leaf dir != "." or "/" or ".." */
30013 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
30014 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30015 buf[i]='\0';
30016 if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30017 int err=errno;
30018 if( err!=EEXIST ) {
30019 OSTRACE(("CREATELOCKPATH FAILED creating %s, "
30020 "'%s' proxy lock path=%s pid=%d\n",
30021 buf, strerror(err), lockPath, getpid()));
30022 return err;
30026 start=i+1;
30028 buf[i] = lockPath[i];
30030 OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
30031 return 0;
30035 ** Create a new VFS file descriptor (stored in memory obtained from
30036 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
30038 ** The caller is responsible not only for closing the file descriptor
30039 ** but also for freeing the memory associated with the file descriptor.
30041 static int proxyCreateUnixFile(
30042 const char *path, /* path for the new unixFile */
30043 unixFile **ppFile, /* unixFile created and returned by ref */
30044 int islockfile /* if non zero missing dirs will be created */
30046 int fd = -1;
30047 unixFile *pNew;
30048 int rc = SQLITE_OK;
30049 int openFlags = O_RDWR | O_CREAT;
30050 sqlite3_vfs dummyVfs;
30051 int terrno = 0;
30052 UnixUnusedFd *pUnused = NULL;
30054 /* 1. first try to open/create the file
30055 ** 2. if that fails, and this is a lock file (not-conch), try creating
30056 ** the parent directories and then try again.
30057 ** 3. if that fails, try to open the file read-only
30058 ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30060 pUnused = findReusableFd(path, openFlags);
30061 if( pUnused ){
30062 fd = pUnused->fd;
30063 }else{
30064 pUnused = sqlite3_malloc(sizeof(*pUnused));
30065 if( !pUnused ){
30066 return SQLITE_NOMEM;
30069 if( fd<0 ){
30070 fd = robust_open(path, openFlags, 0);
30071 terrno = errno;
30072 if( fd<0 && errno==ENOENT && islockfile ){
30073 if( proxyCreateLockPath(path) == SQLITE_OK ){
30074 fd = robust_open(path, openFlags, 0);
30078 if( fd<0 ){
30079 openFlags = O_RDONLY;
30080 fd = robust_open(path, openFlags, 0);
30081 terrno = errno;
30083 if( fd<0 ){
30084 if( islockfile ){
30085 return SQLITE_BUSY;
30087 switch (terrno) {
30088 case EACCES:
30089 return SQLITE_PERM;
30090 case EIO:
30091 return SQLITE_IOERR_LOCK; /* even though it is the conch */
30092 default:
30093 return SQLITE_CANTOPEN_BKPT;
30097 pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30098 if( pNew==NULL ){
30099 rc = SQLITE_NOMEM;
30100 goto end_create_proxy;
30102 memset(pNew, 0, sizeof(unixFile));
30103 pNew->openFlags = openFlags;
30104 memset(&dummyVfs, 0, sizeof(dummyVfs));
30105 dummyVfs.pAppData = (void*)&autolockIoFinder;
30106 dummyVfs.zName = "dummy";
30107 pUnused->fd = fd;
30108 pUnused->flags = openFlags;
30109 pNew->pUnused = pUnused;
30111 rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
30112 if( rc==SQLITE_OK ){
30113 *ppFile = pNew;
30114 return SQLITE_OK;
30116 end_create_proxy:
30117 robust_close(pNew, fd, __LINE__);
30118 sqlite3_free(pNew);
30119 sqlite3_free(pUnused);
30120 return rc;
30123 #ifdef SQLITE_TEST
30124 /* simulate multiple hosts by creating unique hostid file paths */
30125 SQLITE_API int sqlite3_hostid_num = 0;
30126 #endif
30128 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
30130 /* Not always defined in the headers as it ought to be */
30131 extern int gethostuuid(uuid_t id, const struct timespec *wait);
30133 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
30134 ** bytes of writable memory.
30136 static int proxyGetHostID(unsigned char *pHostID, int *pError){
30137 assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30138 memset(pHostID, 0, PROXY_HOSTIDLEN);
30139 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30140 && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30142 static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30143 if( gethostuuid(pHostID, &timeout) ){
30144 int err = errno;
30145 if( pError ){
30146 *pError = err;
30148 return SQLITE_IOERR;
30151 #else
30152 UNUSED_PARAMETER(pError);
30153 #endif
30154 #ifdef SQLITE_TEST
30155 /* simulate multiple hosts by creating unique hostid file paths */
30156 if( sqlite3_hostid_num != 0){
30157 pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30159 #endif
30161 return SQLITE_OK;
30164 /* The conch file contains the header, host id and lock file path
30166 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
30167 #define PROXY_HEADERLEN 1 /* conch file header length */
30168 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30169 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30172 ** Takes an open conch file, copies the contents to a new path and then moves
30173 ** it back. The newly created file's file descriptor is assigned to the
30174 ** conch file structure and finally the original conch file descriptor is
30175 ** closed. Returns zero if successful.
30177 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30178 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30179 unixFile *conchFile = pCtx->conchFile;
30180 char tPath[MAXPATHLEN];
30181 char buf[PROXY_MAXCONCHLEN];
30182 char *cPath = pCtx->conchFilePath;
30183 size_t readLen = 0;
30184 size_t pathLen = 0;
30185 char errmsg[64] = "";
30186 int fd = -1;
30187 int rc = -1;
30188 UNUSED_PARAMETER(myHostID);
30190 /* create a new path by replace the trailing '-conch' with '-break' */
30191 pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30192 if( pathLen>MAXPATHLEN || pathLen<6 ||
30193 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30194 sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30195 goto end_breaklock;
30197 /* read the conch content */
30198 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30199 if( readLen<PROXY_PATHINDEX ){
30200 sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30201 goto end_breaklock;
30203 /* write it out to the temporary break file */
30204 fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
30205 if( fd<0 ){
30206 sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30207 goto end_breaklock;
30209 if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30210 sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30211 goto end_breaklock;
30213 if( rename(tPath, cPath) ){
30214 sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30215 goto end_breaklock;
30217 rc = 0;
30218 fprintf(stderr, "broke stale lock on %s\n", cPath);
30219 robust_close(pFile, conchFile->h, __LINE__);
30220 conchFile->h = fd;
30221 conchFile->openFlags = O_RDWR | O_CREAT;
30223 end_breaklock:
30224 if( rc ){
30225 if( fd>=0 ){
30226 osUnlink(tPath);
30227 robust_close(pFile, fd, __LINE__);
30229 fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30231 return rc;
30234 /* Take the requested lock on the conch file and break a stale lock if the
30235 ** host id matches.
30237 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30238 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30239 unixFile *conchFile = pCtx->conchFile;
30240 int rc = SQLITE_OK;
30241 int nTries = 0;
30242 struct timespec conchModTime;
30244 memset(&conchModTime, 0, sizeof(conchModTime));
30245 do {
30246 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30247 nTries ++;
30248 if( rc==SQLITE_BUSY ){
30249 /* If the lock failed (busy):
30250 * 1st try: get the mod time of the conch, wait 0.5s and try again.
30251 * 2nd try: fail if the mod time changed or host id is different, wait
30252 * 10 sec and try again
30253 * 3rd try: break the lock unless the mod time has changed.
30255 struct stat buf;
30256 if( osFstat(conchFile->h, &buf) ){
30257 pFile->lastErrno = errno;
30258 return SQLITE_IOERR_LOCK;
30261 if( nTries==1 ){
30262 conchModTime = buf.st_mtimespec;
30263 usleep(500000); /* wait 0.5 sec and try the lock again*/
30264 continue;
30267 assert( nTries>1 );
30268 if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30269 conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30270 return SQLITE_BUSY;
30273 if( nTries==2 ){
30274 char tBuf[PROXY_MAXCONCHLEN];
30275 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30276 if( len<0 ){
30277 pFile->lastErrno = errno;
30278 return SQLITE_IOERR_LOCK;
30280 if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30281 /* don't break the lock if the host id doesn't match */
30282 if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30283 return SQLITE_BUSY;
30285 }else{
30286 /* don't break the lock on short read or a version mismatch */
30287 return SQLITE_BUSY;
30289 usleep(10000000); /* wait 10 sec and try the lock again */
30290 continue;
30293 assert( nTries==3 );
30294 if( 0==proxyBreakConchLock(pFile, myHostID) ){
30295 rc = SQLITE_OK;
30296 if( lockType==EXCLUSIVE_LOCK ){
30297 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30299 if( !rc ){
30300 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30304 } while( rc==SQLITE_BUSY && nTries<3 );
30306 return rc;
30309 /* Takes the conch by taking a shared lock and read the contents conch, if
30310 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
30311 ** lockPath means that the lockPath in the conch file will be used if the
30312 ** host IDs match, or a new lock path will be generated automatically
30313 ** and written to the conch file.
30315 static int proxyTakeConch(unixFile *pFile){
30316 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30318 if( pCtx->conchHeld!=0 ){
30319 return SQLITE_OK;
30320 }else{
30321 unixFile *conchFile = pCtx->conchFile;
30322 uuid_t myHostID;
30323 int pError = 0;
30324 char readBuf[PROXY_MAXCONCHLEN];
30325 char lockPath[MAXPATHLEN];
30326 char *tempLockPath = NULL;
30327 int rc = SQLITE_OK;
30328 int createConch = 0;
30329 int hostIdMatch = 0;
30330 int readLen = 0;
30331 int tryOldLockPath = 0;
30332 int forceNewLockPath = 0;
30334 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
30335 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30337 rc = proxyGetHostID(myHostID, &pError);
30338 if( (rc&0xff)==SQLITE_IOERR ){
30339 pFile->lastErrno = pError;
30340 goto end_takeconch;
30342 rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30343 if( rc!=SQLITE_OK ){
30344 goto end_takeconch;
30346 /* read the existing conch file */
30347 readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30348 if( readLen<0 ){
30349 /* I/O error: lastErrno set by seekAndRead */
30350 pFile->lastErrno = conchFile->lastErrno;
30351 rc = SQLITE_IOERR_READ;
30352 goto end_takeconch;
30353 }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30354 readBuf[0]!=(char)PROXY_CONCHVERSION ){
30355 /* a short read or version format mismatch means we need to create a new
30356 ** conch file.
30358 createConch = 1;
30360 /* if the host id matches and the lock path already exists in the conch
30361 ** we'll try to use the path there, if we can't open that path, we'll
30362 ** retry with a new auto-generated path
30364 do { /* in case we need to try again for an :auto: named lock file */
30366 if( !createConch && !forceNewLockPath ){
30367 hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30368 PROXY_HOSTIDLEN);
30369 /* if the conch has data compare the contents */
30370 if( !pCtx->lockProxyPath ){
30371 /* for auto-named local lock file, just check the host ID and we'll
30372 ** use the local lock file path that's already in there
30374 if( hostIdMatch ){
30375 size_t pathLen = (readLen - PROXY_PATHINDEX);
30377 if( pathLen>=MAXPATHLEN ){
30378 pathLen=MAXPATHLEN-1;
30380 memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30381 lockPath[pathLen] = 0;
30382 tempLockPath = lockPath;
30383 tryOldLockPath = 1;
30384 /* create a copy of the lock path if the conch is taken */
30385 goto end_takeconch;
30387 }else if( hostIdMatch
30388 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30389 readLen-PROXY_PATHINDEX)
30391 /* conch host and lock path match */
30392 goto end_takeconch;
30396 /* if the conch isn't writable and doesn't match, we can't take it */
30397 if( (conchFile->openFlags&O_RDWR) == 0 ){
30398 rc = SQLITE_BUSY;
30399 goto end_takeconch;
30402 /* either the conch didn't match or we need to create a new one */
30403 if( !pCtx->lockProxyPath ){
30404 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30405 tempLockPath = lockPath;
30406 /* create a copy of the lock path _only_ if the conch is taken */
30409 /* update conch with host and path (this will fail if other process
30410 ** has a shared lock already), if the host id matches, use the big
30411 ** stick.
30413 futimes(conchFile->h, NULL);
30414 if( hostIdMatch && !createConch ){
30415 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30416 /* We are trying for an exclusive lock but another thread in this
30417 ** same process is still holding a shared lock. */
30418 rc = SQLITE_BUSY;
30419 } else {
30420 rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30422 }else{
30423 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30425 if( rc==SQLITE_OK ){
30426 char writeBuffer[PROXY_MAXCONCHLEN];
30427 int writeSize = 0;
30429 writeBuffer[0] = (char)PROXY_CONCHVERSION;
30430 memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30431 if( pCtx->lockProxyPath!=NULL ){
30432 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30433 }else{
30434 strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30436 writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30437 robust_ftruncate(conchFile->h, writeSize);
30438 rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30439 fsync(conchFile->h);
30440 /* If we created a new conch file (not just updated the contents of a
30441 ** valid conch file), try to match the permissions of the database
30443 if( rc==SQLITE_OK && createConch ){
30444 struct stat buf;
30445 int err = osFstat(pFile->h, &buf);
30446 if( err==0 ){
30447 mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30448 S_IROTH|S_IWOTH);
30449 /* try to match the database file R/W permissions, ignore failure */
30450 #ifndef SQLITE_PROXY_DEBUG
30451 osFchmod(conchFile->h, cmode);
30452 #else
30454 rc = osFchmod(conchFile->h, cmode);
30455 }while( rc==(-1) && errno==EINTR );
30456 if( rc!=0 ){
30457 int code = errno;
30458 fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30459 cmode, code, strerror(code));
30460 } else {
30461 fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30463 }else{
30464 int code = errno;
30465 fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30466 err, code, strerror(code));
30467 #endif
30471 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30473 end_takeconch:
30474 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
30475 if( rc==SQLITE_OK && pFile->openFlags ){
30476 int fd;
30477 if( pFile->h>=0 ){
30478 robust_close(pFile, pFile->h, __LINE__);
30480 pFile->h = -1;
30481 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
30482 OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
30483 if( fd>=0 ){
30484 pFile->h = fd;
30485 }else{
30486 rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30487 during locking */
30490 if( rc==SQLITE_OK && !pCtx->lockProxy ){
30491 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30492 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30493 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30494 /* we couldn't create the proxy lock file with the old lock file path
30495 ** so try again via auto-naming
30497 forceNewLockPath = 1;
30498 tryOldLockPath = 0;
30499 continue; /* go back to the do {} while start point, try again */
30502 if( rc==SQLITE_OK ){
30503 /* Need to make a copy of path if we extracted the value
30504 ** from the conch file or the path was allocated on the stack
30506 if( tempLockPath ){
30507 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30508 if( !pCtx->lockProxyPath ){
30509 rc = SQLITE_NOMEM;
30513 if( rc==SQLITE_OK ){
30514 pCtx->conchHeld = 1;
30516 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30517 afpLockingContext *afpCtx;
30518 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30519 afpCtx->dbPath = pCtx->lockProxyPath;
30521 } else {
30522 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30524 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
30525 rc==SQLITE_OK?"ok":"failed"));
30526 return rc;
30527 } while (1); /* in case we need to retry the :auto: lock file -
30528 ** we should never get here except via the 'continue' call. */
30533 ** If pFile holds a lock on a conch file, then release that lock.
30535 static int proxyReleaseConch(unixFile *pFile){
30536 int rc = SQLITE_OK; /* Subroutine return code */
30537 proxyLockingContext *pCtx; /* The locking context for the proxy lock */
30538 unixFile *conchFile; /* Name of the conch file */
30540 pCtx = (proxyLockingContext *)pFile->lockingContext;
30541 conchFile = pCtx->conchFile;
30542 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
30543 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30544 getpid()));
30545 if( pCtx->conchHeld>0 ){
30546 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30548 pCtx->conchHeld = 0;
30549 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
30550 (rc==SQLITE_OK ? "ok" : "failed")));
30551 return rc;
30555 ** Given the name of a database file, compute the name of its conch file.
30556 ** Store the conch filename in memory obtained from sqlite3_malloc().
30557 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
30558 ** or SQLITE_NOMEM if unable to obtain memory.
30560 ** The caller is responsible for ensuring that the allocated memory
30561 ** space is eventually freed.
30563 ** *pConchPath is set to NULL if a memory allocation error occurs.
30565 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30566 int i; /* Loop counter */
30567 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30568 char *conchPath; /* buffer in which to construct conch name */
30570 /* Allocate space for the conch filename and initialize the name to
30571 ** the name of the original database file. */
30572 *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30573 if( conchPath==0 ){
30574 return SQLITE_NOMEM;
30576 memcpy(conchPath, dbPath, len+1);
30578 /* now insert a "." before the last / character */
30579 for( i=(len-1); i>=0; i-- ){
30580 if( conchPath[i]=='/' ){
30581 i++;
30582 break;
30585 conchPath[i]='.';
30586 while ( i<len ){
30587 conchPath[i+1]=dbPath[i];
30588 i++;
30591 /* append the "-conch" suffix to the file */
30592 memcpy(&conchPath[i+1], "-conch", 7);
30593 assert( (int)strlen(conchPath) == len+7 );
30595 return SQLITE_OK;
30599 /* Takes a fully configured proxy locking-style unix file and switches
30600 ** the local lock file path
30602 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30603 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30604 char *oldPath = pCtx->lockProxyPath;
30605 int rc = SQLITE_OK;
30607 if( pFile->eFileLock!=NO_LOCK ){
30608 return SQLITE_BUSY;
30611 /* nothing to do if the path is NULL, :auto: or matches the existing path */
30612 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30613 (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30614 return SQLITE_OK;
30615 }else{
30616 unixFile *lockProxy = pCtx->lockProxy;
30617 pCtx->lockProxy=NULL;
30618 pCtx->conchHeld = 0;
30619 if( lockProxy!=NULL ){
30620 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30621 if( rc ) return rc;
30622 sqlite3_free(lockProxy);
30624 sqlite3_free(oldPath);
30625 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30628 return rc;
30632 ** pFile is a file that has been opened by a prior xOpen call. dbPath
30633 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30635 ** This routine find the filename associated with pFile and writes it
30636 ** int dbPath.
30638 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30639 #if defined(__APPLE__)
30640 if( pFile->pMethod == &afpIoMethods ){
30641 /* afp style keeps a reference to the db path in the filePath field
30642 ** of the struct */
30643 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30644 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30645 } else
30646 #endif
30647 if( pFile->pMethod == &dotlockIoMethods ){
30648 /* dot lock style uses the locking context to store the dot lock
30649 ** file path */
30650 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30651 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30652 }else{
30653 /* all other styles use the locking context to store the db file path */
30654 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30655 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30657 return SQLITE_OK;
30661 ** Takes an already filled in unix file and alters it so all file locking
30662 ** will be performed on the local proxy lock file. The following fields
30663 ** are preserved in the locking context so that they can be restored and
30664 ** the unix structure properly cleaned up at close time:
30665 ** ->lockingContext
30666 ** ->pMethod
30668 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30669 proxyLockingContext *pCtx;
30670 char dbPath[MAXPATHLEN+1]; /* Name of the database file */
30671 char *lockPath=NULL;
30672 int rc = SQLITE_OK;
30674 if( pFile->eFileLock!=NO_LOCK ){
30675 return SQLITE_BUSY;
30677 proxyGetDbPathForUnixFile(pFile, dbPath);
30678 if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30679 lockPath=NULL;
30680 }else{
30681 lockPath=(char *)path;
30684 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
30685 (lockPath ? lockPath : ":auto:"), getpid()));
30687 pCtx = sqlite3_malloc( sizeof(*pCtx) );
30688 if( pCtx==0 ){
30689 return SQLITE_NOMEM;
30691 memset(pCtx, 0, sizeof(*pCtx));
30693 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30694 if( rc==SQLITE_OK ){
30695 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30696 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30697 /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30698 ** (c) the file system is read-only, then enable no-locking access.
30699 ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30700 ** that openFlags will have only one of O_RDONLY or O_RDWR.
30702 struct statfs fsInfo;
30703 struct stat conchInfo;
30704 int goLockless = 0;
30706 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30707 int err = errno;
30708 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30709 goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30712 if( goLockless ){
30713 pCtx->conchHeld = -1; /* read only FS/ lockless */
30714 rc = SQLITE_OK;
30718 if( rc==SQLITE_OK && lockPath ){
30719 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30722 if( rc==SQLITE_OK ){
30723 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30724 if( pCtx->dbPath==NULL ){
30725 rc = SQLITE_NOMEM;
30728 if( rc==SQLITE_OK ){
30729 /* all memory is allocated, proxys are created and assigned,
30730 ** switch the locking context and pMethod then return.
30732 pCtx->oldLockingContext = pFile->lockingContext;
30733 pFile->lockingContext = pCtx;
30734 pCtx->pOldMethod = pFile->pMethod;
30735 pFile->pMethod = &proxyIoMethods;
30736 }else{
30737 if( pCtx->conchFile ){
30738 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30739 sqlite3_free(pCtx->conchFile);
30741 sqlite3DbFree(0, pCtx->lockProxyPath);
30742 sqlite3_free(pCtx->conchFilePath);
30743 sqlite3_free(pCtx);
30745 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
30746 (rc==SQLITE_OK ? "ok" : "failed")));
30747 return rc;
30752 ** This routine handles sqlite3_file_control() calls that are specific
30753 ** to proxy locking.
30755 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30756 switch( op ){
30757 case SQLITE_GET_LOCKPROXYFILE: {
30758 unixFile *pFile = (unixFile*)id;
30759 if( pFile->pMethod == &proxyIoMethods ){
30760 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30761 proxyTakeConch(pFile);
30762 if( pCtx->lockProxyPath ){
30763 *(const char **)pArg = pCtx->lockProxyPath;
30764 }else{
30765 *(const char **)pArg = ":auto: (not held)";
30767 } else {
30768 *(const char **)pArg = NULL;
30770 return SQLITE_OK;
30772 case SQLITE_SET_LOCKPROXYFILE: {
30773 unixFile *pFile = (unixFile*)id;
30774 int rc = SQLITE_OK;
30775 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30776 if( pArg==NULL || (const char *)pArg==0 ){
30777 if( isProxyStyle ){
30778 /* turn off proxy locking - not supported */
30779 rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30780 }else{
30781 /* turn off proxy locking - already off - NOOP */
30782 rc = SQLITE_OK;
30784 }else{
30785 const char *proxyPath = (const char *)pArg;
30786 if( isProxyStyle ){
30787 proxyLockingContext *pCtx =
30788 (proxyLockingContext*)pFile->lockingContext;
30789 if( !strcmp(pArg, ":auto:")
30790 || (pCtx->lockProxyPath &&
30791 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30793 rc = SQLITE_OK;
30794 }else{
30795 rc = switchLockProxyPath(pFile, proxyPath);
30797 }else{
30798 /* turn on proxy file locking */
30799 rc = proxyTransformUnixFile(pFile, proxyPath);
30802 return rc;
30804 default: {
30805 assert( 0 ); /* The call assures that only valid opcodes are sent */
30808 /*NOTREACHED*/
30809 return SQLITE_ERROR;
30813 ** Within this division (the proxying locking implementation) the procedures
30814 ** above this point are all utilities. The lock-related methods of the
30815 ** proxy-locking sqlite3_io_method object follow.
30820 ** This routine checks if there is a RESERVED lock held on the specified
30821 ** file by this or any other process. If such a lock is held, set *pResOut
30822 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30823 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30825 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30826 unixFile *pFile = (unixFile*)id;
30827 int rc = proxyTakeConch(pFile);
30828 if( rc==SQLITE_OK ){
30829 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30830 if( pCtx->conchHeld>0 ){
30831 unixFile *proxy = pCtx->lockProxy;
30832 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30833 }else{ /* conchHeld < 0 is lockless */
30834 pResOut=0;
30837 return rc;
30841 ** Lock the file with the lock specified by parameter eFileLock - one
30842 ** of the following:
30844 ** (1) SHARED_LOCK
30845 ** (2) RESERVED_LOCK
30846 ** (3) PENDING_LOCK
30847 ** (4) EXCLUSIVE_LOCK
30849 ** Sometimes when requesting one lock state, additional lock states
30850 ** are inserted in between. The locking might fail on one of the later
30851 ** transitions leaving the lock state different from what it started but
30852 ** still short of its goal. The following chart shows the allowed
30853 ** transitions and the inserted intermediate states:
30855 ** UNLOCKED -> SHARED
30856 ** SHARED -> RESERVED
30857 ** SHARED -> (PENDING) -> EXCLUSIVE
30858 ** RESERVED -> (PENDING) -> EXCLUSIVE
30859 ** PENDING -> EXCLUSIVE
30861 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30862 ** routine to lower a locking level.
30864 static int proxyLock(sqlite3_file *id, int eFileLock) {
30865 unixFile *pFile = (unixFile*)id;
30866 int rc = proxyTakeConch(pFile);
30867 if( rc==SQLITE_OK ){
30868 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30869 if( pCtx->conchHeld>0 ){
30870 unixFile *proxy = pCtx->lockProxy;
30871 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30872 pFile->eFileLock = proxy->eFileLock;
30873 }else{
30874 /* conchHeld < 0 is lockless */
30877 return rc;
30882 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
30883 ** must be either NO_LOCK or SHARED_LOCK.
30885 ** If the locking level of the file descriptor is already at or below
30886 ** the requested locking level, this routine is a no-op.
30888 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30889 unixFile *pFile = (unixFile*)id;
30890 int rc = proxyTakeConch(pFile);
30891 if( rc==SQLITE_OK ){
30892 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30893 if( pCtx->conchHeld>0 ){
30894 unixFile *proxy = pCtx->lockProxy;
30895 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30896 pFile->eFileLock = proxy->eFileLock;
30897 }else{
30898 /* conchHeld < 0 is lockless */
30901 return rc;
30905 ** Close a file that uses proxy locks.
30907 static int proxyClose(sqlite3_file *id) {
30908 if( id ){
30909 unixFile *pFile = (unixFile*)id;
30910 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30911 unixFile *lockProxy = pCtx->lockProxy;
30912 unixFile *conchFile = pCtx->conchFile;
30913 int rc = SQLITE_OK;
30915 if( lockProxy ){
30916 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30917 if( rc ) return rc;
30918 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30919 if( rc ) return rc;
30920 sqlite3_free(lockProxy);
30921 pCtx->lockProxy = 0;
30923 if( conchFile ){
30924 if( pCtx->conchHeld ){
30925 rc = proxyReleaseConch(pFile);
30926 if( rc ) return rc;
30928 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30929 if( rc ) return rc;
30930 sqlite3_free(conchFile);
30932 sqlite3DbFree(0, pCtx->lockProxyPath);
30933 sqlite3_free(pCtx->conchFilePath);
30934 sqlite3DbFree(0, pCtx->dbPath);
30935 /* restore the original locking context and pMethod then close it */
30936 pFile->lockingContext = pCtx->oldLockingContext;
30937 pFile->pMethod = pCtx->pOldMethod;
30938 sqlite3_free(pCtx);
30939 return pFile->pMethod->xClose(id);
30941 return SQLITE_OK;
30946 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30948 ** The proxy locking style is intended for use with AFP filesystems.
30949 ** And since AFP is only supported on MacOSX, the proxy locking is also
30950 ** restricted to MacOSX.
30953 ******************* End of the proxy lock implementation **********************
30954 ******************************************************************************/
30957 ** Initialize the operating system interface.
30959 ** This routine registers all VFS implementations for unix-like operating
30960 ** systems. This routine, and the sqlite3_os_end() routine that follows,
30961 ** should be the only routines in this file that are visible from other
30962 ** files.
30964 ** This routine is called once during SQLite initialization and by a
30965 ** single thread. The memory allocation and mutex subsystems have not
30966 ** necessarily been initialized when this routine is called, and so they
30967 ** should not be used.
30969 SQLITE_API int sqlite3_os_init(void){
30971 ** The following macro defines an initializer for an sqlite3_vfs object.
30972 ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
30973 ** to the "finder" function. (pAppData is a pointer to a pointer because
30974 ** silly C90 rules prohibit a void* from being cast to a function pointer
30975 ** and so we have to go through the intermediate pointer to avoid problems
30976 ** when compiling with -pedantic-errors on GCC.)
30978 ** The FINDER parameter to this macro is the name of the pointer to the
30979 ** finder-function. The finder-function returns a pointer to the
30980 ** sqlite_io_methods object that implements the desired locking
30981 ** behaviors. See the division above that contains the IOMETHODS
30982 ** macro for addition information on finder-functions.
30984 ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30985 ** object. But the "autolockIoFinder" available on MacOSX does a little
30986 ** more than that; it looks at the filesystem type that hosts the
30987 ** database file and tries to choose an locking method appropriate for
30988 ** that filesystem time.
30990 #define UNIXVFS(VFSNAME, FINDER) { \
30991 3, /* iVersion */ \
30992 sizeof(unixFile), /* szOsFile */ \
30993 MAX_PATHNAME, /* mxPathname */ \
30994 0, /* pNext */ \
30995 VFSNAME, /* zName */ \
30996 (void*)&FINDER, /* pAppData */ \
30997 unixOpen, /* xOpen */ \
30998 unixDelete, /* xDelete */ \
30999 unixAccess, /* xAccess */ \
31000 unixFullPathname, /* xFullPathname */ \
31001 unixDlOpen, /* xDlOpen */ \
31002 unixDlError, /* xDlError */ \
31003 unixDlSym, /* xDlSym */ \
31004 unixDlClose, /* xDlClose */ \
31005 unixRandomness, /* xRandomness */ \
31006 unixSleep, /* xSleep */ \
31007 unixCurrentTime, /* xCurrentTime */ \
31008 unixGetLastError, /* xGetLastError */ \
31009 unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
31010 unixSetSystemCall, /* xSetSystemCall */ \
31011 unixGetSystemCall, /* xGetSystemCall */ \
31012 unixNextSystemCall, /* xNextSystemCall */ \
31016 ** All default VFSes for unix are contained in the following array.
31018 ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31019 ** by the SQLite core when the VFS is registered. So the following
31020 ** array cannot be const.
31022 static sqlite3_vfs aVfs[] = {
31023 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31024 UNIXVFS("unix", autolockIoFinder ),
31025 #else
31026 UNIXVFS("unix", posixIoFinder ),
31027 #endif
31028 UNIXVFS("unix-none", nolockIoFinder ),
31029 UNIXVFS("unix-dotfile", dotlockIoFinder ),
31030 UNIXVFS("unix-excl", posixIoFinder ),
31031 #if OS_VXWORKS
31032 UNIXVFS("unix-namedsem", semIoFinder ),
31033 #endif
31034 #if SQLITE_ENABLE_LOCKING_STYLE
31035 UNIXVFS("unix-posix", posixIoFinder ),
31036 #if !OS_VXWORKS
31037 UNIXVFS("unix-flock", flockIoFinder ),
31038 #endif
31039 #endif
31040 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31041 UNIXVFS("unix-afp", afpIoFinder ),
31042 UNIXVFS("unix-nfs", nfsIoFinder ),
31043 UNIXVFS("unix-proxy", proxyIoFinder ),
31044 #endif
31046 unsigned int i; /* Loop counter */
31048 /* Double-check that the aSyscall[] array has been constructed
31049 ** correctly. See ticket [bb3a86e890c8e96ab] */
31050 assert( ArraySize(aSyscall)==24 );
31052 /* Register all VFSes defined in the aVfs[] array */
31053 for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31054 sqlite3_vfs_register(&aVfs[i], i==0);
31056 return SQLITE_OK;
31060 ** Shutdown the operating system interface.
31062 ** Some operating systems might need to do some cleanup in this routine,
31063 ** to release dynamically allocated objects. But not on unix.
31064 ** This routine is a no-op for unix.
31066 SQLITE_API int sqlite3_os_end(void){
31067 return SQLITE_OK;
31070 #endif /* SQLITE_OS_UNIX */
31072 /************** End of os_unix.c *********************************************/
31073 /************** Begin file os_win.c ******************************************/
31075 ** 2004 May 22
31077 ** The author disclaims copyright to this source code. In place of
31078 ** a legal notice, here is a blessing:
31080 ** May you do good and not evil.
31081 ** May you find forgiveness for yourself and forgive others.
31082 ** May you share freely, never taking more than you give.
31084 ******************************************************************************
31086 ** This file contains code that is specific to Windows.
31088 #if SQLITE_OS_WIN /* This file is used for Windows only */
31090 #ifdef __CYGWIN__
31091 # include <sys/cygwin.h>
31092 # include <errno.h> /* amalgamator: keep */
31093 #endif
31096 ** Include code that is common to all os_*.c files
31098 /************** Include os_common.h in the middle of os_win.c ****************/
31099 /************** Begin file os_common.h ***************************************/
31101 ** 2004 May 22
31103 ** The author disclaims copyright to this source code. In place of
31104 ** a legal notice, here is a blessing:
31106 ** May you do good and not evil.
31107 ** May you find forgiveness for yourself and forgive others.
31108 ** May you share freely, never taking more than you give.
31110 ******************************************************************************
31112 ** This file contains macros and a little bit of code that is common to
31113 ** all of the platform-specific files (os_*.c) and is #included into those
31114 ** files.
31116 ** This file should be #included by the os_*.c files only. It is not a
31117 ** general purpose header file.
31119 #ifndef _OS_COMMON_H_
31120 #define _OS_COMMON_H_
31123 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31124 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31125 ** switch. The following code should catch this problem at compile-time.
31127 #ifdef MEMORY_DEBUG
31128 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
31129 #endif
31131 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31132 # ifndef SQLITE_DEBUG_OS_TRACE
31133 # define SQLITE_DEBUG_OS_TRACE 0
31134 # endif
31135 int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
31136 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
31137 #else
31138 # define OSTRACE(X)
31139 #endif
31142 ** Macros for performance tracing. Normally turned off. Only works
31143 ** on i486 hardware.
31145 #ifdef SQLITE_PERFORMANCE_TRACE
31148 ** hwtime.h contains inline assembler code for implementing
31149 ** high-performance timing routines.
31151 /************** Include hwtime.h in the middle of os_common.h ****************/
31152 /************** Begin file hwtime.h ******************************************/
31154 ** 2008 May 27
31156 ** The author disclaims copyright to this source code. In place of
31157 ** a legal notice, here is a blessing:
31159 ** May you do good and not evil.
31160 ** May you find forgiveness for yourself and forgive others.
31161 ** May you share freely, never taking more than you give.
31163 ******************************************************************************
31165 ** This file contains inline asm code for retrieving "high-performance"
31166 ** counters for x86 class CPUs.
31168 #ifndef _HWTIME_H_
31169 #define _HWTIME_H_
31172 ** The following routine only works on pentium-class (or newer) processors.
31173 ** It uses the RDTSC opcode to read the cycle count value out of the
31174 ** processor and returns that value. This can be used for high-res
31175 ** profiling.
31177 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
31178 (defined(i386) || defined(__i386__) || defined(_M_IX86))
31180 #if defined(__GNUC__)
31182 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31183 unsigned int lo, hi;
31184 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31185 return (sqlite_uint64)hi << 32 | lo;
31188 #elif defined(_MSC_VER)
31190 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31191 __asm {
31192 rdtsc
31193 ret ; return value at EDX:EAX
31197 #endif
31199 #elif (defined(__GNUC__) && defined(__x86_64__))
31201 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31202 unsigned long val;
31203 __asm__ __volatile__ ("rdtsc" : "=A" (val));
31204 return val;
31207 #elif (defined(__GNUC__) && defined(__ppc__))
31209 __inline__ sqlite_uint64 sqlite3Hwtime(void){
31210 unsigned long long retval;
31211 unsigned long junk;
31212 __asm__ __volatile__ ("\n\
31213 1: mftbu %1\n\
31214 mftb %L0\n\
31215 mftbu %0\n\
31216 cmpw %0,%1\n\
31217 bne 1b"
31218 : "=r" (retval), "=r" (junk));
31219 return retval;
31222 #else
31224 #error Need implementation of sqlite3Hwtime() for your platform.
31227 ** To compile without implementing sqlite3Hwtime() for your platform,
31228 ** you can remove the above #error and use the following
31229 ** stub function. You will lose timing support for many
31230 ** of the debugging and testing utilities, but it should at
31231 ** least compile and run.
31233 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31235 #endif
31237 #endif /* !defined(_HWTIME_H_) */
31239 /************** End of hwtime.h **********************************************/
31240 /************** Continuing where we left off in os_common.h ******************/
31242 static sqlite_uint64 g_start;
31243 static sqlite_uint64 g_elapsed;
31244 #define TIMER_START g_start=sqlite3Hwtime()
31245 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
31246 #define TIMER_ELAPSED g_elapsed
31247 #else
31248 #define TIMER_START
31249 #define TIMER_END
31250 #define TIMER_ELAPSED ((sqlite_uint64)0)
31251 #endif
31254 ** If we compile with the SQLITE_TEST macro set, then the following block
31255 ** of code will give us the ability to simulate a disk I/O error. This
31256 ** is used for testing the I/O recovery logic.
31258 #ifdef SQLITE_TEST
31259 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
31260 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
31261 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
31262 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
31263 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
31264 SQLITE_API int sqlite3_diskfull_pending = 0;
31265 SQLITE_API int sqlite3_diskfull = 0;
31266 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31267 #define SimulateIOError(CODE) \
31268 if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31269 || sqlite3_io_error_pending-- == 1 ) \
31270 { local_ioerr(); CODE; }
31271 static void local_ioerr(){
31272 IOTRACE(("IOERR\n"));
31273 sqlite3_io_error_hit++;
31274 if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31276 #define SimulateDiskfullError(CODE) \
31277 if( sqlite3_diskfull_pending ){ \
31278 if( sqlite3_diskfull_pending == 1 ){ \
31279 local_ioerr(); \
31280 sqlite3_diskfull = 1; \
31281 sqlite3_io_error_hit = 1; \
31282 CODE; \
31283 }else{ \
31284 sqlite3_diskfull_pending--; \
31287 #else
31288 #define SimulateIOErrorBenign(X)
31289 #define SimulateIOError(A)
31290 #define SimulateDiskfullError(A)
31291 #endif
31294 ** When testing, keep a count of the number of open files.
31296 #ifdef SQLITE_TEST
31297 SQLITE_API int sqlite3_open_file_count = 0;
31298 #define OpenCounter(X) sqlite3_open_file_count+=(X)
31299 #else
31300 #define OpenCounter(X)
31301 #endif
31303 #endif /* !defined(_OS_COMMON_H_) */
31305 /************** End of os_common.h *******************************************/
31306 /************** Continuing where we left off in os_win.c *********************/
31309 ** Compiling and using WAL mode requires several APIs that are only
31310 ** available in Windows platforms based on the NT kernel.
31312 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
31313 # error "WAL mode requires support from the Windows NT kernel, compile\
31314 with SQLITE_OMIT_WAL."
31315 #endif
31318 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
31319 ** based on the sub-platform)?
31321 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
31322 # define SQLITE_WIN32_HAS_ANSI
31323 #endif
31326 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
31327 ** based on the sub-platform)?
31329 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
31330 !defined(SQLITE_WIN32_NO_WIDE)
31331 # define SQLITE_WIN32_HAS_WIDE
31332 #endif
31335 ** Make sure at least one set of Win32 APIs is available.
31337 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
31338 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
31339 must be defined."
31340 #endif
31343 ** Define the required Windows SDK version constants if they are not
31344 ** already available.
31346 #ifndef NTDDI_WIN8
31347 # define NTDDI_WIN8 0x06020000
31348 #endif
31350 #ifndef NTDDI_WINBLUE
31351 # define NTDDI_WINBLUE 0x06030000
31352 #endif
31355 ** Check if the GetVersionEx[AW] functions should be considered deprecated
31356 ** and avoid using them in that case. It should be noted here that if the
31357 ** value of the SQLITE_WIN32_GETVERSIONEX pre-processor macro is zero
31358 ** (whether via this block or via being manually specified), that implies
31359 ** the underlying operating system will always be based on the Windows NT
31360 ** Kernel.
31362 #ifndef SQLITE_WIN32_GETVERSIONEX
31363 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
31364 # define SQLITE_WIN32_GETVERSIONEX 0
31365 # else
31366 # define SQLITE_WIN32_GETVERSIONEX 1
31367 # endif
31368 #endif
31371 ** This constant should already be defined (in the "WinDef.h" SDK file).
31373 #ifndef MAX_PATH
31374 # define MAX_PATH (260)
31375 #endif
31378 ** Maximum pathname length (in chars) for Win32. This should normally be
31379 ** MAX_PATH.
31381 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
31382 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
31383 #endif
31386 ** This constant should already be defined (in the "WinNT.h" SDK file).
31388 #ifndef UNICODE_STRING_MAX_CHARS
31389 # define UNICODE_STRING_MAX_CHARS (32767)
31390 #endif
31393 ** Maximum pathname length (in chars) for WinNT. This should normally be
31394 ** UNICODE_STRING_MAX_CHARS.
31396 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
31397 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
31398 #endif
31401 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
31402 ** characters, so we allocate 4 bytes per character assuming worst-case of
31403 ** 4-bytes-per-character for UTF8.
31405 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
31406 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
31407 #endif
31410 ** Maximum pathname length (in bytes) for WinNT. This should normally be
31411 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
31413 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
31414 # define SQLITE_WINNT_MAX_PATH_BYTES \
31415 (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
31416 #endif
31419 ** Maximum error message length (in chars) for WinRT.
31421 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
31422 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
31423 #endif
31426 ** Returns non-zero if the character should be treated as a directory
31427 ** separator.
31429 #ifndef winIsDirSep
31430 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
31431 #endif
31434 ** This macro is used when a local variable is set to a value that is
31435 ** [sometimes] not used by the code (e.g. via conditional compilation).
31437 #ifndef UNUSED_VARIABLE_VALUE
31438 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
31439 #endif
31442 ** Returns the character that should be used as the directory separator.
31444 #ifndef winGetDirSep
31445 # define winGetDirSep() '\\'
31446 #endif
31449 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
31450 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
31451 ** are not present in the header file)?
31453 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
31455 ** Two of the file mapping APIs are different under WinRT. Figure out which
31456 ** set we need.
31458 #if SQLITE_OS_WINRT
31459 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
31460 LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
31462 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
31463 #else
31464 #if defined(SQLITE_WIN32_HAS_ANSI)
31465 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
31466 DWORD, DWORD, DWORD, LPCSTR);
31467 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
31469 #if defined(SQLITE_WIN32_HAS_WIDE)
31470 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
31471 DWORD, DWORD, DWORD, LPCWSTR);
31472 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
31474 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
31475 #endif /* SQLITE_OS_WINRT */
31478 ** This file mapping API is common to both Win32 and WinRT.
31480 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
31481 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
31484 ** Some Microsoft compilers lack this definition.
31486 #ifndef INVALID_FILE_ATTRIBUTES
31487 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31488 #endif
31490 #ifndef FILE_FLAG_MASK
31491 # define FILE_FLAG_MASK (0xFF3C0000)
31492 #endif
31494 #ifndef FILE_ATTRIBUTE_MASK
31495 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
31496 #endif
31498 #ifndef SQLITE_OMIT_WAL
31499 /* Forward references to structures used for WAL */
31500 typedef struct winShm winShm; /* A connection to shared-memory */
31501 typedef struct winShmNode winShmNode; /* A region of shared-memory */
31502 #endif
31505 ** WinCE lacks native support for file locking so we have to fake it
31506 ** with some code of our own.
31508 #if SQLITE_OS_WINCE
31509 typedef struct winceLock {
31510 int nReaders; /* Number of reader locks obtained */
31511 BOOL bPending; /* Indicates a pending lock has been obtained */
31512 BOOL bReserved; /* Indicates a reserved lock has been obtained */
31513 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
31514 } winceLock;
31515 #endif
31518 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31519 ** portability layer.
31521 typedef struct winFile winFile;
31522 struct winFile {
31523 const sqlite3_io_methods *pMethod; /*** Must be first ***/
31524 sqlite3_vfs *pVfs; /* The VFS used to open this file */
31525 HANDLE h; /* Handle for accessing the file */
31526 u8 locktype; /* Type of lock currently held on this file */
31527 short sharedLockByte; /* Randomly chosen byte used as a shared lock */
31528 u8 ctrlFlags; /* Flags. See WINFILE_* below */
31529 DWORD lastErrno; /* The Windows errno from the last I/O error */
31530 #ifndef SQLITE_OMIT_WAL
31531 winShm *pShm; /* Instance of shared memory on this file */
31532 #endif
31533 const char *zPath; /* Full pathname of this file */
31534 int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
31535 #if SQLITE_OS_WINCE
31536 LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
31537 HANDLE hMutex; /* Mutex used to control access to shared lock */
31538 HANDLE hShared; /* Shared memory segment used for locking */
31539 winceLock local; /* Locks obtained by this instance of winFile */
31540 winceLock *shared; /* Global shared lock memory for the file */
31541 #endif
31542 #if SQLITE_MAX_MMAP_SIZE>0
31543 int nFetchOut; /* Number of outstanding xFetch references */
31544 HANDLE hMap; /* Handle for accessing memory mapping */
31545 void *pMapRegion; /* Area memory mapped */
31546 sqlite3_int64 mmapSize; /* Usable size of mapped region */
31547 sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
31548 sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
31549 #endif
31553 ** Allowed values for winFile.ctrlFlags
31555 #define WINFILE_RDONLY 0x02 /* Connection is read only */
31556 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
31557 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
31560 * The size of the buffer used by sqlite3_win32_write_debug().
31562 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
31563 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
31564 #endif
31567 * The value used with sqlite3_win32_set_directory() to specify that
31568 * the data directory should be changed.
31570 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
31571 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
31572 #endif
31575 * The value used with sqlite3_win32_set_directory() to specify that
31576 * the temporary directory should be changed.
31578 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
31579 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
31580 #endif
31583 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
31584 * various Win32 API heap functions instead of our own.
31586 #ifdef SQLITE_WIN32_MALLOC
31589 * If this is non-zero, an isolated heap will be created by the native Win32
31590 * allocator subsystem; otherwise, the default process heap will be used. This
31591 * setting has no effect when compiling for WinRT. By default, this is enabled
31592 * and an isolated heap will be created to store all allocated data.
31594 ******************************************************************************
31595 * WARNING: It is important to note that when this setting is non-zero and the
31596 * winMemShutdown function is called (e.g. by the sqlite3_shutdown
31597 * function), all data that was allocated using the isolated heap will
31598 * be freed immediately and any attempt to access any of that freed
31599 * data will almost certainly result in an immediate access violation.
31600 ******************************************************************************
31602 #ifndef SQLITE_WIN32_HEAP_CREATE
31603 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
31604 #endif
31607 * The initial size of the Win32-specific heap. This value may be zero.
31609 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
31610 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
31611 (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
31612 #endif
31615 * The maximum size of the Win32-specific heap. This value may be zero.
31617 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
31618 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
31619 #endif
31622 * The extra flags to use in calls to the Win32 heap APIs. This value may be
31623 * zero for the default behavior.
31625 #ifndef SQLITE_WIN32_HEAP_FLAGS
31626 # define SQLITE_WIN32_HEAP_FLAGS (0)
31627 #endif
31631 ** The winMemData structure stores information required by the Win32-specific
31632 ** sqlite3_mem_methods implementation.
31634 typedef struct winMemData winMemData;
31635 struct winMemData {
31636 #ifndef NDEBUG
31637 u32 magic1; /* Magic number to detect structure corruption. */
31638 #endif
31639 HANDLE hHeap; /* The handle to our heap. */
31640 BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
31641 #ifndef NDEBUG
31642 u32 magic2; /* Magic number to detect structure corruption. */
31643 #endif
31646 #ifndef NDEBUG
31647 #define WINMEM_MAGIC1 0x42b2830b
31648 #define WINMEM_MAGIC2 0xbd4d7cf4
31649 #endif
31651 static struct winMemData win_mem_data = {
31652 #ifndef NDEBUG
31653 WINMEM_MAGIC1,
31654 #endif
31655 NULL, FALSE
31656 #ifndef NDEBUG
31657 ,WINMEM_MAGIC2
31658 #endif
31661 #ifndef NDEBUG
31662 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
31663 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
31664 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
31665 #else
31666 #define winMemAssertMagic()
31667 #endif
31669 #define winMemGetDataPtr() &win_mem_data
31670 #define winMemGetHeap() win_mem_data.hHeap
31671 #define winMemGetOwned() win_mem_data.bOwned
31673 static void *winMemMalloc(int nBytes);
31674 static void winMemFree(void *pPrior);
31675 static void *winMemRealloc(void *pPrior, int nBytes);
31676 static int winMemSize(void *p);
31677 static int winMemRoundup(int n);
31678 static int winMemInit(void *pAppData);
31679 static void winMemShutdown(void *pAppData);
31681 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
31682 #endif /* SQLITE_WIN32_MALLOC */
31685 ** The following variable is (normally) set once and never changes
31686 ** thereafter. It records whether the operating system is Win9x
31687 ** or WinNT.
31689 ** 0: Operating system unknown.
31690 ** 1: Operating system is Win9x.
31691 ** 2: Operating system is WinNT.
31693 ** In order to facilitate testing on a WinNT system, the test fixture
31694 ** can manually set this value to 1 to emulate Win98 behavior.
31696 #ifdef SQLITE_TEST
31697 SQLITE_API int sqlite3_os_type = 0;
31698 #elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
31699 defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
31700 static int sqlite3_os_type = 0;
31701 #endif
31703 #ifndef SYSCALL
31704 # define SYSCALL sqlite3_syscall_ptr
31705 #endif
31708 ** This function is not available on Windows CE or WinRT.
31711 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31712 # define osAreFileApisANSI() 1
31713 #endif
31716 ** Many system calls are accessed through pointer-to-functions so that
31717 ** they may be overridden at runtime to facilitate fault injection during
31718 ** testing and sandboxing. The following array holds the names and pointers
31719 ** to all overrideable system calls.
31721 static struct win_syscall {
31722 const char *zName; /* Name of the system call */
31723 sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
31724 sqlite3_syscall_ptr pDefault; /* Default value */
31725 } aSyscall[] = {
31726 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31727 { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
31728 #else
31729 { "AreFileApisANSI", (SYSCALL)0, 0 },
31730 #endif
31732 #ifndef osAreFileApisANSI
31733 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
31734 #endif
31736 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31737 { "CharLowerW", (SYSCALL)CharLowerW, 0 },
31738 #else
31739 { "CharLowerW", (SYSCALL)0, 0 },
31740 #endif
31742 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
31744 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31745 { "CharUpperW", (SYSCALL)CharUpperW, 0 },
31746 #else
31747 { "CharUpperW", (SYSCALL)0, 0 },
31748 #endif
31750 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
31752 { "CloseHandle", (SYSCALL)CloseHandle, 0 },
31754 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
31756 #if defined(SQLITE_WIN32_HAS_ANSI)
31757 { "CreateFileA", (SYSCALL)CreateFileA, 0 },
31758 #else
31759 { "CreateFileA", (SYSCALL)0, 0 },
31760 #endif
31762 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
31763 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
31765 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31766 { "CreateFileW", (SYSCALL)CreateFileW, 0 },
31767 #else
31768 { "CreateFileW", (SYSCALL)0, 0 },
31769 #endif
31771 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
31772 LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
31774 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
31775 !defined(SQLITE_OMIT_WAL))
31776 { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
31777 #else
31778 { "CreateFileMappingA", (SYSCALL)0, 0 },
31779 #endif
31781 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31782 DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
31784 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31785 !defined(SQLITE_OMIT_WAL))
31786 { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
31787 #else
31788 { "CreateFileMappingW", (SYSCALL)0, 0 },
31789 #endif
31791 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31792 DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
31794 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31795 { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
31796 #else
31797 { "CreateMutexW", (SYSCALL)0, 0 },
31798 #endif
31800 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
31801 LPCWSTR))aSyscall[8].pCurrent)
31803 #if defined(SQLITE_WIN32_HAS_ANSI)
31804 { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
31805 #else
31806 { "DeleteFileA", (SYSCALL)0, 0 },
31807 #endif
31809 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
31811 #if defined(SQLITE_WIN32_HAS_WIDE)
31812 { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
31813 #else
31814 { "DeleteFileW", (SYSCALL)0, 0 },
31815 #endif
31817 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
31819 #if SQLITE_OS_WINCE
31820 { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
31821 #else
31822 { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
31823 #endif
31825 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31826 LPFILETIME))aSyscall[11].pCurrent)
31828 #if SQLITE_OS_WINCE
31829 { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
31830 #else
31831 { "FileTimeToSystemTime", (SYSCALL)0, 0 },
31832 #endif
31834 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31835 LPSYSTEMTIME))aSyscall[12].pCurrent)
31837 { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
31839 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
31841 #if defined(SQLITE_WIN32_HAS_ANSI)
31842 { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
31843 #else
31844 { "FormatMessageA", (SYSCALL)0, 0 },
31845 #endif
31847 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
31848 DWORD,va_list*))aSyscall[14].pCurrent)
31850 #if defined(SQLITE_WIN32_HAS_WIDE)
31851 { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
31852 #else
31853 { "FormatMessageW", (SYSCALL)0, 0 },
31854 #endif
31856 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
31857 DWORD,va_list*))aSyscall[15].pCurrent)
31859 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31860 { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
31861 #else
31862 { "FreeLibrary", (SYSCALL)0, 0 },
31863 #endif
31865 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
31867 { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
31869 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
31871 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31872 { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
31873 #else
31874 { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
31875 #endif
31877 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
31878 LPDWORD))aSyscall[18].pCurrent)
31880 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31881 { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
31882 #else
31883 { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
31884 #endif
31886 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
31887 LPDWORD))aSyscall[19].pCurrent)
31889 #if defined(SQLITE_WIN32_HAS_ANSI)
31890 { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
31891 #else
31892 { "GetFileAttributesA", (SYSCALL)0, 0 },
31893 #endif
31895 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
31897 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31898 { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
31899 #else
31900 { "GetFileAttributesW", (SYSCALL)0, 0 },
31901 #endif
31903 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
31905 #if defined(SQLITE_WIN32_HAS_WIDE)
31906 { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
31907 #else
31908 { "GetFileAttributesExW", (SYSCALL)0, 0 },
31909 #endif
31911 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
31912 LPVOID))aSyscall[22].pCurrent)
31914 #if !SQLITE_OS_WINRT
31915 { "GetFileSize", (SYSCALL)GetFileSize, 0 },
31916 #else
31917 { "GetFileSize", (SYSCALL)0, 0 },
31918 #endif
31920 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
31922 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31923 { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
31924 #else
31925 { "GetFullPathNameA", (SYSCALL)0, 0 },
31926 #endif
31928 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
31929 LPSTR*))aSyscall[24].pCurrent)
31931 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31932 { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
31933 #else
31934 { "GetFullPathNameW", (SYSCALL)0, 0 },
31935 #endif
31937 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
31938 LPWSTR*))aSyscall[25].pCurrent)
31940 { "GetLastError", (SYSCALL)GetLastError, 0 },
31942 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
31944 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31945 #if SQLITE_OS_WINCE
31946 /* The GetProcAddressA() routine is only available on Windows CE. */
31947 { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
31948 #else
31949 /* All other Windows platforms expect GetProcAddress() to take
31950 ** an ANSI string regardless of the _UNICODE setting */
31951 { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
31952 #endif
31953 #else
31954 { "GetProcAddressA", (SYSCALL)0, 0 },
31955 #endif
31957 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
31958 LPCSTR))aSyscall[27].pCurrent)
31960 #if !SQLITE_OS_WINRT
31961 { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
31962 #else
31963 { "GetSystemInfo", (SYSCALL)0, 0 },
31964 #endif
31966 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
31968 { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
31970 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
31972 #if !SQLITE_OS_WINCE
31973 { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
31974 #else
31975 { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
31976 #endif
31978 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
31979 LPFILETIME))aSyscall[30].pCurrent)
31981 #if defined(SQLITE_WIN32_HAS_ANSI)
31982 { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
31983 #else
31984 { "GetTempPathA", (SYSCALL)0, 0 },
31985 #endif
31987 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
31989 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31990 { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
31991 #else
31992 { "GetTempPathW", (SYSCALL)0, 0 },
31993 #endif
31995 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
31997 #if !SQLITE_OS_WINRT
31998 { "GetTickCount", (SYSCALL)GetTickCount, 0 },
31999 #else
32000 { "GetTickCount", (SYSCALL)0, 0 },
32001 #endif
32003 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
32005 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
32006 SQLITE_WIN32_GETVERSIONEX
32007 { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
32008 #else
32009 { "GetVersionExA", (SYSCALL)0, 0 },
32010 #endif
32012 #define osGetVersionExA ((BOOL(WINAPI*)( \
32013 LPOSVERSIONINFOA))aSyscall[34].pCurrent)
32015 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
32016 defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
32017 { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
32018 #else
32019 { "GetVersionExW", (SYSCALL)0, 0 },
32020 #endif
32022 #define osGetVersionExW ((BOOL(WINAPI*)( \
32023 LPOSVERSIONINFOW))aSyscall[35].pCurrent)
32025 { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
32027 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
32028 SIZE_T))aSyscall[36].pCurrent)
32030 #if !SQLITE_OS_WINRT
32031 { "HeapCreate", (SYSCALL)HeapCreate, 0 },
32032 #else
32033 { "HeapCreate", (SYSCALL)0, 0 },
32034 #endif
32036 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
32037 SIZE_T))aSyscall[37].pCurrent)
32039 #if !SQLITE_OS_WINRT
32040 { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
32041 #else
32042 { "HeapDestroy", (SYSCALL)0, 0 },
32043 #endif
32045 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
32047 { "HeapFree", (SYSCALL)HeapFree, 0 },
32049 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
32051 { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
32053 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
32054 SIZE_T))aSyscall[40].pCurrent)
32056 { "HeapSize", (SYSCALL)HeapSize, 0 },
32058 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
32059 LPCVOID))aSyscall[41].pCurrent)
32061 #if !SQLITE_OS_WINRT
32062 { "HeapValidate", (SYSCALL)HeapValidate, 0 },
32063 #else
32064 { "HeapValidate", (SYSCALL)0, 0 },
32065 #endif
32067 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
32068 LPCVOID))aSyscall[42].pCurrent)
32070 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32071 { "HeapCompact", (SYSCALL)HeapCompact, 0 },
32072 #else
32073 { "HeapCompact", (SYSCALL)0, 0 },
32074 #endif
32076 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
32078 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
32079 { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
32080 #else
32081 { "LoadLibraryA", (SYSCALL)0, 0 },
32082 #endif
32084 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
32086 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
32087 !defined(SQLITE_OMIT_LOAD_EXTENSION)
32088 { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
32089 #else
32090 { "LoadLibraryW", (SYSCALL)0, 0 },
32091 #endif
32093 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
32095 #if !SQLITE_OS_WINRT
32096 { "LocalFree", (SYSCALL)LocalFree, 0 },
32097 #else
32098 { "LocalFree", (SYSCALL)0, 0 },
32099 #endif
32101 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
32103 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32104 { "LockFile", (SYSCALL)LockFile, 0 },
32105 #else
32106 { "LockFile", (SYSCALL)0, 0 },
32107 #endif
32109 #ifndef osLockFile
32110 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32111 DWORD))aSyscall[47].pCurrent)
32112 #endif
32114 #if !SQLITE_OS_WINCE
32115 { "LockFileEx", (SYSCALL)LockFileEx, 0 },
32116 #else
32117 { "LockFileEx", (SYSCALL)0, 0 },
32118 #endif
32120 #ifndef osLockFileEx
32121 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
32122 LPOVERLAPPED))aSyscall[48].pCurrent)
32123 #endif
32125 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
32126 { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
32127 #else
32128 { "MapViewOfFile", (SYSCALL)0, 0 },
32129 #endif
32131 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32132 SIZE_T))aSyscall[49].pCurrent)
32134 { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
32136 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
32137 int))aSyscall[50].pCurrent)
32139 { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
32141 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
32142 LARGE_INTEGER*))aSyscall[51].pCurrent)
32144 { "ReadFile", (SYSCALL)ReadFile, 0 },
32146 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
32147 LPOVERLAPPED))aSyscall[52].pCurrent)
32149 { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
32151 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
32153 #if !SQLITE_OS_WINRT
32154 { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
32155 #else
32156 { "SetFilePointer", (SYSCALL)0, 0 },
32157 #endif
32159 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
32160 DWORD))aSyscall[54].pCurrent)
32162 #if !SQLITE_OS_WINRT
32163 { "Sleep", (SYSCALL)Sleep, 0 },
32164 #else
32165 { "Sleep", (SYSCALL)0, 0 },
32166 #endif
32168 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
32170 { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
32172 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
32173 LPFILETIME))aSyscall[56].pCurrent)
32175 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32176 { "UnlockFile", (SYSCALL)UnlockFile, 0 },
32177 #else
32178 { "UnlockFile", (SYSCALL)0, 0 },
32179 #endif
32181 #ifndef osUnlockFile
32182 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32183 DWORD))aSyscall[57].pCurrent)
32184 #endif
32186 #if !SQLITE_OS_WINCE
32187 { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
32188 #else
32189 { "UnlockFileEx", (SYSCALL)0, 0 },
32190 #endif
32192 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32193 LPOVERLAPPED))aSyscall[58].pCurrent)
32195 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
32196 { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
32197 #else
32198 { "UnmapViewOfFile", (SYSCALL)0, 0 },
32199 #endif
32201 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
32203 { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
32205 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
32206 LPCSTR,LPBOOL))aSyscall[60].pCurrent)
32208 { "WriteFile", (SYSCALL)WriteFile, 0 },
32210 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
32211 LPOVERLAPPED))aSyscall[61].pCurrent)
32213 #if SQLITE_OS_WINRT
32214 { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
32215 #else
32216 { "CreateEventExW", (SYSCALL)0, 0 },
32217 #endif
32219 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
32220 DWORD,DWORD))aSyscall[62].pCurrent)
32222 #if !SQLITE_OS_WINRT
32223 { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
32224 #else
32225 { "WaitForSingleObject", (SYSCALL)0, 0 },
32226 #endif
32228 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
32229 DWORD))aSyscall[63].pCurrent)
32231 #if SQLITE_OS_WINRT
32232 { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
32233 #else
32234 { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
32235 #endif
32237 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
32238 BOOL))aSyscall[64].pCurrent)
32240 #if SQLITE_OS_WINRT
32241 { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
32242 #else
32243 { "SetFilePointerEx", (SYSCALL)0, 0 },
32244 #endif
32246 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
32247 PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
32249 #if SQLITE_OS_WINRT
32250 { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
32251 #else
32252 { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
32253 #endif
32255 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
32256 FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
32258 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
32259 { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
32260 #else
32261 { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
32262 #endif
32264 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
32265 SIZE_T))aSyscall[67].pCurrent)
32267 #if SQLITE_OS_WINRT
32268 { "CreateFile2", (SYSCALL)CreateFile2, 0 },
32269 #else
32270 { "CreateFile2", (SYSCALL)0, 0 },
32271 #endif
32273 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
32274 LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
32276 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
32277 { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
32278 #else
32279 { "LoadPackagedLibrary", (SYSCALL)0, 0 },
32280 #endif
32282 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
32283 DWORD))aSyscall[69].pCurrent)
32285 #if SQLITE_OS_WINRT
32286 { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
32287 #else
32288 { "GetTickCount64", (SYSCALL)0, 0 },
32289 #endif
32291 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
32293 #if SQLITE_OS_WINRT
32294 { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
32295 #else
32296 { "GetNativeSystemInfo", (SYSCALL)0, 0 },
32297 #endif
32299 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
32300 LPSYSTEM_INFO))aSyscall[71].pCurrent)
32302 #if defined(SQLITE_WIN32_HAS_ANSI)
32303 { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
32304 #else
32305 { "OutputDebugStringA", (SYSCALL)0, 0 },
32306 #endif
32308 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
32310 #if defined(SQLITE_WIN32_HAS_WIDE)
32311 { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
32312 #else
32313 { "OutputDebugStringW", (SYSCALL)0, 0 },
32314 #endif
32316 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
32318 { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
32320 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
32322 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
32323 { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
32324 #else
32325 { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
32326 #endif
32328 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
32329 LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
32331 }; /* End of the overrideable system calls */
32334 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
32335 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
32336 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
32337 ** system call named zName.
32339 static int winSetSystemCall(
32340 sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
32341 const char *zName, /* Name of system call to override */
32342 sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
32344 unsigned int i;
32345 int rc = SQLITE_NOTFOUND;
32347 UNUSED_PARAMETER(pNotUsed);
32348 if( zName==0 ){
32349 /* If no zName is given, restore all system calls to their default
32350 ** settings and return NULL
32352 rc = SQLITE_OK;
32353 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32354 if( aSyscall[i].pDefault ){
32355 aSyscall[i].pCurrent = aSyscall[i].pDefault;
32358 }else{
32359 /* If zName is specified, operate on only the one system call
32360 ** specified.
32362 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32363 if( strcmp(zName, aSyscall[i].zName)==0 ){
32364 if( aSyscall[i].pDefault==0 ){
32365 aSyscall[i].pDefault = aSyscall[i].pCurrent;
32367 rc = SQLITE_OK;
32368 if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
32369 aSyscall[i].pCurrent = pNewFunc;
32370 break;
32374 return rc;
32378 ** Return the value of a system call. Return NULL if zName is not a
32379 ** recognized system call name. NULL is also returned if the system call
32380 ** is currently undefined.
32382 static sqlite3_syscall_ptr winGetSystemCall(
32383 sqlite3_vfs *pNotUsed,
32384 const char *zName
32386 unsigned int i;
32388 UNUSED_PARAMETER(pNotUsed);
32389 for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32390 if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
32392 return 0;
32396 ** Return the name of the first system call after zName. If zName==NULL
32397 ** then return the name of the first system call. Return NULL if zName
32398 ** is the last system call or if zName is not the name of a valid
32399 ** system call.
32401 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
32402 int i = -1;
32404 UNUSED_PARAMETER(p);
32405 if( zName ){
32406 for(i=0; i<ArraySize(aSyscall)-1; i++){
32407 if( strcmp(zName, aSyscall[i].zName)==0 ) break;
32410 for(i++; i<ArraySize(aSyscall); i++){
32411 if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
32413 return 0;
32416 #ifdef SQLITE_WIN32_MALLOC
32418 ** If a Win32 native heap has been configured, this function will attempt to
32419 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
32420 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
32421 ** "pnLargest" argument, if non-zero, will be used to return the size of the
32422 ** largest committed free block in the heap, in bytes.
32424 SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
32425 int rc = SQLITE_OK;
32426 UINT nLargest = 0;
32427 HANDLE hHeap;
32429 winMemAssertMagic();
32430 hHeap = winMemGetHeap();
32431 assert( hHeap!=0 );
32432 assert( hHeap!=INVALID_HANDLE_VALUE );
32433 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32434 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32435 #endif
32436 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
32437 if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
32438 DWORD lastErrno = osGetLastError();
32439 if( lastErrno==NO_ERROR ){
32440 sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
32441 (void*)hHeap);
32442 rc = SQLITE_NOMEM;
32443 }else{
32444 sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
32445 osGetLastError(), (void*)hHeap);
32446 rc = SQLITE_ERROR;
32449 #else
32450 sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
32451 (void*)hHeap);
32452 rc = SQLITE_NOTFOUND;
32453 #endif
32454 if( pnLargest ) *pnLargest = nLargest;
32455 return rc;
32459 ** If a Win32 native heap has been configured, this function will attempt to
32460 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
32461 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
32462 ** be returned and no changes will be made to the Win32 native heap.
32464 SQLITE_API int sqlite3_win32_reset_heap(){
32465 int rc;
32466 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
32467 MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
32468 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
32469 MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
32470 sqlite3_mutex_enter(pMaster);
32471 sqlite3_mutex_enter(pMem);
32472 winMemAssertMagic();
32473 if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
32475 ** At this point, there should be no outstanding memory allocations on
32476 ** the heap. Also, since both the master and memsys locks are currently
32477 ** being held by us, no other function (i.e. from another thread) should
32478 ** be able to even access the heap. Attempt to destroy and recreate our
32479 ** isolated Win32 native heap now.
32481 assert( winMemGetHeap()!=NULL );
32482 assert( winMemGetOwned() );
32483 assert( sqlite3_memory_used()==0 );
32484 winMemShutdown(winMemGetDataPtr());
32485 assert( winMemGetHeap()==NULL );
32486 assert( !winMemGetOwned() );
32487 assert( sqlite3_memory_used()==0 );
32488 rc = winMemInit(winMemGetDataPtr());
32489 assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
32490 assert( rc!=SQLITE_OK || winMemGetOwned() );
32491 assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
32492 }else{
32494 ** The Win32 native heap cannot be modified because it may be in use.
32496 rc = SQLITE_BUSY;
32498 sqlite3_mutex_leave(pMem);
32499 sqlite3_mutex_leave(pMaster);
32500 return rc;
32502 #endif /* SQLITE_WIN32_MALLOC */
32505 ** This function outputs the specified (ANSI) string to the Win32 debugger
32506 ** (if available).
32509 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
32510 char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
32511 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
32512 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
32513 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
32514 #if defined(SQLITE_WIN32_HAS_ANSI)
32515 if( nMin>0 ){
32516 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32517 memcpy(zDbgBuf, zBuf, nMin);
32518 osOutputDebugStringA(zDbgBuf);
32519 }else{
32520 osOutputDebugStringA(zBuf);
32522 #elif defined(SQLITE_WIN32_HAS_WIDE)
32523 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32524 if ( osMultiByteToWideChar(
32525 osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
32526 nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
32527 return;
32529 osOutputDebugStringW((LPCWSTR)zDbgBuf);
32530 #else
32531 if( nMin>0 ){
32532 memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
32533 memcpy(zDbgBuf, zBuf, nMin);
32534 fprintf(stderr, "%s", zDbgBuf);
32535 }else{
32536 fprintf(stderr, "%s", zBuf);
32538 #endif
32542 ** The following routine suspends the current thread for at least ms
32543 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
32545 #if SQLITE_OS_WINRT
32546 static HANDLE sleepObj = NULL;
32547 #endif
32549 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
32550 #if SQLITE_OS_WINRT
32551 if ( sleepObj==NULL ){
32552 sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
32553 SYNCHRONIZE);
32555 assert( sleepObj!=NULL );
32556 osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
32557 #else
32558 osSleep(milliseconds);
32559 #endif
32563 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
32564 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
32566 ** Here is an interesting observation: Win95, Win98, and WinME lack
32567 ** the LockFileEx() API. But we can still statically link against that
32568 ** API as long as we don't call it when running Win95/98/ME. A call to
32569 ** this routine is used to determine if the host is Win95/98/ME or
32570 ** WinNT/2K/XP so that we will know whether or not we can safely call
32571 ** the LockFileEx() API.
32574 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
32575 # define osIsNT() (1)
32576 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
32577 # define osIsNT() (1)
32578 #elif !defined(SQLITE_WIN32_HAS_WIDE)
32579 # define osIsNT() (0)
32580 #else
32581 static int osIsNT(void){
32582 if( sqlite3_os_type==0 ){
32583 #if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
32584 OSVERSIONINFOW sInfo;
32585 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32586 osGetVersionExW(&sInfo);
32587 #else
32588 OSVERSIONINFOA sInfo;
32589 sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32590 osGetVersionExA(&sInfo);
32591 #endif
32592 sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
32594 return sqlite3_os_type==2;
32596 #endif
32598 #ifdef SQLITE_WIN32_MALLOC
32600 ** Allocate nBytes of memory.
32602 static void *winMemMalloc(int nBytes){
32603 HANDLE hHeap;
32604 void *p;
32606 winMemAssertMagic();
32607 hHeap = winMemGetHeap();
32608 assert( hHeap!=0 );
32609 assert( hHeap!=INVALID_HANDLE_VALUE );
32610 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32611 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32612 #endif
32613 assert( nBytes>=0 );
32614 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32615 if( !p ){
32616 sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
32617 nBytes, osGetLastError(), (void*)hHeap);
32619 return p;
32623 ** Free memory.
32625 static void winMemFree(void *pPrior){
32626 HANDLE hHeap;
32628 winMemAssertMagic();
32629 hHeap = winMemGetHeap();
32630 assert( hHeap!=0 );
32631 assert( hHeap!=INVALID_HANDLE_VALUE );
32632 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32633 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32634 #endif
32635 if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
32636 if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
32637 sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
32638 pPrior, osGetLastError(), (void*)hHeap);
32643 ** Change the size of an existing memory allocation
32645 static void *winMemRealloc(void *pPrior, int nBytes){
32646 HANDLE hHeap;
32647 void *p;
32649 winMemAssertMagic();
32650 hHeap = winMemGetHeap();
32651 assert( hHeap!=0 );
32652 assert( hHeap!=INVALID_HANDLE_VALUE );
32653 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32654 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32655 #endif
32656 assert( nBytes>=0 );
32657 if( !pPrior ){
32658 p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32659 }else{
32660 p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
32662 if( !p ){
32663 sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
32664 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
32665 (void*)hHeap);
32667 return p;
32671 ** Return the size of an outstanding allocation, in bytes.
32673 static int winMemSize(void *p){
32674 HANDLE hHeap;
32675 SIZE_T n;
32677 winMemAssertMagic();
32678 hHeap = winMemGetHeap();
32679 assert( hHeap!=0 );
32680 assert( hHeap!=INVALID_HANDLE_VALUE );
32681 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32682 assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
32683 #endif
32684 if( !p ) return 0;
32685 n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
32686 if( n==(SIZE_T)-1 ){
32687 sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
32688 p, osGetLastError(), (void*)hHeap);
32689 return 0;
32691 return (int)n;
32695 ** Round up a request size to the next valid allocation size.
32697 static int winMemRoundup(int n){
32698 return n;
32702 ** Initialize this module.
32704 static int winMemInit(void *pAppData){
32705 winMemData *pWinMemData = (winMemData *)pAppData;
32707 if( !pWinMemData ) return SQLITE_ERROR;
32708 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
32709 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
32711 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
32712 if( !pWinMemData->hHeap ){
32713 DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
32714 DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
32715 if( dwMaximumSize==0 ){
32716 dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
32717 }else if( dwInitialSize>dwMaximumSize ){
32718 dwInitialSize = dwMaximumSize;
32720 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
32721 dwInitialSize, dwMaximumSize);
32722 if( !pWinMemData->hHeap ){
32723 sqlite3_log(SQLITE_NOMEM,
32724 "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
32725 osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
32726 dwMaximumSize);
32727 return SQLITE_NOMEM;
32729 pWinMemData->bOwned = TRUE;
32730 assert( pWinMemData->bOwned );
32732 #else
32733 pWinMemData->hHeap = osGetProcessHeap();
32734 if( !pWinMemData->hHeap ){
32735 sqlite3_log(SQLITE_NOMEM,
32736 "failed to GetProcessHeap (%lu)", osGetLastError());
32737 return SQLITE_NOMEM;
32739 pWinMemData->bOwned = FALSE;
32740 assert( !pWinMemData->bOwned );
32741 #endif
32742 assert( pWinMemData->hHeap!=0 );
32743 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32744 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32745 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32746 #endif
32747 return SQLITE_OK;
32751 ** Deinitialize this module.
32753 static void winMemShutdown(void *pAppData){
32754 winMemData *pWinMemData = (winMemData *)pAppData;
32756 if( !pWinMemData ) return;
32757 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
32758 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
32760 if( pWinMemData->hHeap ){
32761 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32762 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
32763 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32764 #endif
32765 if( pWinMemData->bOwned ){
32766 if( !osHeapDestroy(pWinMemData->hHeap) ){
32767 sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
32768 osGetLastError(), (void*)pWinMemData->hHeap);
32770 pWinMemData->bOwned = FALSE;
32772 pWinMemData->hHeap = NULL;
32777 ** Populate the low-level memory allocation function pointers in
32778 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
32779 ** arguments specify the block of memory to manage.
32781 ** This routine is only called by sqlite3_config(), and therefore
32782 ** is not required to be threadsafe (it is not).
32784 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
32785 static const sqlite3_mem_methods winMemMethods = {
32786 winMemMalloc,
32787 winMemFree,
32788 winMemRealloc,
32789 winMemSize,
32790 winMemRoundup,
32791 winMemInit,
32792 winMemShutdown,
32793 &win_mem_data
32795 return &winMemMethods;
32798 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
32799 sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
32801 #endif /* SQLITE_WIN32_MALLOC */
32804 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
32806 ** Space to hold the returned string is obtained from malloc.
32808 static LPWSTR winUtf8ToUnicode(const char *zFilename){
32809 int nChar;
32810 LPWSTR zWideFilename;
32812 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
32813 if( nChar==0 ){
32814 return 0;
32816 zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
32817 if( zWideFilename==0 ){
32818 return 0;
32820 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
32821 nChar);
32822 if( nChar==0 ){
32823 sqlite3_free(zWideFilename);
32824 zWideFilename = 0;
32826 return zWideFilename;
32830 ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
32831 ** obtained from sqlite3_malloc().
32833 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
32834 int nByte;
32835 char *zFilename;
32837 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
32838 if( nByte == 0 ){
32839 return 0;
32841 zFilename = sqlite3MallocZero( nByte );
32842 if( zFilename==0 ){
32843 return 0;
32845 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
32846 0, 0);
32847 if( nByte == 0 ){
32848 sqlite3_free(zFilename);
32849 zFilename = 0;
32851 return zFilename;
32855 ** Convert an ANSI string to Microsoft Unicode, based on the
32856 ** current codepage settings for file apis.
32858 ** Space to hold the returned string is obtained
32859 ** from sqlite3_malloc.
32861 static LPWSTR winMbcsToUnicode(const char *zFilename){
32862 int nByte;
32863 LPWSTR zMbcsFilename;
32864 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32866 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
32867 0)*sizeof(WCHAR);
32868 if( nByte==0 ){
32869 return 0;
32871 zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
32872 if( zMbcsFilename==0 ){
32873 return 0;
32875 nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
32876 nByte);
32877 if( nByte==0 ){
32878 sqlite3_free(zMbcsFilename);
32879 zMbcsFilename = 0;
32881 return zMbcsFilename;
32885 ** Convert Microsoft Unicode to multi-byte character string, based on the
32886 ** user's ANSI codepage.
32888 ** Space to hold the returned string is obtained from
32889 ** sqlite3_malloc().
32891 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
32892 int nByte;
32893 char *zFilename;
32894 int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32896 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32897 if( nByte == 0 ){
32898 return 0;
32900 zFilename = sqlite3MallocZero( nByte );
32901 if( zFilename==0 ){
32902 return 0;
32904 nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
32905 nByte, 0, 0);
32906 if( nByte == 0 ){
32907 sqlite3_free(zFilename);
32908 zFilename = 0;
32910 return zFilename;
32914 ** Convert multibyte character string to UTF-8. Space to hold the
32915 ** returned string is obtained from sqlite3_malloc().
32917 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32918 char *zFilenameUtf8;
32919 LPWSTR zTmpWide;
32921 zTmpWide = winMbcsToUnicode(zFilename);
32922 if( zTmpWide==0 ){
32923 return 0;
32925 zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
32926 sqlite3_free(zTmpWide);
32927 return zFilenameUtf8;
32931 ** Convert UTF-8 to multibyte character string. Space to hold the
32932 ** returned string is obtained from sqlite3_malloc().
32934 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32935 char *zFilenameMbcs;
32936 LPWSTR zTmpWide;
32938 zTmpWide = winUtf8ToUnicode(zFilename);
32939 if( zTmpWide==0 ){
32940 return 0;
32942 zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
32943 sqlite3_free(zTmpWide);
32944 return zFilenameMbcs;
32948 ** This function sets the data directory or the temporary directory based on
32949 ** the provided arguments. The type argument must be 1 in order to set the
32950 ** data directory or 2 in order to set the temporary directory. The zValue
32951 ** argument is the name of the directory to use. The return value will be
32952 ** SQLITE_OK if successful.
32954 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
32955 char **ppDirectory = 0;
32956 #ifndef SQLITE_OMIT_AUTOINIT
32957 int rc = sqlite3_initialize();
32958 if( rc ) return rc;
32959 #endif
32960 if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
32961 ppDirectory = &sqlite3_data_directory;
32962 }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
32963 ppDirectory = &sqlite3_temp_directory;
32965 assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
32966 || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32968 assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
32969 if( ppDirectory ){
32970 char *zValueUtf8 = 0;
32971 if( zValue && zValue[0] ){
32972 zValueUtf8 = winUnicodeToUtf8(zValue);
32973 if ( zValueUtf8==0 ){
32974 return SQLITE_NOMEM;
32977 sqlite3_free(*ppDirectory);
32978 *ppDirectory = zValueUtf8;
32979 return SQLITE_OK;
32981 return SQLITE_ERROR;
32985 ** The return value of winGetLastErrorMsg
32986 ** is zero if the error message fits in the buffer, or non-zero
32987 ** otherwise (if the message was truncated).
32989 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
32990 /* FormatMessage returns 0 on failure. Otherwise it
32991 ** returns the number of TCHARs written to the output
32992 ** buffer, excluding the terminating null char.
32994 DWORD dwLen = 0;
32995 char *zOut = 0;
32997 if( osIsNT() ){
32998 #if SQLITE_OS_WINRT
32999 WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
33000 dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
33001 FORMAT_MESSAGE_IGNORE_INSERTS,
33002 NULL,
33003 lastErrno,
33005 zTempWide,
33006 SQLITE_WIN32_MAX_ERRMSG_CHARS,
33008 #else
33009 LPWSTR zTempWide = NULL;
33010 dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33011 FORMAT_MESSAGE_FROM_SYSTEM |
33012 FORMAT_MESSAGE_IGNORE_INSERTS,
33013 NULL,
33014 lastErrno,
33016 (LPWSTR) &zTempWide,
33019 #endif
33020 if( dwLen > 0 ){
33021 /* allocate a buffer and convert to UTF8 */
33022 sqlite3BeginBenignMalloc();
33023 zOut = winUnicodeToUtf8(zTempWide);
33024 sqlite3EndBenignMalloc();
33025 #if !SQLITE_OS_WINRT
33026 /* free the system buffer allocated by FormatMessage */
33027 osLocalFree(zTempWide);
33028 #endif
33031 #ifdef SQLITE_WIN32_HAS_ANSI
33032 else{
33033 char *zTemp = NULL;
33034 dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33035 FORMAT_MESSAGE_FROM_SYSTEM |
33036 FORMAT_MESSAGE_IGNORE_INSERTS,
33037 NULL,
33038 lastErrno,
33040 (LPSTR) &zTemp,
33043 if( dwLen > 0 ){
33044 /* allocate a buffer and convert to UTF8 */
33045 sqlite3BeginBenignMalloc();
33046 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33047 sqlite3EndBenignMalloc();
33048 /* free the system buffer allocated by FormatMessage */
33049 osLocalFree(zTemp);
33052 #endif
33053 if( 0 == dwLen ){
33054 sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
33055 }else{
33056 /* copy a maximum of nBuf chars to output buffer */
33057 sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33058 /* free the UTF8 buffer */
33059 sqlite3_free(zOut);
33061 return 0;
33066 ** This function - winLogErrorAtLine() - is only ever called via the macro
33067 ** winLogError().
33069 ** This routine is invoked after an error occurs in an OS function.
33070 ** It logs a message using sqlite3_log() containing the current value of
33071 ** error code and, if possible, the human-readable equivalent from
33072 ** FormatMessage.
33074 ** The first argument passed to the macro should be the error code that
33075 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
33076 ** The two subsequent arguments should be the name of the OS function that
33077 ** failed and the associated file-system path, if any.
33079 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
33080 static int winLogErrorAtLine(
33081 int errcode, /* SQLite error code */
33082 DWORD lastErrno, /* Win32 last error */
33083 const char *zFunc, /* Name of OS function that failed */
33084 const char *zPath, /* File path associated with error */
33085 int iLine /* Source line number where error occurred */
33087 char zMsg[500]; /* Human readable error text */
33088 int i; /* Loop counter */
33090 zMsg[0] = 0;
33091 winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
33092 assert( errcode!=SQLITE_OK );
33093 if( zPath==0 ) zPath = "";
33094 for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
33095 zMsg[i] = 0;
33096 sqlite3_log(errcode,
33097 "os_win.c:%d: (%lu) %s(%s) - %s",
33098 iLine, lastErrno, zFunc, zPath, zMsg
33101 return errcode;
33105 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
33106 ** will be retried following a locking error - probably caused by
33107 ** antivirus software. Also the initial delay before the first retry.
33108 ** The delay increases linearly with each retry.
33110 #ifndef SQLITE_WIN32_IOERR_RETRY
33111 # define SQLITE_WIN32_IOERR_RETRY 10
33112 #endif
33113 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
33114 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
33115 #endif
33116 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
33117 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
33120 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
33121 ** to see if it should be retried. Return TRUE to retry. Return FALSE
33122 ** to give up with an error.
33124 static int winRetryIoerr(int *pnRetry, DWORD *pError){
33125 DWORD e = osGetLastError();
33126 if( *pnRetry>=winIoerrRetry ){
33127 if( pError ){
33128 *pError = e;
33130 return 0;
33132 if( e==ERROR_ACCESS_DENIED ||
33133 e==ERROR_LOCK_VIOLATION ||
33134 e==ERROR_SHARING_VIOLATION ){
33135 sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
33136 ++*pnRetry;
33137 return 1;
33139 if( pError ){
33140 *pError = e;
33142 return 0;
33146 ** Log a I/O error retry episode.
33148 static void winLogIoerr(int nRetry){
33149 if( nRetry ){
33150 sqlite3_log(SQLITE_IOERR,
33151 "delayed %dms for lock/sharing conflict",
33152 winIoerrRetryDelay*nRetry*(nRetry+1)/2
33157 #if SQLITE_OS_WINCE
33158 /*************************************************************************
33159 ** This section contains code for WinCE only.
33161 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
33163 ** The MSVC CRT on Windows CE may not have a localtime() function. So
33164 ** create a substitute.
33166 /* #include <time.h> */
33167 struct tm *__cdecl localtime(const time_t *t)
33169 static struct tm y;
33170 FILETIME uTm, lTm;
33171 SYSTEMTIME pTm;
33172 sqlite3_int64 t64;
33173 t64 = *t;
33174 t64 = (t64 + 11644473600)*10000000;
33175 uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
33176 uTm.dwHighDateTime= (DWORD)(t64 >> 32);
33177 osFileTimeToLocalFileTime(&uTm,&lTm);
33178 osFileTimeToSystemTime(&lTm,&pTm);
33179 y.tm_year = pTm.wYear - 1900;
33180 y.tm_mon = pTm.wMonth - 1;
33181 y.tm_wday = pTm.wDayOfWeek;
33182 y.tm_mday = pTm.wDay;
33183 y.tm_hour = pTm.wHour;
33184 y.tm_min = pTm.wMinute;
33185 y.tm_sec = pTm.wSecond;
33186 return &y;
33188 #endif
33190 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
33193 ** Acquire a lock on the handle h
33195 static void winceMutexAcquire(HANDLE h){
33196 DWORD dwErr;
33197 do {
33198 dwErr = osWaitForSingleObject(h, INFINITE);
33199 } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
33202 ** Release a lock acquired by winceMutexAcquire()
33204 #define winceMutexRelease(h) ReleaseMutex(h)
33207 ** Create the mutex and shared memory used for locking in the file
33208 ** descriptor pFile
33210 static int winceCreateLock(const char *zFilename, winFile *pFile){
33211 LPWSTR zTok;
33212 LPWSTR zName;
33213 DWORD lastErrno;
33214 BOOL bLogged = FALSE;
33215 BOOL bInit = TRUE;
33217 zName = winUtf8ToUnicode(zFilename);
33218 if( zName==0 ){
33219 /* out of memory */
33220 return SQLITE_IOERR_NOMEM;
33223 /* Initialize the local lockdata */
33224 memset(&pFile->local, 0, sizeof(pFile->local));
33226 /* Replace the backslashes from the filename and lowercase it
33227 ** to derive a mutex name. */
33228 zTok = osCharLowerW(zName);
33229 for (;*zTok;zTok++){
33230 if (*zTok == '\\') *zTok = '_';
33233 /* Create/open the named mutex */
33234 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
33235 if (!pFile->hMutex){
33236 pFile->lastErrno = osGetLastError();
33237 sqlite3_free(zName);
33238 return winLogError(SQLITE_IOERR, pFile->lastErrno,
33239 "winceCreateLock1", zFilename);
33242 /* Acquire the mutex before continuing */
33243 winceMutexAcquire(pFile->hMutex);
33245 /* Since the names of named mutexes, semaphores, file mappings etc are
33246 ** case-sensitive, take advantage of that by uppercasing the mutex name
33247 ** and using that as the shared filemapping name.
33249 osCharUpperW(zName);
33250 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
33251 PAGE_READWRITE, 0, sizeof(winceLock),
33252 zName);
33254 /* Set a flag that indicates we're the first to create the memory so it
33255 ** must be zero-initialized */
33256 lastErrno = osGetLastError();
33257 if (lastErrno == ERROR_ALREADY_EXISTS){
33258 bInit = FALSE;
33261 sqlite3_free(zName);
33263 /* If we succeeded in making the shared memory handle, map it. */
33264 if( pFile->hShared ){
33265 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
33266 FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
33267 /* If mapping failed, close the shared memory handle and erase it */
33268 if( !pFile->shared ){
33269 pFile->lastErrno = osGetLastError();
33270 winLogError(SQLITE_IOERR, pFile->lastErrno,
33271 "winceCreateLock2", zFilename);
33272 bLogged = TRUE;
33273 osCloseHandle(pFile->hShared);
33274 pFile->hShared = NULL;
33278 /* If shared memory could not be created, then close the mutex and fail */
33279 if( pFile->hShared==NULL ){
33280 if( !bLogged ){
33281 pFile->lastErrno = lastErrno;
33282 winLogError(SQLITE_IOERR, pFile->lastErrno,
33283 "winceCreateLock3", zFilename);
33284 bLogged = TRUE;
33286 winceMutexRelease(pFile->hMutex);
33287 osCloseHandle(pFile->hMutex);
33288 pFile->hMutex = NULL;
33289 return SQLITE_IOERR;
33292 /* Initialize the shared memory if we're supposed to */
33293 if( bInit ){
33294 memset(pFile->shared, 0, sizeof(winceLock));
33297 winceMutexRelease(pFile->hMutex);
33298 return SQLITE_OK;
33302 ** Destroy the part of winFile that deals with wince locks
33304 static void winceDestroyLock(winFile *pFile){
33305 if (pFile->hMutex){
33306 /* Acquire the mutex */
33307 winceMutexAcquire(pFile->hMutex);
33309 /* The following blocks should probably assert in debug mode, but they
33310 are to cleanup in case any locks remained open */
33311 if (pFile->local.nReaders){
33312 pFile->shared->nReaders --;
33314 if (pFile->local.bReserved){
33315 pFile->shared->bReserved = FALSE;
33317 if (pFile->local.bPending){
33318 pFile->shared->bPending = FALSE;
33320 if (pFile->local.bExclusive){
33321 pFile->shared->bExclusive = FALSE;
33324 /* De-reference and close our copy of the shared memory handle */
33325 osUnmapViewOfFile(pFile->shared);
33326 osCloseHandle(pFile->hShared);
33328 /* Done with the mutex */
33329 winceMutexRelease(pFile->hMutex);
33330 osCloseHandle(pFile->hMutex);
33331 pFile->hMutex = NULL;
33336 ** An implementation of the LockFile() API of Windows for CE
33338 static BOOL winceLockFile(
33339 LPHANDLE phFile,
33340 DWORD dwFileOffsetLow,
33341 DWORD dwFileOffsetHigh,
33342 DWORD nNumberOfBytesToLockLow,
33343 DWORD nNumberOfBytesToLockHigh
33345 winFile *pFile = HANDLE_TO_WINFILE(phFile);
33346 BOOL bReturn = FALSE;
33348 UNUSED_PARAMETER(dwFileOffsetHigh);
33349 UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33351 if (!pFile->hMutex) return TRUE;
33352 winceMutexAcquire(pFile->hMutex);
33354 /* Wanting an exclusive lock? */
33355 if (dwFileOffsetLow == (DWORD)SHARED_FIRST
33356 && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33357 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
33358 pFile->shared->bExclusive = TRUE;
33359 pFile->local.bExclusive = TRUE;
33360 bReturn = TRUE;
33364 /* Want a read-only lock? */
33365 else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
33366 nNumberOfBytesToLockLow == 1){
33367 if (pFile->shared->bExclusive == 0){
33368 pFile->local.nReaders ++;
33369 if (pFile->local.nReaders == 1){
33370 pFile->shared->nReaders ++;
33372 bReturn = TRUE;
33376 /* Want a pending lock? */
33377 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
33378 && nNumberOfBytesToLockLow == 1){
33379 /* If no pending lock has been acquired, then acquire it */
33380 if (pFile->shared->bPending == 0) {
33381 pFile->shared->bPending = TRUE;
33382 pFile->local.bPending = TRUE;
33383 bReturn = TRUE;
33387 /* Want a reserved lock? */
33388 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
33389 && nNumberOfBytesToLockLow == 1){
33390 if (pFile->shared->bReserved == 0) {
33391 pFile->shared->bReserved = TRUE;
33392 pFile->local.bReserved = TRUE;
33393 bReturn = TRUE;
33397 winceMutexRelease(pFile->hMutex);
33398 return bReturn;
33402 ** An implementation of the UnlockFile API of Windows for CE
33404 static BOOL winceUnlockFile(
33405 LPHANDLE phFile,
33406 DWORD dwFileOffsetLow,
33407 DWORD dwFileOffsetHigh,
33408 DWORD nNumberOfBytesToUnlockLow,
33409 DWORD nNumberOfBytesToUnlockHigh
33411 winFile *pFile = HANDLE_TO_WINFILE(phFile);
33412 BOOL bReturn = FALSE;
33414 UNUSED_PARAMETER(dwFileOffsetHigh);
33415 UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
33417 if (!pFile->hMutex) return TRUE;
33418 winceMutexAcquire(pFile->hMutex);
33420 /* Releasing a reader lock or an exclusive lock */
33421 if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
33422 /* Did we have an exclusive lock? */
33423 if (pFile->local.bExclusive){
33424 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
33425 pFile->local.bExclusive = FALSE;
33426 pFile->shared->bExclusive = FALSE;
33427 bReturn = TRUE;
33430 /* Did we just have a reader lock? */
33431 else if (pFile->local.nReaders){
33432 assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
33433 || nNumberOfBytesToUnlockLow == 1);
33434 pFile->local.nReaders --;
33435 if (pFile->local.nReaders == 0)
33437 pFile->shared->nReaders --;
33439 bReturn = TRUE;
33443 /* Releasing a pending lock */
33444 else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
33445 && nNumberOfBytesToUnlockLow == 1){
33446 if (pFile->local.bPending){
33447 pFile->local.bPending = FALSE;
33448 pFile->shared->bPending = FALSE;
33449 bReturn = TRUE;
33452 /* Releasing a reserved lock */
33453 else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
33454 && nNumberOfBytesToUnlockLow == 1){
33455 if (pFile->local.bReserved) {
33456 pFile->local.bReserved = FALSE;
33457 pFile->shared->bReserved = FALSE;
33458 bReturn = TRUE;
33462 winceMutexRelease(pFile->hMutex);
33463 return bReturn;
33466 ** End of the special code for wince
33467 *****************************************************************************/
33468 #endif /* SQLITE_OS_WINCE */
33471 ** Lock a file region.
33473 static BOOL winLockFile(
33474 LPHANDLE phFile,
33475 DWORD flags,
33476 DWORD offsetLow,
33477 DWORD offsetHigh,
33478 DWORD numBytesLow,
33479 DWORD numBytesHigh
33481 #if SQLITE_OS_WINCE
33483 ** NOTE: Windows CE is handled differently here due its lack of the Win32
33484 ** API LockFile.
33486 return winceLockFile(phFile, offsetLow, offsetHigh,
33487 numBytesLow, numBytesHigh);
33488 #else
33489 if( osIsNT() ){
33490 OVERLAPPED ovlp;
33491 memset(&ovlp, 0, sizeof(OVERLAPPED));
33492 ovlp.Offset = offsetLow;
33493 ovlp.OffsetHigh = offsetHigh;
33494 return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
33495 }else{
33496 return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
33497 numBytesHigh);
33499 #endif
33503 ** Unlock a file region.
33505 static BOOL winUnlockFile(
33506 LPHANDLE phFile,
33507 DWORD offsetLow,
33508 DWORD offsetHigh,
33509 DWORD numBytesLow,
33510 DWORD numBytesHigh
33512 #if SQLITE_OS_WINCE
33514 ** NOTE: Windows CE is handled differently here due its lack of the Win32
33515 ** API UnlockFile.
33517 return winceUnlockFile(phFile, offsetLow, offsetHigh,
33518 numBytesLow, numBytesHigh);
33519 #else
33520 if( osIsNT() ){
33521 OVERLAPPED ovlp;
33522 memset(&ovlp, 0, sizeof(OVERLAPPED));
33523 ovlp.Offset = offsetLow;
33524 ovlp.OffsetHigh = offsetHigh;
33525 return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
33526 }else{
33527 return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
33528 numBytesHigh);
33530 #endif
33533 /*****************************************************************************
33534 ** The next group of routines implement the I/O methods specified
33535 ** by the sqlite3_io_methods object.
33536 ******************************************************************************/
33539 ** Some Microsoft compilers lack this definition.
33541 #ifndef INVALID_SET_FILE_POINTER
33542 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
33543 #endif
33546 ** Move the current position of the file handle passed as the first
33547 ** argument to offset iOffset within the file. If successful, return 0.
33548 ** Otherwise, set pFile->lastErrno and return non-zero.
33550 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
33551 #if !SQLITE_OS_WINRT
33552 LONG upperBits; /* Most sig. 32 bits of new offset */
33553 LONG lowerBits; /* Least sig. 32 bits of new offset */
33554 DWORD dwRet; /* Value returned by SetFilePointer() */
33555 DWORD lastErrno; /* Value returned by GetLastError() */
33557 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
33559 upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
33560 lowerBits = (LONG)(iOffset & 0xffffffff);
33562 /* API oddity: If successful, SetFilePointer() returns a dword
33563 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
33564 ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
33565 ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
33566 ** whether an error has actually occurred, it is also necessary to call
33567 ** GetLastError().
33569 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
33571 if( (dwRet==INVALID_SET_FILE_POINTER
33572 && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
33573 pFile->lastErrno = lastErrno;
33574 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33575 "winSeekFile", pFile->zPath);
33576 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
33577 return 1;
33580 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
33581 return 0;
33582 #else
33584 ** Same as above, except that this implementation works for WinRT.
33587 LARGE_INTEGER x; /* The new offset */
33588 BOOL bRet; /* Value returned by SetFilePointerEx() */
33590 x.QuadPart = iOffset;
33591 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
33593 if(!bRet){
33594 pFile->lastErrno = osGetLastError();
33595 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33596 "winSeekFile", pFile->zPath);
33597 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
33598 return 1;
33601 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
33602 return 0;
33603 #endif
33606 #if SQLITE_MAX_MMAP_SIZE>0
33607 /* Forward references to VFS helper methods used for memory mapped files */
33608 static int winMapfile(winFile*, sqlite3_int64);
33609 static int winUnmapfile(winFile*);
33610 #endif
33613 ** Close a file.
33615 ** It is reported that an attempt to close a handle might sometimes
33616 ** fail. This is a very unreasonable result, but Windows is notorious
33617 ** for being unreasonable so I do not doubt that it might happen. If
33618 ** the close fails, we pause for 100 milliseconds and try again. As
33619 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
33620 ** giving up and returning an error.
33622 #define MX_CLOSE_ATTEMPT 3
33623 static int winClose(sqlite3_file *id){
33624 int rc, cnt = 0;
33625 winFile *pFile = (winFile*)id;
33627 assert( id!=0 );
33628 #ifndef SQLITE_OMIT_WAL
33629 assert( pFile->pShm==0 );
33630 #endif
33631 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
33632 OSTRACE(("CLOSE file=%p\n", pFile->h));
33634 #if SQLITE_MAX_MMAP_SIZE>0
33635 winUnmapfile(pFile);
33636 #endif
33639 rc = osCloseHandle(pFile->h);
33640 /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
33641 }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
33642 #if SQLITE_OS_WINCE
33643 #define WINCE_DELETION_ATTEMPTS 3
33644 winceDestroyLock(pFile);
33645 if( pFile->zDeleteOnClose ){
33646 int cnt = 0;
33647 while(
33648 osDeleteFileW(pFile->zDeleteOnClose)==0
33649 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
33650 && cnt++ < WINCE_DELETION_ATTEMPTS
33652 sqlite3_win32_sleep(100); /* Wait a little before trying again */
33654 sqlite3_free(pFile->zDeleteOnClose);
33656 #endif
33657 if( rc ){
33658 pFile->h = NULL;
33660 OpenCounter(-1);
33661 OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
33662 return rc ? SQLITE_OK
33663 : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
33664 "winClose", pFile->zPath);
33668 ** Read data from a file into a buffer. Return SQLITE_OK if all
33669 ** bytes were read successfully and SQLITE_IOERR if anything goes
33670 ** wrong.
33672 static int winRead(
33673 sqlite3_file *id, /* File to read from */
33674 void *pBuf, /* Write content into this buffer */
33675 int amt, /* Number of bytes to read */
33676 sqlite3_int64 offset /* Begin reading at this offset */
33678 #if !SQLITE_OS_WINCE
33679 OVERLAPPED overlapped; /* The offset for ReadFile. */
33680 #endif
33681 winFile *pFile = (winFile*)id; /* file handle */
33682 DWORD nRead; /* Number of bytes actually read from file */
33683 int nRetry = 0; /* Number of retrys */
33685 assert( id!=0 );
33686 assert( amt>0 );
33687 assert( offset>=0 );
33688 SimulateIOError(return SQLITE_IOERR_READ);
33689 OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
33690 pFile->h, pBuf, amt, offset, pFile->locktype));
33692 #if SQLITE_MAX_MMAP_SIZE>0
33693 /* Deal with as much of this read request as possible by transfering
33694 ** data from the memory mapping using memcpy(). */
33695 if( offset<pFile->mmapSize ){
33696 if( offset+amt <= pFile->mmapSize ){
33697 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
33698 OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
33699 return SQLITE_OK;
33700 }else{
33701 int nCopy = (int)(pFile->mmapSize - offset);
33702 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
33703 pBuf = &((u8 *)pBuf)[nCopy];
33704 amt -= nCopy;
33705 offset += nCopy;
33708 #endif
33710 #if SQLITE_OS_WINCE
33711 if( winSeekFile(pFile, offset) ){
33712 OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
33713 return SQLITE_FULL;
33715 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
33716 #else
33717 memset(&overlapped, 0, sizeof(OVERLAPPED));
33718 overlapped.Offset = (LONG)(offset & 0xffffffff);
33719 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33720 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
33721 osGetLastError()!=ERROR_HANDLE_EOF ){
33722 #endif
33723 DWORD lastErrno;
33724 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
33725 pFile->lastErrno = lastErrno;
33726 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
33727 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
33728 "winRead", pFile->zPath);
33730 winLogIoerr(nRetry);
33731 if( nRead<(DWORD)amt ){
33732 /* Unread parts of the buffer must be zero-filled */
33733 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
33734 OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
33735 return SQLITE_IOERR_SHORT_READ;
33738 OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
33739 return SQLITE_OK;
33743 ** Write data from a buffer into a file. Return SQLITE_OK on success
33744 ** or some other error code on failure.
33746 static int winWrite(
33747 sqlite3_file *id, /* File to write into */
33748 const void *pBuf, /* The bytes to be written */
33749 int amt, /* Number of bytes to write */
33750 sqlite3_int64 offset /* Offset into the file to begin writing at */
33752 int rc = 0; /* True if error has occurred, else false */
33753 winFile *pFile = (winFile*)id; /* File handle */
33754 int nRetry = 0; /* Number of retries */
33756 assert( amt>0 );
33757 assert( pFile );
33758 SimulateIOError(return SQLITE_IOERR_WRITE);
33759 SimulateDiskfullError(return SQLITE_FULL);
33761 OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
33762 pFile->h, pBuf, amt, offset, pFile->locktype));
33764 #if SQLITE_MAX_MMAP_SIZE>0
33765 /* Deal with as much of this write request as possible by transfering
33766 ** data from the memory mapping using memcpy(). */
33767 if( offset<pFile->mmapSize ){
33768 if( offset+amt <= pFile->mmapSize ){
33769 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
33770 OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
33771 return SQLITE_OK;
33772 }else{
33773 int nCopy = (int)(pFile->mmapSize - offset);
33774 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
33775 pBuf = &((u8 *)pBuf)[nCopy];
33776 amt -= nCopy;
33777 offset += nCopy;
33780 #endif
33782 #if SQLITE_OS_WINCE
33783 rc = winSeekFile(pFile, offset);
33784 if( rc==0 ){
33785 #else
33787 #endif
33788 #if !SQLITE_OS_WINCE
33789 OVERLAPPED overlapped; /* The offset for WriteFile. */
33790 #endif
33791 u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
33792 int nRem = amt; /* Number of bytes yet to be written */
33793 DWORD nWrite; /* Bytes written by each WriteFile() call */
33794 DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
33796 #if !SQLITE_OS_WINCE
33797 memset(&overlapped, 0, sizeof(OVERLAPPED));
33798 overlapped.Offset = (LONG)(offset & 0xffffffff);
33799 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33800 #endif
33802 while( nRem>0 ){
33803 #if SQLITE_OS_WINCE
33804 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
33805 #else
33806 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
33807 #endif
33808 if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
33809 break;
33811 assert( nWrite==0 || nWrite<=(DWORD)nRem );
33812 if( nWrite==0 || nWrite>(DWORD)nRem ){
33813 lastErrno = osGetLastError();
33814 break;
33816 #if !SQLITE_OS_WINCE
33817 offset += nWrite;
33818 overlapped.Offset = (LONG)(offset & 0xffffffff);
33819 overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33820 #endif
33821 aRem += nWrite;
33822 nRem -= nWrite;
33824 if( nRem>0 ){
33825 pFile->lastErrno = lastErrno;
33826 rc = 1;
33830 if( rc ){
33831 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
33832 || ( pFile->lastErrno==ERROR_DISK_FULL )){
33833 OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
33834 return winLogError(SQLITE_FULL, pFile->lastErrno,
33835 "winWrite1", pFile->zPath);
33837 OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
33838 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
33839 "winWrite2", pFile->zPath);
33840 }else{
33841 winLogIoerr(nRetry);
33843 OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
33844 return SQLITE_OK;
33848 ** Truncate an open file to a specified size
33850 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
33851 winFile *pFile = (winFile*)id; /* File handle object */
33852 int rc = SQLITE_OK; /* Return code for this function */
33853 DWORD lastErrno;
33855 assert( pFile );
33856 SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33857 OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
33858 pFile->h, nByte, pFile->locktype));
33860 /* If the user has configured a chunk-size for this file, truncate the
33861 ** file so that it consists of an integer number of chunks (i.e. the
33862 ** actual file size after the operation may be larger than the requested
33863 ** size).
33865 if( pFile->szChunk>0 ){
33866 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33869 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33870 if( winSeekFile(pFile, nByte) ){
33871 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33872 "winTruncate1", pFile->zPath);
33873 }else if( 0==osSetEndOfFile(pFile->h) &&
33874 ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
33875 pFile->lastErrno = lastErrno;
33876 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33877 "winTruncate2", pFile->zPath);
33880 #if SQLITE_MAX_MMAP_SIZE>0
33881 /* If the file was truncated to a size smaller than the currently
33882 ** mapped region, reduce the effective mapping size as well. SQLite will
33883 ** use read() and write() to access data beyond this point from now on.
33885 if( pFile->pMapRegion && nByte<pFile->mmapSize ){
33886 pFile->mmapSize = nByte;
33888 #endif
33890 OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33891 return rc;
33894 #ifdef SQLITE_TEST
33896 ** Count the number of fullsyncs and normal syncs. This is used to test
33897 ** that syncs and fullsyncs are occuring at the right times.
33899 SQLITE_API int sqlite3_sync_count = 0;
33900 SQLITE_API int sqlite3_fullsync_count = 0;
33901 #endif
33904 ** Make sure all writes to a particular file are committed to disk.
33906 static int winSync(sqlite3_file *id, int flags){
33907 #ifndef SQLITE_NO_SYNC
33909 ** Used only when SQLITE_NO_SYNC is not defined.
33911 BOOL rc;
33912 #endif
33913 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33914 (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33916 ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33917 ** OSTRACE() macros.
33919 winFile *pFile = (winFile*)id;
33920 #else
33921 UNUSED_PARAMETER(id);
33922 #endif
33924 assert( pFile );
33925 /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33926 assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33927 || (flags&0x0F)==SQLITE_SYNC_FULL
33930 /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33931 ** line is to test that doing so does not cause any problems.
33933 SimulateDiskfullError( return SQLITE_FULL );
33935 OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
33936 pFile->h, flags, pFile->locktype));
33938 #ifndef SQLITE_TEST
33939 UNUSED_PARAMETER(flags);
33940 #else
33941 if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33942 sqlite3_fullsync_count++;
33944 sqlite3_sync_count++;
33945 #endif
33947 /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33948 ** no-op
33950 #ifdef SQLITE_NO_SYNC
33951 OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
33952 return SQLITE_OK;
33953 #else
33954 rc = osFlushFileBuffers(pFile->h);
33955 SimulateIOError( rc=FALSE );
33956 if( rc ){
33957 OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
33958 return SQLITE_OK;
33959 }else{
33960 pFile->lastErrno = osGetLastError();
33961 OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
33962 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33963 "winSync", pFile->zPath);
33965 #endif
33969 ** Determine the current size of a file in bytes
33971 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33972 winFile *pFile = (winFile*)id;
33973 int rc = SQLITE_OK;
33975 assert( id!=0 );
33976 assert( pSize!=0 );
33977 SimulateIOError(return SQLITE_IOERR_FSTAT);
33978 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
33980 #if SQLITE_OS_WINRT
33982 FILE_STANDARD_INFO info;
33983 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
33984 &info, sizeof(info)) ){
33985 *pSize = info.EndOfFile.QuadPart;
33986 }else{
33987 pFile->lastErrno = osGetLastError();
33988 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33989 "winFileSize", pFile->zPath);
33992 #else
33994 DWORD upperBits;
33995 DWORD lowerBits;
33996 DWORD lastErrno;
33998 lowerBits = osGetFileSize(pFile->h, &upperBits);
33999 *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
34000 if( (lowerBits == INVALID_FILE_SIZE)
34001 && ((lastErrno = osGetLastError())!=NO_ERROR) ){
34002 pFile->lastErrno = lastErrno;
34003 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
34004 "winFileSize", pFile->zPath);
34007 #endif
34008 OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
34009 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
34010 return rc;
34014 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
34016 #ifndef LOCKFILE_FAIL_IMMEDIATELY
34017 # define LOCKFILE_FAIL_IMMEDIATELY 1
34018 #endif
34020 #ifndef LOCKFILE_EXCLUSIVE_LOCK
34021 # define LOCKFILE_EXCLUSIVE_LOCK 2
34022 #endif
34025 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
34026 ** When the LockFile function was used, it was always expected to fail
34027 ** immediately if the lock could not be obtained. Also, it always expected to
34028 ** obtain an exclusive lock. These flags are used with the LockFileEx function
34029 ** and reflect those expectations; therefore, they should not be changed.
34031 #ifndef SQLITE_LOCKFILE_FLAGS
34032 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
34033 LOCKFILE_EXCLUSIVE_LOCK)
34034 #endif
34037 ** Currently, SQLite never calls the LockFileEx function without wanting the
34038 ** call to fail immediately if the lock cannot be obtained.
34040 #ifndef SQLITE_LOCKFILEEX_FLAGS
34041 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
34042 #endif
34045 ** Acquire a reader lock.
34046 ** Different API routines are called depending on whether or not this
34047 ** is Win9x or WinNT.
34049 static int winGetReadLock(winFile *pFile){
34050 int res;
34051 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
34052 if( osIsNT() ){
34053 #if SQLITE_OS_WINCE
34055 ** NOTE: Windows CE is handled differently here due its lack of the Win32
34056 ** API LockFileEx.
34058 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
34059 #else
34060 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
34061 SHARED_SIZE, 0);
34062 #endif
34064 #ifdef SQLITE_WIN32_HAS_ANSI
34065 else{
34066 int lk;
34067 sqlite3_randomness(sizeof(lk), &lk);
34068 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
34069 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34070 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34072 #endif
34073 if( res == 0 ){
34074 pFile->lastErrno = osGetLastError();
34075 /* No need to log a failure to lock */
34077 OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
34078 return res;
34082 ** Undo a readlock
34084 static int winUnlockReadLock(winFile *pFile){
34085 int res;
34086 DWORD lastErrno;
34087 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
34088 if( osIsNT() ){
34089 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34091 #ifdef SQLITE_WIN32_HAS_ANSI
34092 else{
34093 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
34095 #endif
34096 if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
34097 pFile->lastErrno = lastErrno;
34098 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
34099 "winUnlockReadLock", pFile->zPath);
34101 OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
34102 return res;
34106 ** Lock the file with the lock specified by parameter locktype - one
34107 ** of the following:
34109 ** (1) SHARED_LOCK
34110 ** (2) RESERVED_LOCK
34111 ** (3) PENDING_LOCK
34112 ** (4) EXCLUSIVE_LOCK
34114 ** Sometimes when requesting one lock state, additional lock states
34115 ** are inserted in between. The locking might fail on one of the later
34116 ** transitions leaving the lock state different from what it started but
34117 ** still short of its goal. The following chart shows the allowed
34118 ** transitions and the inserted intermediate states:
34120 ** UNLOCKED -> SHARED
34121 ** SHARED -> RESERVED
34122 ** SHARED -> (PENDING) -> EXCLUSIVE
34123 ** RESERVED -> (PENDING) -> EXCLUSIVE
34124 ** PENDING -> EXCLUSIVE
34126 ** This routine will only increase a lock. The winUnlock() routine
34127 ** erases all locks at once and returns us immediately to locking level 0.
34128 ** It is not possible to lower the locking level one step at a time. You
34129 ** must go straight to locking level 0.
34131 static int winLock(sqlite3_file *id, int locktype){
34132 int rc = SQLITE_OK; /* Return code from subroutines */
34133 int res = 1; /* Result of a Windows lock call */
34134 int newLocktype; /* Set pFile->locktype to this value before exiting */
34135 int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
34136 winFile *pFile = (winFile*)id;
34137 DWORD lastErrno = NO_ERROR;
34139 assert( id!=0 );
34140 OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
34141 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
34143 /* If there is already a lock of this type or more restrictive on the
34144 ** OsFile, do nothing. Don't use the end_lock: exit path, as
34145 ** sqlite3OsEnterMutex() hasn't been called yet.
34147 if( pFile->locktype>=locktype ){
34148 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
34149 return SQLITE_OK;
34152 /* Make sure the locking sequence is correct
34154 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
34155 assert( locktype!=PENDING_LOCK );
34156 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
34158 /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
34159 ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
34160 ** the PENDING_LOCK byte is temporary.
34162 newLocktype = pFile->locktype;
34163 if( (pFile->locktype==NO_LOCK)
34164 || ( (locktype==EXCLUSIVE_LOCK)
34165 && (pFile->locktype==RESERVED_LOCK))
34167 int cnt = 3;
34168 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
34169 PENDING_BYTE, 0, 1, 0))==0 ){
34170 /* Try 3 times to get the pending lock. This is needed to work
34171 ** around problems caused by indexing and/or anti-virus software on
34172 ** Windows systems.
34173 ** If you are using this code as a model for alternative VFSes, do not
34174 ** copy this retry logic. It is a hack intended for Windows only.
34176 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
34177 pFile->h, cnt, sqlite3ErrName(res)));
34178 if( cnt ) sqlite3_win32_sleep(1);
34180 gotPendingLock = res;
34181 if( !res ){
34182 lastErrno = osGetLastError();
34186 /* Acquire a shared lock
34188 if( locktype==SHARED_LOCK && res ){
34189 assert( pFile->locktype==NO_LOCK );
34190 res = winGetReadLock(pFile);
34191 if( res ){
34192 newLocktype = SHARED_LOCK;
34193 }else{
34194 lastErrno = osGetLastError();
34198 /* Acquire a RESERVED lock
34200 if( locktype==RESERVED_LOCK && res ){
34201 assert( pFile->locktype==SHARED_LOCK );
34202 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
34203 if( res ){
34204 newLocktype = RESERVED_LOCK;
34205 }else{
34206 lastErrno = osGetLastError();
34210 /* Acquire a PENDING lock
34212 if( locktype==EXCLUSIVE_LOCK && res ){
34213 newLocktype = PENDING_LOCK;
34214 gotPendingLock = 0;
34217 /* Acquire an EXCLUSIVE lock
34219 if( locktype==EXCLUSIVE_LOCK && res ){
34220 assert( pFile->locktype>=SHARED_LOCK );
34221 res = winUnlockReadLock(pFile);
34222 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
34223 SHARED_SIZE, 0);
34224 if( res ){
34225 newLocktype = EXCLUSIVE_LOCK;
34226 }else{
34227 lastErrno = osGetLastError();
34228 winGetReadLock(pFile);
34232 /* If we are holding a PENDING lock that ought to be released, then
34233 ** release it now.
34235 if( gotPendingLock && locktype==SHARED_LOCK ){
34236 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34239 /* Update the state of the lock has held in the file descriptor then
34240 ** return the appropriate result code.
34242 if( res ){
34243 rc = SQLITE_OK;
34244 }else{
34245 pFile->lastErrno = lastErrno;
34246 rc = SQLITE_BUSY;
34247 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
34248 pFile->h, locktype, newLocktype));
34250 pFile->locktype = (u8)newLocktype;
34251 OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
34252 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
34253 return rc;
34257 ** This routine checks if there is a RESERVED lock held on the specified
34258 ** file by this or any other process. If such a lock is held, return
34259 ** non-zero, otherwise zero.
34261 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
34262 int rc;
34263 winFile *pFile = (winFile*)id;
34265 SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
34266 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
34268 assert( id!=0 );
34269 if( pFile->locktype>=RESERVED_LOCK ){
34270 rc = 1;
34271 OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
34272 }else{
34273 rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
34274 if( rc ){
34275 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34277 rc = !rc;
34278 OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
34280 *pResOut = rc;
34281 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
34282 pFile->h, pResOut, *pResOut));
34283 return SQLITE_OK;
34287 ** Lower the locking level on file descriptor id to locktype. locktype
34288 ** must be either NO_LOCK or SHARED_LOCK.
34290 ** If the locking level of the file descriptor is already at or below
34291 ** the requested locking level, this routine is a no-op.
34293 ** It is not possible for this routine to fail if the second argument
34294 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
34295 ** might return SQLITE_IOERR;
34297 static int winUnlock(sqlite3_file *id, int locktype){
34298 int type;
34299 winFile *pFile = (winFile*)id;
34300 int rc = SQLITE_OK;
34301 assert( pFile!=0 );
34302 assert( locktype<=SHARED_LOCK );
34303 OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
34304 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
34305 type = pFile->locktype;
34306 if( type>=EXCLUSIVE_LOCK ){
34307 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34308 if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
34309 /* This should never happen. We should always be able to
34310 ** reacquire the read lock */
34311 rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
34312 "winUnlock", pFile->zPath);
34315 if( type>=RESERVED_LOCK ){
34316 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
34318 if( locktype==NO_LOCK && type>=SHARED_LOCK ){
34319 winUnlockReadLock(pFile);
34321 if( type>=PENDING_LOCK ){
34322 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
34324 pFile->locktype = (u8)locktype;
34325 OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
34326 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
34327 return rc;
34331 ** If *pArg is inititially negative then this is a query. Set *pArg to
34332 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34334 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34336 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
34337 if( *pArg<0 ){
34338 *pArg = (pFile->ctrlFlags & mask)!=0;
34339 }else if( (*pArg)==0 ){
34340 pFile->ctrlFlags &= ~mask;
34341 }else{
34342 pFile->ctrlFlags |= mask;
34346 /* Forward references to VFS helper methods used for temporary files */
34347 static int winGetTempname(sqlite3_vfs *, char **);
34348 static int winIsDir(const void *);
34349 static BOOL winIsDriveLetterAndColon(const char *);
34352 ** Control and query of the open file handle.
34354 static int winFileControl(sqlite3_file *id, int op, void *pArg){
34355 winFile *pFile = (winFile*)id;
34356 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
34357 switch( op ){
34358 case SQLITE_FCNTL_LOCKSTATE: {
34359 *(int*)pArg = pFile->locktype;
34360 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34361 return SQLITE_OK;
34363 case SQLITE_LAST_ERRNO: {
34364 *(int*)pArg = (int)pFile->lastErrno;
34365 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34366 return SQLITE_OK;
34368 case SQLITE_FCNTL_CHUNK_SIZE: {
34369 pFile->szChunk = *(int *)pArg;
34370 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34371 return SQLITE_OK;
34373 case SQLITE_FCNTL_SIZE_HINT: {
34374 if( pFile->szChunk>0 ){
34375 sqlite3_int64 oldSz;
34376 int rc = winFileSize(id, &oldSz);
34377 if( rc==SQLITE_OK ){
34378 sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
34379 if( newSz>oldSz ){
34380 SimulateIOErrorBenign(1);
34381 rc = winTruncate(id, newSz);
34382 SimulateIOErrorBenign(0);
34385 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34386 return rc;
34388 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34389 return SQLITE_OK;
34391 case SQLITE_FCNTL_PERSIST_WAL: {
34392 winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
34393 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34394 return SQLITE_OK;
34396 case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34397 winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
34398 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34399 return SQLITE_OK;
34401 case SQLITE_FCNTL_VFSNAME: {
34402 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
34403 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34404 return SQLITE_OK;
34406 case SQLITE_FCNTL_WIN32_AV_RETRY: {
34407 int *a = (int*)pArg;
34408 if( a[0]>0 ){
34409 winIoerrRetry = a[0];
34410 }else{
34411 a[0] = winIoerrRetry;
34413 if( a[1]>0 ){
34414 winIoerrRetryDelay = a[1];
34415 }else{
34416 a[1] = winIoerrRetryDelay;
34418 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
34419 return SQLITE_OK;
34421 case SQLITE_FCNTL_TEMPFILENAME: {
34422 char *zTFile = 0;
34423 int rc = winGetTempname(pFile->pVfs, &zTFile);
34424 if( rc==SQLITE_OK ){
34425 *(char**)pArg = zTFile;
34427 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34428 return rc;
34430 #if SQLITE_MAX_MMAP_SIZE>0
34431 case SQLITE_FCNTL_MMAP_SIZE: {
34432 i64 newLimit = *(i64*)pArg;
34433 int rc = SQLITE_OK;
34434 if( newLimit>sqlite3GlobalConfig.mxMmap ){
34435 newLimit = sqlite3GlobalConfig.mxMmap;
34437 *(i64*)pArg = pFile->mmapSizeMax;
34438 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
34439 pFile->mmapSizeMax = newLimit;
34440 if( pFile->mmapSize>0 ){
34441 winUnmapfile(pFile);
34442 rc = winMapfile(pFile, -1);
34445 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
34446 return rc;
34448 #endif
34450 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
34451 return SQLITE_NOTFOUND;
34455 ** Return the sector size in bytes of the underlying block device for
34456 ** the specified file. This is almost always 512 bytes, but may be
34457 ** larger for some devices.
34459 ** SQLite code assumes this function cannot fail. It also assumes that
34460 ** if two files are created in the same file-system directory (i.e.
34461 ** a database and its journal file) that the sector size will be the
34462 ** same for both.
34464 static int winSectorSize(sqlite3_file *id){
34465 (void)id;
34466 return SQLITE_DEFAULT_SECTOR_SIZE;
34470 ** Return a vector of device characteristics.
34472 static int winDeviceCharacteristics(sqlite3_file *id){
34473 winFile *p = (winFile*)id;
34474 return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
34475 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
34479 ** Windows will only let you create file view mappings
34480 ** on allocation size granularity boundaries.
34481 ** During sqlite3_os_init() we do a GetSystemInfo()
34482 ** to get the granularity size.
34484 SYSTEM_INFO winSysInfo;
34486 #ifndef SQLITE_OMIT_WAL
34489 ** Helper functions to obtain and relinquish the global mutex. The
34490 ** global mutex is used to protect the winLockInfo objects used by
34491 ** this file, all of which may be shared by multiple threads.
34493 ** Function winShmMutexHeld() is used to assert() that the global mutex
34494 ** is held when required. This function is only used as part of assert()
34495 ** statements. e.g.
34497 ** winShmEnterMutex()
34498 ** assert( winShmMutexHeld() );
34499 ** winShmLeaveMutex()
34501 static void winShmEnterMutex(void){
34502 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34504 static void winShmLeaveMutex(void){
34505 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34507 #ifndef NDEBUG
34508 static int winShmMutexHeld(void) {
34509 return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34511 #endif
34514 ** Object used to represent a single file opened and mmapped to provide
34515 ** shared memory. When multiple threads all reference the same
34516 ** log-summary, each thread has its own winFile object, but they all
34517 ** point to a single instance of this object. In other words, each
34518 ** log-summary is opened only once per process.
34520 ** winShmMutexHeld() must be true when creating or destroying
34521 ** this object or while reading or writing the following fields:
34523 ** nRef
34524 ** pNext
34526 ** The following fields are read-only after the object is created:
34528 ** fid
34529 ** zFilename
34531 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
34532 ** winShmMutexHeld() is true when reading or writing any other field
34533 ** in this structure.
34536 struct winShmNode {
34537 sqlite3_mutex *mutex; /* Mutex to access this object */
34538 char *zFilename; /* Name of the file */
34539 winFile hFile; /* File handle from winOpen */
34541 int szRegion; /* Size of shared-memory regions */
34542 int nRegion; /* Size of array apRegion */
34543 struct ShmRegion {
34544 HANDLE hMap; /* File handle from CreateFileMapping */
34545 void *pMap;
34546 } *aRegion;
34547 DWORD lastErrno; /* The Windows errno from the last I/O error */
34549 int nRef; /* Number of winShm objects pointing to this */
34550 winShm *pFirst; /* All winShm objects pointing to this */
34551 winShmNode *pNext; /* Next in list of all winShmNode objects */
34552 #ifdef SQLITE_DEBUG
34553 u8 nextShmId; /* Next available winShm.id value */
34554 #endif
34558 ** A global array of all winShmNode objects.
34560 ** The winShmMutexHeld() must be true while reading or writing this list.
34562 static winShmNode *winShmNodeList = 0;
34565 ** Structure used internally by this VFS to record the state of an
34566 ** open shared memory connection.
34568 ** The following fields are initialized when this object is created and
34569 ** are read-only thereafter:
34571 ** winShm.pShmNode
34572 ** winShm.id
34574 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
34575 ** while accessing any read/write fields.
34577 struct winShm {
34578 winShmNode *pShmNode; /* The underlying winShmNode object */
34579 winShm *pNext; /* Next winShm with the same winShmNode */
34580 u8 hasMutex; /* True if holding the winShmNode mutex */
34581 u16 sharedMask; /* Mask of shared locks held */
34582 u16 exclMask; /* Mask of exclusive locks held */
34583 #ifdef SQLITE_DEBUG
34584 u8 id; /* Id of this connection with its winShmNode */
34585 #endif
34589 ** Constants used for locking
34591 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
34592 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
34595 ** Apply advisory locks for all n bytes beginning at ofst.
34597 #define _SHM_UNLCK 1
34598 #define _SHM_RDLCK 2
34599 #define _SHM_WRLCK 3
34600 static int winShmSystemLock(
34601 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
34602 int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
34603 int ofst, /* Offset to first byte to be locked/unlocked */
34604 int nByte /* Number of bytes to lock or unlock */
34606 int rc = 0; /* Result code form Lock/UnlockFileEx() */
34608 /* Access to the winShmNode object is serialized by the caller */
34609 assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
34611 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
34612 pFile->hFile.h, lockType, ofst, nByte));
34614 /* Release/Acquire the system-level lock */
34615 if( lockType==_SHM_UNLCK ){
34616 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
34617 }else{
34618 /* Initialize the locking parameters */
34619 DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
34620 if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
34621 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
34624 if( rc!= 0 ){
34625 rc = SQLITE_OK;
34626 }else{
34627 pFile->lastErrno = osGetLastError();
34628 rc = SQLITE_BUSY;
34631 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
34632 pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
34633 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
34635 return rc;
34638 /* Forward references to VFS methods */
34639 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
34640 static int winDelete(sqlite3_vfs *,const char*,int);
34643 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
34645 ** This is not a VFS shared-memory method; it is a utility function called
34646 ** by VFS shared-memory methods.
34648 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
34649 winShmNode **pp;
34650 winShmNode *p;
34651 assert( winShmMutexHeld() );
34652 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
34653 osGetCurrentProcessId(), deleteFlag));
34654 pp = &winShmNodeList;
34655 while( (p = *pp)!=0 ){
34656 if( p->nRef==0 ){
34657 int i;
34658 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
34659 for(i=0; i<p->nRegion; i++){
34660 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
34661 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
34662 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
34663 UNUSED_VARIABLE_VALUE(bRc);
34664 bRc = osCloseHandle(p->aRegion[i].hMap);
34665 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
34666 osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
34667 UNUSED_VARIABLE_VALUE(bRc);
34669 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
34670 SimulateIOErrorBenign(1);
34671 winClose((sqlite3_file *)&p->hFile);
34672 SimulateIOErrorBenign(0);
34674 if( deleteFlag ){
34675 SimulateIOErrorBenign(1);
34676 sqlite3BeginBenignMalloc();
34677 winDelete(pVfs, p->zFilename, 0);
34678 sqlite3EndBenignMalloc();
34679 SimulateIOErrorBenign(0);
34681 *pp = p->pNext;
34682 sqlite3_free(p->aRegion);
34683 sqlite3_free(p);
34684 }else{
34685 pp = &p->pNext;
34691 ** Open the shared-memory area associated with database file pDbFd.
34693 ** When opening a new shared-memory file, if no other instances of that
34694 ** file are currently open, in this process or in other processes, then
34695 ** the file must be truncated to zero length or have its header cleared.
34697 static int winOpenSharedMemory(winFile *pDbFd){
34698 struct winShm *p; /* The connection to be opened */
34699 struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
34700 int rc; /* Result code */
34701 struct winShmNode *pNew; /* Newly allocated winShmNode */
34702 int nName; /* Size of zName in bytes */
34704 assert( pDbFd->pShm==0 ); /* Not previously opened */
34706 /* Allocate space for the new sqlite3_shm object. Also speculatively
34707 ** allocate space for a new winShmNode and filename.
34709 p = sqlite3MallocZero( sizeof(*p) );
34710 if( p==0 ) return SQLITE_IOERR_NOMEM;
34711 nName = sqlite3Strlen30(pDbFd->zPath);
34712 pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
34713 if( pNew==0 ){
34714 sqlite3_free(p);
34715 return SQLITE_IOERR_NOMEM;
34717 pNew->zFilename = (char*)&pNew[1];
34718 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
34719 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
34721 /* Look to see if there is an existing winShmNode that can be used.
34722 ** If no matching winShmNode currently exists, create a new one.
34724 winShmEnterMutex();
34725 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
34726 /* TBD need to come up with better match here. Perhaps
34727 ** use FILE_ID_BOTH_DIR_INFO Structure.
34729 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
34731 if( pShmNode ){
34732 sqlite3_free(pNew);
34733 }else{
34734 pShmNode = pNew;
34735 pNew = 0;
34736 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
34737 pShmNode->pNext = winShmNodeList;
34738 winShmNodeList = pShmNode;
34740 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34741 if( pShmNode->mutex==0 ){
34742 rc = SQLITE_IOERR_NOMEM;
34743 goto shm_open_err;
34746 rc = winOpen(pDbFd->pVfs,
34747 pShmNode->zFilename, /* Name of the file (UTF-8) */
34748 (sqlite3_file*)&pShmNode->hFile, /* File handle here */
34749 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
34751 if( SQLITE_OK!=rc ){
34752 goto shm_open_err;
34755 /* Check to see if another process is holding the dead-man switch.
34756 ** If not, truncate the file to zero length.
34758 if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
34759 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
34760 if( rc!=SQLITE_OK ){
34761 rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
34762 "winOpenShm", pDbFd->zPath);
34765 if( rc==SQLITE_OK ){
34766 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34767 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
34769 if( rc ) goto shm_open_err;
34772 /* Make the new connection a child of the winShmNode */
34773 p->pShmNode = pShmNode;
34774 #ifdef SQLITE_DEBUG
34775 p->id = pShmNode->nextShmId++;
34776 #endif
34777 pShmNode->nRef++;
34778 pDbFd->pShm = p;
34779 winShmLeaveMutex();
34781 /* The reference count on pShmNode has already been incremented under
34782 ** the cover of the winShmEnterMutex() mutex and the pointer from the
34783 ** new (struct winShm) object to the pShmNode has been set. All that is
34784 ** left to do is to link the new object into the linked list starting
34785 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
34786 ** mutex.
34788 sqlite3_mutex_enter(pShmNode->mutex);
34789 p->pNext = pShmNode->pFirst;
34790 pShmNode->pFirst = p;
34791 sqlite3_mutex_leave(pShmNode->mutex);
34792 return SQLITE_OK;
34794 /* Jump here on any error */
34795 shm_open_err:
34796 winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34797 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
34798 sqlite3_free(p);
34799 sqlite3_free(pNew);
34800 winShmLeaveMutex();
34801 return rc;
34805 ** Close a connection to shared-memory. Delete the underlying
34806 ** storage if deleteFlag is true.
34808 static int winShmUnmap(
34809 sqlite3_file *fd, /* Database holding shared memory */
34810 int deleteFlag /* Delete after closing if true */
34812 winFile *pDbFd; /* Database holding shared-memory */
34813 winShm *p; /* The connection to be closed */
34814 winShmNode *pShmNode; /* The underlying shared-memory file */
34815 winShm **pp; /* For looping over sibling connections */
34817 pDbFd = (winFile*)fd;
34818 p = pDbFd->pShm;
34819 if( p==0 ) return SQLITE_OK;
34820 pShmNode = p->pShmNode;
34822 /* Remove connection p from the set of connections associated
34823 ** with pShmNode */
34824 sqlite3_mutex_enter(pShmNode->mutex);
34825 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34826 *pp = p->pNext;
34828 /* Free the connection p */
34829 sqlite3_free(p);
34830 pDbFd->pShm = 0;
34831 sqlite3_mutex_leave(pShmNode->mutex);
34833 /* If pShmNode->nRef has reached 0, then close the underlying
34834 ** shared-memory file, too */
34835 winShmEnterMutex();
34836 assert( pShmNode->nRef>0 );
34837 pShmNode->nRef--;
34838 if( pShmNode->nRef==0 ){
34839 winShmPurge(pDbFd->pVfs, deleteFlag);
34841 winShmLeaveMutex();
34843 return SQLITE_OK;
34847 ** Change the lock state for a shared-memory segment.
34849 static int winShmLock(
34850 sqlite3_file *fd, /* Database file holding the shared memory */
34851 int ofst, /* First lock to acquire or release */
34852 int n, /* Number of locks to acquire or release */
34853 int flags /* What to do with the lock */
34855 winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
34856 winShm *p = pDbFd->pShm; /* The shared memory being locked */
34857 winShm *pX; /* For looping over all siblings */
34858 winShmNode *pShmNode = p->pShmNode;
34859 int rc = SQLITE_OK; /* Result code */
34860 u16 mask; /* Mask of locks to take or release */
34862 assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34863 assert( n>=1 );
34864 assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34865 || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34866 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34867 || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34868 assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34870 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34871 assert( n>1 || mask==(1<<ofst) );
34872 sqlite3_mutex_enter(pShmNode->mutex);
34873 if( flags & SQLITE_SHM_UNLOCK ){
34874 u16 allMask = 0; /* Mask of locks held by siblings */
34876 /* See if any siblings hold this same lock */
34877 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34878 if( pX==p ) continue;
34879 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34880 allMask |= pX->sharedMask;
34883 /* Unlock the system-level locks */
34884 if( (mask & allMask)==0 ){
34885 rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34886 }else{
34887 rc = SQLITE_OK;
34890 /* Undo the local locks */
34891 if( rc==SQLITE_OK ){
34892 p->exclMask &= ~mask;
34893 p->sharedMask &= ~mask;
34895 }else if( flags & SQLITE_SHM_SHARED ){
34896 u16 allShared = 0; /* Union of locks held by connections other than "p" */
34898 /* Find out which shared locks are already held by sibling connections.
34899 ** If any sibling already holds an exclusive lock, go ahead and return
34900 ** SQLITE_BUSY.
34902 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34903 if( (pX->exclMask & mask)!=0 ){
34904 rc = SQLITE_BUSY;
34905 break;
34907 allShared |= pX->sharedMask;
34910 /* Get shared locks at the system level, if necessary */
34911 if( rc==SQLITE_OK ){
34912 if( (allShared & mask)==0 ){
34913 rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34914 }else{
34915 rc = SQLITE_OK;
34919 /* Get the local shared locks */
34920 if( rc==SQLITE_OK ){
34921 p->sharedMask |= mask;
34923 }else{
34924 /* Make sure no sibling connections hold locks that will block this
34925 ** lock. If any do, return SQLITE_BUSY right away.
34927 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34928 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34929 rc = SQLITE_BUSY;
34930 break;
34934 /* Get the exclusive locks at the system level. Then if successful
34935 ** also mark the local connection as being locked.
34937 if( rc==SQLITE_OK ){
34938 rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34939 if( rc==SQLITE_OK ){
34940 assert( (p->sharedMask & mask)==0 );
34941 p->exclMask |= mask;
34945 sqlite3_mutex_leave(pShmNode->mutex);
34946 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
34947 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
34948 sqlite3ErrName(rc)));
34949 return rc;
34953 ** Implement a memory barrier or memory fence on shared memory.
34955 ** All loads and stores begun before the barrier must complete before
34956 ** any load or store begun after the barrier.
34958 static void winShmBarrier(
34959 sqlite3_file *fd /* Database holding the shared memory */
34961 UNUSED_PARAMETER(fd);
34962 /* MemoryBarrier(); // does not work -- do not know why not */
34963 winShmEnterMutex();
34964 winShmLeaveMutex();
34968 ** This function is called to obtain a pointer to region iRegion of the
34969 ** shared-memory associated with the database file fd. Shared-memory regions
34970 ** are numbered starting from zero. Each shared-memory region is szRegion
34971 ** bytes in size.
34973 ** If an error occurs, an error code is returned and *pp is set to NULL.
34975 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34976 ** region has not been allocated (by any client, including one running in a
34977 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34978 ** isWrite is non-zero and the requested shared-memory region has not yet
34979 ** been allocated, it is allocated by this function.
34981 ** If the shared-memory region has already been allocated or is allocated by
34982 ** this call as described above, then it is mapped into this processes
34983 ** address space (if it is not already), *pp is set to point to the mapped
34984 ** memory and SQLITE_OK returned.
34986 static int winShmMap(
34987 sqlite3_file *fd, /* Handle open on database file */
34988 int iRegion, /* Region to retrieve */
34989 int szRegion, /* Size of regions */
34990 int isWrite, /* True to extend file if necessary */
34991 void volatile **pp /* OUT: Mapped memory */
34993 winFile *pDbFd = (winFile*)fd;
34994 winShm *p = pDbFd->pShm;
34995 winShmNode *pShmNode;
34996 int rc = SQLITE_OK;
34998 if( !p ){
34999 rc = winOpenSharedMemory(pDbFd);
35000 if( rc!=SQLITE_OK ) return rc;
35001 p = pDbFd->pShm;
35003 pShmNode = p->pShmNode;
35005 sqlite3_mutex_enter(pShmNode->mutex);
35006 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
35008 if( pShmNode->nRegion<=iRegion ){
35009 struct ShmRegion *apNew; /* New aRegion[] array */
35010 int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
35011 sqlite3_int64 sz; /* Current size of wal-index file */
35013 pShmNode->szRegion = szRegion;
35015 /* The requested region is not mapped into this processes address space.
35016 ** Check to see if it has been allocated (i.e. if the wal-index file is
35017 ** large enough to contain the requested region).
35019 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
35020 if( rc!=SQLITE_OK ){
35021 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35022 "winShmMap1", pDbFd->zPath);
35023 goto shmpage_out;
35026 if( sz<nByte ){
35027 /* The requested memory region does not exist. If isWrite is set to
35028 ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
35030 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
35031 ** the requested memory region.
35033 if( !isWrite ) goto shmpage_out;
35034 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
35035 if( rc!=SQLITE_OK ){
35036 rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
35037 "winShmMap2", pDbFd->zPath);
35038 goto shmpage_out;
35042 /* Map the requested memory region into this processes address space. */
35043 apNew = (struct ShmRegion *)sqlite3_realloc(
35044 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
35046 if( !apNew ){
35047 rc = SQLITE_IOERR_NOMEM;
35048 goto shmpage_out;
35050 pShmNode->aRegion = apNew;
35052 while( pShmNode->nRegion<=iRegion ){
35053 HANDLE hMap = NULL; /* file-mapping handle */
35054 void *pMap = 0; /* Mapped memory region */
35056 #if SQLITE_OS_WINRT
35057 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
35058 NULL, PAGE_READWRITE, nByte, NULL
35060 #elif defined(SQLITE_WIN32_HAS_WIDE)
35061 hMap = osCreateFileMappingW(pShmNode->hFile.h,
35062 NULL, PAGE_READWRITE, 0, nByte, NULL
35064 #elif defined(SQLITE_WIN32_HAS_ANSI)
35065 hMap = osCreateFileMappingA(pShmNode->hFile.h,
35066 NULL, PAGE_READWRITE, 0, nByte, NULL
35068 #endif
35069 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
35070 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
35071 hMap ? "ok" : "failed"));
35072 if( hMap ){
35073 int iOffset = pShmNode->nRegion*szRegion;
35074 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35075 #if SQLITE_OS_WINRT
35076 pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35077 iOffset - iOffsetShift, szRegion + iOffsetShift
35079 #else
35080 pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
35081 0, iOffset - iOffsetShift, szRegion + iOffsetShift
35083 #endif
35084 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
35085 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
35086 szRegion, pMap ? "ok" : "failed"));
35088 if( !pMap ){
35089 pShmNode->lastErrno = osGetLastError();
35090 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
35091 "winShmMap3", pDbFd->zPath);
35092 if( hMap ) osCloseHandle(hMap);
35093 goto shmpage_out;
35096 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
35097 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
35098 pShmNode->nRegion++;
35102 shmpage_out:
35103 if( pShmNode->nRegion>iRegion ){
35104 int iOffset = iRegion*szRegion;
35105 int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
35106 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
35107 *pp = (void *)&p[iOffsetShift];
35108 }else{
35109 *pp = 0;
35111 sqlite3_mutex_leave(pShmNode->mutex);
35112 return rc;
35115 #else
35116 # define winShmMap 0
35117 # define winShmLock 0
35118 # define winShmBarrier 0
35119 # define winShmUnmap 0
35120 #endif /* #ifndef SQLITE_OMIT_WAL */
35123 ** Cleans up the mapped region of the specified file, if any.
35125 #if SQLITE_MAX_MMAP_SIZE>0
35126 static int winUnmapfile(winFile *pFile){
35127 assert( pFile!=0 );
35128 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
35129 "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
35130 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
35131 pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
35132 if( pFile->pMapRegion ){
35133 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
35134 pFile->lastErrno = osGetLastError();
35135 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
35136 "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
35137 pFile->pMapRegion));
35138 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
35139 "winUnmapfile1", pFile->zPath);
35141 pFile->pMapRegion = 0;
35142 pFile->mmapSize = 0;
35143 pFile->mmapSizeActual = 0;
35145 if( pFile->hMap!=NULL ){
35146 if( !osCloseHandle(pFile->hMap) ){
35147 pFile->lastErrno = osGetLastError();
35148 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
35149 osGetCurrentProcessId(), pFile, pFile->hMap));
35150 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
35151 "winUnmapfile2", pFile->zPath);
35153 pFile->hMap = NULL;
35155 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35156 osGetCurrentProcessId(), pFile));
35157 return SQLITE_OK;
35161 ** Memory map or remap the file opened by file-descriptor pFd (if the file
35162 ** is already mapped, the existing mapping is replaced by the new). Or, if
35163 ** there already exists a mapping for this file, and there are still
35164 ** outstanding xFetch() references to it, this function is a no-op.
35166 ** If parameter nByte is non-negative, then it is the requested size of
35167 ** the mapping to create. Otherwise, if nByte is less than zero, then the
35168 ** requested size is the size of the file on disk. The actual size of the
35169 ** created mapping is either the requested size or the value configured
35170 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
35172 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
35173 ** recreated as a result of outstanding references) or an SQLite error
35174 ** code otherwise.
35176 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
35177 sqlite3_int64 nMap = nByte;
35178 int rc;
35180 assert( nMap>=0 || pFd->nFetchOut==0 );
35181 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
35182 osGetCurrentProcessId(), pFd, nByte));
35184 if( pFd->nFetchOut>0 ) return SQLITE_OK;
35186 if( nMap<0 ){
35187 rc = winFileSize((sqlite3_file*)pFd, &nMap);
35188 if( rc ){
35189 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
35190 osGetCurrentProcessId(), pFd));
35191 return SQLITE_IOERR_FSTAT;
35194 if( nMap>pFd->mmapSizeMax ){
35195 nMap = pFd->mmapSizeMax;
35197 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
35199 if( nMap==0 && pFd->mmapSize>0 ){
35200 winUnmapfile(pFd);
35202 if( nMap!=pFd->mmapSize ){
35203 void *pNew = 0;
35204 DWORD protect = PAGE_READONLY;
35205 DWORD flags = FILE_MAP_READ;
35207 winUnmapfile(pFd);
35208 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
35209 protect = PAGE_READWRITE;
35210 flags |= FILE_MAP_WRITE;
35212 #if SQLITE_OS_WINRT
35213 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
35214 #elif defined(SQLITE_WIN32_HAS_WIDE)
35215 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
35216 (DWORD)((nMap>>32) & 0xffffffff),
35217 (DWORD)(nMap & 0xffffffff), NULL);
35218 #elif defined(SQLITE_WIN32_HAS_ANSI)
35219 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
35220 (DWORD)((nMap>>32) & 0xffffffff),
35221 (DWORD)(nMap & 0xffffffff), NULL);
35222 #endif
35223 if( pFd->hMap==NULL ){
35224 pFd->lastErrno = osGetLastError();
35225 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
35226 "winMapfile1", pFd->zPath);
35227 /* Log the error, but continue normal operation using xRead/xWrite */
35228 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
35229 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
35230 return SQLITE_OK;
35232 assert( (nMap % winSysInfo.dwPageSize)==0 );
35233 assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
35234 #if SQLITE_OS_WINRT
35235 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
35236 #else
35237 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
35238 #endif
35239 if( pNew==NULL ){
35240 osCloseHandle(pFd->hMap);
35241 pFd->hMap = NULL;
35242 pFd->lastErrno = osGetLastError();
35243 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
35244 "winMapfile2", pFd->zPath);
35245 /* Log the error, but continue normal operation using xRead/xWrite */
35246 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
35247 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
35248 return SQLITE_OK;
35250 pFd->pMapRegion = pNew;
35251 pFd->mmapSize = nMap;
35252 pFd->mmapSizeActual = nMap;
35255 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35256 osGetCurrentProcessId(), pFd));
35257 return SQLITE_OK;
35259 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
35262 ** If possible, return a pointer to a mapping of file fd starting at offset
35263 ** iOff. The mapping must be valid for at least nAmt bytes.
35265 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
35266 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
35267 ** Finally, if an error does occur, return an SQLite error code. The final
35268 ** value of *pp is undefined in this case.
35270 ** If this function does return a pointer, the caller must eventually
35271 ** release the reference by calling winUnfetch().
35273 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
35274 #if SQLITE_MAX_MMAP_SIZE>0
35275 winFile *pFd = (winFile*)fd; /* The underlying database file */
35276 #endif
35277 *pp = 0;
35279 OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
35280 osGetCurrentProcessId(), fd, iOff, nAmt, pp));
35282 #if SQLITE_MAX_MMAP_SIZE>0
35283 if( pFd->mmapSizeMax>0 ){
35284 if( pFd->pMapRegion==0 ){
35285 int rc = winMapfile(pFd, -1);
35286 if( rc!=SQLITE_OK ){
35287 OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
35288 osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
35289 return rc;
35292 if( pFd->mmapSize >= iOff+nAmt ){
35293 *pp = &((u8 *)pFd->pMapRegion)[iOff];
35294 pFd->nFetchOut++;
35297 #endif
35299 OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
35300 osGetCurrentProcessId(), fd, pp, *pp));
35301 return SQLITE_OK;
35305 ** If the third argument is non-NULL, then this function releases a
35306 ** reference obtained by an earlier call to winFetch(). The second
35307 ** argument passed to this function must be the same as the corresponding
35308 ** argument that was passed to the winFetch() invocation.
35310 ** Or, if the third argument is NULL, then this function is being called
35311 ** to inform the VFS layer that, according to POSIX, any existing mapping
35312 ** may now be invalid and should be unmapped.
35314 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
35315 #if SQLITE_MAX_MMAP_SIZE>0
35316 winFile *pFd = (winFile*)fd; /* The underlying database file */
35318 /* If p==0 (unmap the entire file) then there must be no outstanding
35319 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
35320 ** then there must be at least one outstanding. */
35321 assert( (p==0)==(pFd->nFetchOut==0) );
35323 /* If p!=0, it must match the iOff value. */
35324 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
35326 OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
35327 osGetCurrentProcessId(), pFd, iOff, p));
35329 if( p ){
35330 pFd->nFetchOut--;
35331 }else{
35332 /* FIXME: If Windows truly always prevents truncating or deleting a
35333 ** file while a mapping is held, then the following winUnmapfile() call
35334 ** is unnecessary can can be omitted - potentially improving
35335 ** performance. */
35336 winUnmapfile(pFd);
35339 assert( pFd->nFetchOut>=0 );
35340 #endif
35342 OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
35343 osGetCurrentProcessId(), fd));
35344 return SQLITE_OK;
35348 ** Here ends the implementation of all sqlite3_file methods.
35350 ********************** End sqlite3_file Methods *******************************
35351 ******************************************************************************/
35354 ** This vector defines all the methods that can operate on an
35355 ** sqlite3_file for win32.
35357 static const sqlite3_io_methods winIoMethod = {
35358 3, /* iVersion */
35359 winClose, /* xClose */
35360 winRead, /* xRead */
35361 winWrite, /* xWrite */
35362 winTruncate, /* xTruncate */
35363 winSync, /* xSync */
35364 winFileSize, /* xFileSize */
35365 winLock, /* xLock */
35366 winUnlock, /* xUnlock */
35367 winCheckReservedLock, /* xCheckReservedLock */
35368 winFileControl, /* xFileControl */
35369 winSectorSize, /* xSectorSize */
35370 winDeviceCharacteristics, /* xDeviceCharacteristics */
35371 winShmMap, /* xShmMap */
35372 winShmLock, /* xShmLock */
35373 winShmBarrier, /* xShmBarrier */
35374 winShmUnmap, /* xShmUnmap */
35375 winFetch, /* xFetch */
35376 winUnfetch /* xUnfetch */
35379 /****************************************************************************
35380 **************************** sqlite3_vfs methods ****************************
35382 ** This division contains the implementation of methods on the
35383 ** sqlite3_vfs object.
35386 #if defined(__CYGWIN__)
35388 ** Convert a filename from whatever the underlying operating system
35389 ** supports for filenames into UTF-8. Space to hold the result is
35390 ** obtained from malloc and must be freed by the calling function.
35392 static char *winConvertToUtf8Filename(const void *zFilename){
35393 char *zConverted = 0;
35394 if( osIsNT() ){
35395 zConverted = winUnicodeToUtf8(zFilename);
35397 #ifdef SQLITE_WIN32_HAS_ANSI
35398 else{
35399 zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
35401 #endif
35402 /* caller will handle out of memory */
35403 return zConverted;
35405 #endif
35408 ** Convert a UTF-8 filename into whatever form the underlying
35409 ** operating system wants filenames in. Space to hold the result
35410 ** is obtained from malloc and must be freed by the calling
35411 ** function.
35413 static void *winConvertFromUtf8Filename(const char *zFilename){
35414 void *zConverted = 0;
35415 if( osIsNT() ){
35416 zConverted = winUtf8ToUnicode(zFilename);
35418 #ifdef SQLITE_WIN32_HAS_ANSI
35419 else{
35420 zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35422 #endif
35423 /* caller will handle out of memory */
35424 return zConverted;
35428 ** This function returns non-zero if the specified UTF-8 string buffer
35429 ** ends with a directory separator character or one was successfully
35430 ** added to it.
35432 static int winMakeEndInDirSep(int nBuf, char *zBuf){
35433 if( zBuf ){
35434 int nLen = sqlite3Strlen30(zBuf);
35435 if( nLen>0 ){
35436 if( winIsDirSep(zBuf[nLen-1]) ){
35437 return 1;
35438 }else if( nLen+1<nBuf ){
35439 zBuf[nLen] = winGetDirSep();
35440 zBuf[nLen+1] = '\0';
35441 return 1;
35445 return 0;
35449 ** Create a temporary file name and store the resulting pointer into pzBuf.
35450 ** The pointer returned in pzBuf must be freed via sqlite3_free().
35452 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
35453 static char zChars[] =
35454 "abcdefghijklmnopqrstuvwxyz"
35455 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35456 "0123456789";
35457 size_t i, j;
35458 int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
35459 int nMax, nBuf, nDir, nLen;
35460 char *zBuf;
35462 /* It's odd to simulate an io-error here, but really this is just
35463 ** using the io-error infrastructure to test that SQLite handles this
35464 ** function failing.
35466 SimulateIOError( return SQLITE_IOERR );
35468 /* Allocate a temporary buffer to store the fully qualified file
35469 ** name for the temporary file. If this fails, we cannot continue.
35471 nMax = pVfs->mxPathname; nBuf = nMax + 2;
35472 zBuf = sqlite3MallocZero( nBuf );
35473 if( !zBuf ){
35474 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35475 return SQLITE_IOERR_NOMEM;
35478 /* Figure out the effective temporary directory. First, check if one
35479 ** has been explicitly set by the application; otherwise, use the one
35480 ** configured by the operating system.
35482 nDir = nMax - (nPre + 15);
35483 assert( nDir>0 );
35484 if( sqlite3_temp_directory ){
35485 int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
35486 if( nDirLen>0 ){
35487 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
35488 nDirLen++;
35490 if( nDirLen>nDir ){
35491 sqlite3_free(zBuf);
35492 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35493 return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
35495 sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
35498 #if defined(__CYGWIN__)
35499 else{
35500 static const char *azDirs[] = {
35501 0, /* getenv("SQLITE_TMPDIR") */
35502 0, /* getenv("TMPDIR") */
35503 0, /* getenv("TMP") */
35504 0, /* getenv("TEMP") */
35505 0, /* getenv("USERPROFILE") */
35506 "/var/tmp",
35507 "/usr/tmp",
35508 "/tmp",
35509 ".",
35510 0 /* List terminator */
35512 unsigned int i;
35513 const char *zDir = 0;
35515 if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
35516 if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
35517 if( !azDirs[2] ) azDirs[2] = getenv("TMP");
35518 if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
35519 if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
35520 for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
35521 void *zConverted;
35522 if( zDir==0 ) continue;
35523 /* If the path starts with a drive letter followed by the colon
35524 ** character, assume it is already a native Win32 path; otherwise,
35525 ** it must be converted to a native Win32 path via the Cygwin API
35526 ** prior to using it.
35528 if( winIsDriveLetterAndColon(zDir) ){
35529 zConverted = winConvertFromUtf8Filename(zDir);
35530 if( !zConverted ){
35531 sqlite3_free(zBuf);
35532 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35533 return SQLITE_IOERR_NOMEM;
35535 if( winIsDir(zConverted) ){
35536 sqlite3_snprintf(nMax, zBuf, "%s", zDir);
35537 sqlite3_free(zConverted);
35538 break;
35540 sqlite3_free(zConverted);
35541 }else{
35542 zConverted = sqlite3MallocZero( nMax+1 );
35543 if( !zConverted ){
35544 sqlite3_free(zBuf);
35545 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35546 return SQLITE_IOERR_NOMEM;
35548 if( cygwin_conv_path(
35549 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
35550 zConverted, nMax+1)<0 ){
35551 sqlite3_free(zConverted);
35552 sqlite3_free(zBuf);
35553 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
35554 return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
35555 "winGetTempname2", zDir);
35557 if( winIsDir(zConverted) ){
35558 /* At this point, we know the candidate directory exists and should
35559 ** be used. However, we may need to convert the string containing
35560 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
35562 char *zUtf8 = winConvertToUtf8Filename(zConverted);
35563 if( !zUtf8 ){
35564 sqlite3_free(zConverted);
35565 sqlite3_free(zBuf);
35566 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35567 return SQLITE_IOERR_NOMEM;
35569 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
35570 sqlite3_free(zUtf8);
35571 sqlite3_free(zConverted);
35572 break;
35574 sqlite3_free(zConverted);
35578 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
35579 else if( osIsNT() ){
35580 char *zMulti;
35581 LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
35582 if( !zWidePath ){
35583 sqlite3_free(zBuf);
35584 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35585 return SQLITE_IOERR_NOMEM;
35587 if( osGetTempPathW(nMax, zWidePath)==0 ){
35588 sqlite3_free(zWidePath);
35589 sqlite3_free(zBuf);
35590 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
35591 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
35592 "winGetTempname2", 0);
35594 zMulti = winUnicodeToUtf8(zWidePath);
35595 if( zMulti ){
35596 sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
35597 sqlite3_free(zMulti);
35598 sqlite3_free(zWidePath);
35599 }else{
35600 sqlite3_free(zWidePath);
35601 sqlite3_free(zBuf);
35602 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35603 return SQLITE_IOERR_NOMEM;
35606 #ifdef SQLITE_WIN32_HAS_ANSI
35607 else{
35608 char *zUtf8;
35609 char *zMbcsPath = sqlite3MallocZero( nMax );
35610 if( !zMbcsPath ){
35611 sqlite3_free(zBuf);
35612 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35613 return SQLITE_IOERR_NOMEM;
35615 if( osGetTempPathA(nMax, zMbcsPath)==0 ){
35616 sqlite3_free(zBuf);
35617 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
35618 return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
35619 "winGetTempname3", 0);
35621 zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
35622 if( zUtf8 ){
35623 sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
35624 sqlite3_free(zUtf8);
35625 }else{
35626 sqlite3_free(zBuf);
35627 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
35628 return SQLITE_IOERR_NOMEM;
35631 #endif /* SQLITE_WIN32_HAS_ANSI */
35632 #endif /* !SQLITE_OS_WINRT */
35635 ** Check to make sure the temporary directory ends with an appropriate
35636 ** separator. If it does not and there is not enough space left to add
35637 ** one, fail.
35639 if( !winMakeEndInDirSep(nDir+1, zBuf) ){
35640 sqlite3_free(zBuf);
35641 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35642 return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
35646 ** Check that the output buffer is large enough for the temporary file
35647 ** name in the following format:
35649 ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
35651 ** If not, return SQLITE_ERROR. The number 17 is used here in order to
35652 ** account for the space used by the 15 character random suffix and the
35653 ** two trailing NUL characters. The final directory separator character
35654 ** has already added if it was not already present.
35656 nLen = sqlite3Strlen30(zBuf);
35657 if( (nLen + nPre + 17) > nBuf ){
35658 sqlite3_free(zBuf);
35659 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
35660 return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
35663 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
35665 j = sqlite3Strlen30(zBuf);
35666 sqlite3_randomness(15, &zBuf[j]);
35667 for(i=0; i<15; i++, j++){
35668 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
35670 zBuf[j] = 0;
35671 zBuf[j+1] = 0;
35672 *pzBuf = zBuf;
35674 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
35675 return SQLITE_OK;
35679 ** Return TRUE if the named file is really a directory. Return false if
35680 ** it is something other than a directory, or if there is any kind of memory
35681 ** allocation failure.
35683 static int winIsDir(const void *zConverted){
35684 DWORD attr;
35685 int rc = 0;
35686 DWORD lastErrno;
35688 if( osIsNT() ){
35689 int cnt = 0;
35690 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35691 memset(&sAttrData, 0, sizeof(sAttrData));
35692 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35693 GetFileExInfoStandard,
35694 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
35695 if( !rc ){
35696 return 0; /* Invalid name? */
35698 attr = sAttrData.dwFileAttributes;
35699 #if SQLITE_OS_WINCE==0
35700 }else{
35701 attr = osGetFileAttributesA((char*)zConverted);
35702 #endif
35704 return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
35708 ** Open a file.
35710 static int winOpen(
35711 sqlite3_vfs *pVfs, /* Used to get maximum path name length */
35712 const char *zName, /* Name of the file (UTF-8) */
35713 sqlite3_file *id, /* Write the SQLite file handle here */
35714 int flags, /* Open mode flags */
35715 int *pOutFlags /* Status return flags */
35717 HANDLE h;
35718 DWORD lastErrno = 0;
35719 DWORD dwDesiredAccess;
35720 DWORD dwShareMode;
35721 DWORD dwCreationDisposition;
35722 DWORD dwFlagsAndAttributes = 0;
35723 #if SQLITE_OS_WINCE
35724 int isTemp = 0;
35725 #endif
35726 winFile *pFile = (winFile*)id;
35727 void *zConverted; /* Filename in OS encoding */
35728 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
35729 int cnt = 0;
35731 /* If argument zPath is a NULL pointer, this function is required to open
35732 ** a temporary file. Use this buffer to store the file name in.
35734 char *zTmpname = 0; /* For temporary filename, if necessary. */
35736 int rc = SQLITE_OK; /* Function Return Code */
35737 #if !defined(NDEBUG) || SQLITE_OS_WINCE
35738 int eType = flags&0xFFFFFF00; /* Type of file to open */
35739 #endif
35741 int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
35742 int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
35743 int isCreate = (flags & SQLITE_OPEN_CREATE);
35744 int isReadonly = (flags & SQLITE_OPEN_READONLY);
35745 int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
35747 #ifndef NDEBUG
35748 int isOpenJournal = (isCreate && (
35749 eType==SQLITE_OPEN_MASTER_JOURNAL
35750 || eType==SQLITE_OPEN_MAIN_JOURNAL
35751 || eType==SQLITE_OPEN_WAL
35753 #endif
35755 OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
35756 zUtf8Name, id, flags, pOutFlags));
35758 /* Check the following statements are true:
35760 ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
35761 ** (b) if CREATE is set, then READWRITE must also be set, and
35762 ** (c) if EXCLUSIVE is set, then CREATE must also be set.
35763 ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
35765 assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35766 assert(isCreate==0 || isReadWrite);
35767 assert(isExclusive==0 || isCreate);
35768 assert(isDelete==0 || isCreate);
35770 /* The main DB, main journal, WAL file and master journal are never
35771 ** automatically deleted. Nor are they ever temporary files. */
35772 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35773 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35774 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35775 assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35777 /* Assert that the upper layer has set one of the "file-type" flags. */
35778 assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
35779 || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
35780 || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
35781 || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35784 assert( pFile!=0 );
35785 memset(pFile, 0, sizeof(winFile));
35786 pFile->h = INVALID_HANDLE_VALUE;
35788 #if SQLITE_OS_WINRT
35789 if( !zUtf8Name && !sqlite3_temp_directory ){
35790 sqlite3_log(SQLITE_ERROR,
35791 "sqlite3_temp_directory variable should be set for WinRT");
35793 #endif
35795 /* If the second argument to this function is NULL, generate a
35796 ** temporary file name to use
35798 if( !zUtf8Name ){
35799 assert( isDelete && !isOpenJournal );
35800 rc = winGetTempname(pVfs, &zTmpname);
35801 if( rc!=SQLITE_OK ){
35802 OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
35803 return rc;
35805 zUtf8Name = zTmpname;
35808 /* Database filenames are double-zero terminated if they are not
35809 ** URIs with parameters. Hence, they can always be passed into
35810 ** sqlite3_uri_parameter().
35812 assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
35813 zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
35815 /* Convert the filename to the system encoding. */
35816 zConverted = winConvertFromUtf8Filename(zUtf8Name);
35817 if( zConverted==0 ){
35818 sqlite3_free(zTmpname);
35819 OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
35820 return SQLITE_IOERR_NOMEM;
35823 if( winIsDir(zConverted) ){
35824 sqlite3_free(zConverted);
35825 sqlite3_free(zTmpname);
35826 OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
35827 return SQLITE_CANTOPEN_ISDIR;
35830 if( isReadWrite ){
35831 dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
35832 }else{
35833 dwDesiredAccess = GENERIC_READ;
35836 /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
35837 ** created. SQLite doesn't use it to indicate "exclusive access"
35838 ** as it is usually understood.
35840 if( isExclusive ){
35841 /* Creates a new file, only if it does not already exist. */
35842 /* If the file exists, it fails. */
35843 dwCreationDisposition = CREATE_NEW;
35844 }else if( isCreate ){
35845 /* Open existing file, or create if it doesn't exist */
35846 dwCreationDisposition = OPEN_ALWAYS;
35847 }else{
35848 /* Opens a file, only if it exists. */
35849 dwCreationDisposition = OPEN_EXISTING;
35852 dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
35854 if( isDelete ){
35855 #if SQLITE_OS_WINCE
35856 dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
35857 isTemp = 1;
35858 #else
35859 dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
35860 | FILE_ATTRIBUTE_HIDDEN
35861 | FILE_FLAG_DELETE_ON_CLOSE;
35862 #endif
35863 }else{
35864 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
35866 /* Reports from the internet are that performance is always
35867 ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
35868 #if SQLITE_OS_WINCE
35869 dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
35870 #endif
35872 if( osIsNT() ){
35873 #if SQLITE_OS_WINRT
35874 CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
35875 extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
35876 extendedParameters.dwFileAttributes =
35877 dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
35878 extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
35879 extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
35880 extendedParameters.lpSecurityAttributes = NULL;
35881 extendedParameters.hTemplateFile = NULL;
35882 while( (h = osCreateFile2((LPCWSTR)zConverted,
35883 dwDesiredAccess,
35884 dwShareMode,
35885 dwCreationDisposition,
35886 &extendedParameters))==INVALID_HANDLE_VALUE &&
35887 winRetryIoerr(&cnt, &lastErrno) ){
35888 /* Noop */
35890 #else
35891 while( (h = osCreateFileW((LPCWSTR)zConverted,
35892 dwDesiredAccess,
35893 dwShareMode, NULL,
35894 dwCreationDisposition,
35895 dwFlagsAndAttributes,
35896 NULL))==INVALID_HANDLE_VALUE &&
35897 winRetryIoerr(&cnt, &lastErrno) ){
35898 /* Noop */
35900 #endif
35902 #ifdef SQLITE_WIN32_HAS_ANSI
35903 else{
35904 while( (h = osCreateFileA((LPCSTR)zConverted,
35905 dwDesiredAccess,
35906 dwShareMode, NULL,
35907 dwCreationDisposition,
35908 dwFlagsAndAttributes,
35909 NULL))==INVALID_HANDLE_VALUE &&
35910 winRetryIoerr(&cnt, &lastErrno) ){
35911 /* Noop */
35914 #endif
35915 winLogIoerr(cnt);
35917 OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
35918 dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
35920 if( h==INVALID_HANDLE_VALUE ){
35921 pFile->lastErrno = lastErrno;
35922 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
35923 sqlite3_free(zConverted);
35924 sqlite3_free(zTmpname);
35925 if( isReadWrite && !isExclusive ){
35926 return winOpen(pVfs, zName, id,
35927 ((flags|SQLITE_OPEN_READONLY) &
35928 ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
35929 pOutFlags);
35930 }else{
35931 return SQLITE_CANTOPEN_BKPT;
35935 if( pOutFlags ){
35936 if( isReadWrite ){
35937 *pOutFlags = SQLITE_OPEN_READWRITE;
35938 }else{
35939 *pOutFlags = SQLITE_OPEN_READONLY;
35943 OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
35944 "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
35945 *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
35947 #if SQLITE_OS_WINCE
35948 if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
35949 && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
35951 osCloseHandle(h);
35952 sqlite3_free(zConverted);
35953 sqlite3_free(zTmpname);
35954 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
35955 return rc;
35957 if( isTemp ){
35958 pFile->zDeleteOnClose = zConverted;
35959 }else
35960 #endif
35962 sqlite3_free(zConverted);
35965 sqlite3_free(zTmpname);
35966 pFile->pMethod = &winIoMethod;
35967 pFile->pVfs = pVfs;
35968 pFile->h = h;
35969 if( isReadonly ){
35970 pFile->ctrlFlags |= WINFILE_RDONLY;
35972 if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35973 pFile->ctrlFlags |= WINFILE_PSOW;
35975 pFile->lastErrno = NO_ERROR;
35976 pFile->zPath = zName;
35977 #if SQLITE_MAX_MMAP_SIZE>0
35978 pFile->hMap = NULL;
35979 pFile->pMapRegion = 0;
35980 pFile->mmapSize = 0;
35981 pFile->mmapSizeActual = 0;
35982 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
35983 #endif
35985 OpenCounter(+1);
35986 return rc;
35990 ** Delete the named file.
35992 ** Note that Windows does not allow a file to be deleted if some other
35993 ** process has it open. Sometimes a virus scanner or indexing program
35994 ** will open a journal file shortly after it is created in order to do
35995 ** whatever it does. While this other process is holding the
35996 ** file open, we will be unable to delete it. To work around this
35997 ** problem, we delay 100 milliseconds and try to delete again. Up
35998 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
35999 ** up and returning an error.
36001 static int winDelete(
36002 sqlite3_vfs *pVfs, /* Not used on win32 */
36003 const char *zFilename, /* Name of file to delete */
36004 int syncDir /* Not used on win32 */
36006 int cnt = 0;
36007 int rc;
36008 DWORD attr;
36009 DWORD lastErrno = 0;
36010 void *zConverted;
36011 UNUSED_PARAMETER(pVfs);
36012 UNUSED_PARAMETER(syncDir);
36014 SimulateIOError(return SQLITE_IOERR_DELETE);
36015 OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
36017 zConverted = winConvertFromUtf8Filename(zFilename);
36018 if( zConverted==0 ){
36019 OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
36020 return SQLITE_IOERR_NOMEM;
36022 if( osIsNT() ){
36023 do {
36024 #if SQLITE_OS_WINRT
36025 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36026 memset(&sAttrData, 0, sizeof(sAttrData));
36027 if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
36028 &sAttrData) ){
36029 attr = sAttrData.dwFileAttributes;
36030 }else{
36031 lastErrno = osGetLastError();
36032 if( lastErrno==ERROR_FILE_NOT_FOUND
36033 || lastErrno==ERROR_PATH_NOT_FOUND ){
36034 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36035 }else{
36036 rc = SQLITE_ERROR;
36038 break;
36040 #else
36041 attr = osGetFileAttributesW(zConverted);
36042 #endif
36043 if ( attr==INVALID_FILE_ATTRIBUTES ){
36044 lastErrno = osGetLastError();
36045 if( lastErrno==ERROR_FILE_NOT_FOUND
36046 || lastErrno==ERROR_PATH_NOT_FOUND ){
36047 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36048 }else{
36049 rc = SQLITE_ERROR;
36051 break;
36053 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36054 rc = SQLITE_ERROR; /* Files only. */
36055 break;
36057 if ( osDeleteFileW(zConverted) ){
36058 rc = SQLITE_OK; /* Deleted OK. */
36059 break;
36061 if ( !winRetryIoerr(&cnt, &lastErrno) ){
36062 rc = SQLITE_ERROR; /* No more retries. */
36063 break;
36065 } while(1);
36067 #ifdef SQLITE_WIN32_HAS_ANSI
36068 else{
36069 do {
36070 attr = osGetFileAttributesA(zConverted);
36071 if ( attr==INVALID_FILE_ATTRIBUTES ){
36072 lastErrno = osGetLastError();
36073 if( lastErrno==ERROR_FILE_NOT_FOUND
36074 || lastErrno==ERROR_PATH_NOT_FOUND ){
36075 rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
36076 }else{
36077 rc = SQLITE_ERROR;
36079 break;
36081 if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
36082 rc = SQLITE_ERROR; /* Files only. */
36083 break;
36085 if ( osDeleteFileA(zConverted) ){
36086 rc = SQLITE_OK; /* Deleted OK. */
36087 break;
36089 if ( !winRetryIoerr(&cnt, &lastErrno) ){
36090 rc = SQLITE_ERROR; /* No more retries. */
36091 break;
36093 } while(1);
36095 #endif
36096 if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
36097 rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
36098 }else{
36099 winLogIoerr(cnt);
36101 sqlite3_free(zConverted);
36102 OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
36103 return rc;
36107 ** Check the existence and status of a file.
36109 static int winAccess(
36110 sqlite3_vfs *pVfs, /* Not used on win32 */
36111 const char *zFilename, /* Name of file to check */
36112 int flags, /* Type of test to make on this file */
36113 int *pResOut /* OUT: Result */
36115 DWORD attr;
36116 int rc = 0;
36117 DWORD lastErrno = 0;
36118 void *zConverted;
36119 UNUSED_PARAMETER(pVfs);
36121 SimulateIOError( return SQLITE_IOERR_ACCESS; );
36122 OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
36123 zFilename, flags, pResOut));
36125 zConverted = winConvertFromUtf8Filename(zFilename);
36126 if( zConverted==0 ){
36127 OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
36128 return SQLITE_IOERR_NOMEM;
36130 if( osIsNT() ){
36131 int cnt = 0;
36132 WIN32_FILE_ATTRIBUTE_DATA sAttrData;
36133 memset(&sAttrData, 0, sizeof(sAttrData));
36134 while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
36135 GetFileExInfoStandard,
36136 &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
36137 if( rc ){
36138 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
36139 ** as if it does not exist.
36141 if( flags==SQLITE_ACCESS_EXISTS
36142 && sAttrData.nFileSizeHigh==0
36143 && sAttrData.nFileSizeLow==0 ){
36144 attr = INVALID_FILE_ATTRIBUTES;
36145 }else{
36146 attr = sAttrData.dwFileAttributes;
36148 }else{
36149 winLogIoerr(cnt);
36150 if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
36151 sqlite3_free(zConverted);
36152 return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
36153 zFilename);
36154 }else{
36155 attr = INVALID_FILE_ATTRIBUTES;
36159 #ifdef SQLITE_WIN32_HAS_ANSI
36160 else{
36161 attr = osGetFileAttributesA((char*)zConverted);
36163 #endif
36164 sqlite3_free(zConverted);
36165 switch( flags ){
36166 case SQLITE_ACCESS_READ:
36167 case SQLITE_ACCESS_EXISTS:
36168 rc = attr!=INVALID_FILE_ATTRIBUTES;
36169 break;
36170 case SQLITE_ACCESS_READWRITE:
36171 rc = attr!=INVALID_FILE_ATTRIBUTES &&
36172 (attr & FILE_ATTRIBUTE_READONLY)==0;
36173 break;
36174 default:
36175 assert(!"Invalid flags argument");
36177 *pResOut = rc;
36178 OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
36179 zFilename, pResOut, *pResOut));
36180 return SQLITE_OK;
36184 ** Returns non-zero if the specified path name starts with a drive letter
36185 ** followed by a colon character.
36187 static BOOL winIsDriveLetterAndColon(
36188 const char *zPathname
36190 return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
36194 ** Returns non-zero if the specified path name should be used verbatim. If
36195 ** non-zero is returned from this function, the calling function must simply
36196 ** use the provided path name verbatim -OR- resolve it into a full path name
36197 ** using the GetFullPathName Win32 API function (if available).
36199 static BOOL winIsVerbatimPathname(
36200 const char *zPathname
36203 ** If the path name starts with a forward slash or a backslash, it is either
36204 ** a legal UNC name, a volume relative path, or an absolute path name in the
36205 ** "Unix" format on Windows. There is no easy way to differentiate between
36206 ** the final two cases; therefore, we return the safer return value of TRUE
36207 ** so that callers of this function will simply use it verbatim.
36209 if ( winIsDirSep(zPathname[0]) ){
36210 return TRUE;
36214 ** If the path name starts with a letter and a colon it is either a volume
36215 ** relative path or an absolute path. Callers of this function must not
36216 ** attempt to treat it as a relative path name (i.e. they should simply use
36217 ** it verbatim).
36219 if ( winIsDriveLetterAndColon(zPathname) ){
36220 return TRUE;
36224 ** If we get to this point, the path name should almost certainly be a purely
36225 ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
36227 return FALSE;
36231 ** Turn a relative pathname into a full pathname. Write the full
36232 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
36233 ** bytes in size.
36235 static int winFullPathname(
36236 sqlite3_vfs *pVfs, /* Pointer to vfs object */
36237 const char *zRelative, /* Possibly relative input path */
36238 int nFull, /* Size of output buffer in bytes */
36239 char *zFull /* Output buffer */
36242 #if defined(__CYGWIN__)
36243 SimulateIOError( return SQLITE_ERROR );
36244 UNUSED_PARAMETER(nFull);
36245 assert( nFull>=pVfs->mxPathname );
36246 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36248 ** NOTE: We are dealing with a relative path name and the data
36249 ** directory has been set. Therefore, use it as the basis
36250 ** for converting the relative path name to an absolute
36251 ** one by prepending the data directory and a slash.
36253 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
36254 if( !zOut ){
36255 return SQLITE_IOERR_NOMEM;
36257 if( cygwin_conv_path(
36258 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
36259 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
36260 sqlite3_free(zOut);
36261 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
36262 "winFullPathname1", zRelative);
36263 }else{
36264 char *zUtf8 = winConvertToUtf8Filename(zOut);
36265 if( !zUtf8 ){
36266 sqlite3_free(zOut);
36267 return SQLITE_IOERR_NOMEM;
36269 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36270 sqlite3_data_directory, winGetDirSep(), zUtf8);
36271 sqlite3_free(zUtf8);
36272 sqlite3_free(zOut);
36274 }else{
36275 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
36276 if( !zOut ){
36277 return SQLITE_IOERR_NOMEM;
36279 if( cygwin_conv_path(
36280 (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
36281 zRelative, zOut, pVfs->mxPathname+1)<0 ){
36282 sqlite3_free(zOut);
36283 return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
36284 "winFullPathname2", zRelative);
36285 }else{
36286 char *zUtf8 = winConvertToUtf8Filename(zOut);
36287 if( !zUtf8 ){
36288 sqlite3_free(zOut);
36289 return SQLITE_IOERR_NOMEM;
36291 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
36292 sqlite3_free(zUtf8);
36293 sqlite3_free(zOut);
36296 return SQLITE_OK;
36297 #endif
36299 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
36300 SimulateIOError( return SQLITE_ERROR );
36301 /* WinCE has no concept of a relative pathname, or so I am told. */
36302 /* WinRT has no way to convert a relative path to an absolute one. */
36303 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36305 ** NOTE: We are dealing with a relative path name and the data
36306 ** directory has been set. Therefore, use it as the basis
36307 ** for converting the relative path name to an absolute
36308 ** one by prepending the data directory and a backslash.
36310 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36311 sqlite3_data_directory, winGetDirSep(), zRelative);
36312 }else{
36313 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
36315 return SQLITE_OK;
36316 #endif
36318 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
36319 DWORD nByte;
36320 void *zConverted;
36321 char *zOut;
36323 /* If this path name begins with "/X:", where "X" is any alphabetic
36324 ** character, discard the initial "/" from the pathname.
36326 if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
36327 zRelative++;
36330 /* It's odd to simulate an io-error here, but really this is just
36331 ** using the io-error infrastructure to test that SQLite handles this
36332 ** function failing. This function could fail if, for example, the
36333 ** current working directory has been unlinked.
36335 SimulateIOError( return SQLITE_ERROR );
36336 if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
36338 ** NOTE: We are dealing with a relative path name and the data
36339 ** directory has been set. Therefore, use it as the basis
36340 ** for converting the relative path name to an absolute
36341 ** one by prepending the data directory and a backslash.
36343 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
36344 sqlite3_data_directory, winGetDirSep(), zRelative);
36345 return SQLITE_OK;
36347 zConverted = winConvertFromUtf8Filename(zRelative);
36348 if( zConverted==0 ){
36349 return SQLITE_IOERR_NOMEM;
36351 if( osIsNT() ){
36352 LPWSTR zTemp;
36353 nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
36354 if( nByte==0 ){
36355 sqlite3_free(zConverted);
36356 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36357 "winFullPathname1", zRelative);
36359 nByte += 3;
36360 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36361 if( zTemp==0 ){
36362 sqlite3_free(zConverted);
36363 return SQLITE_IOERR_NOMEM;
36365 nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
36366 if( nByte==0 ){
36367 sqlite3_free(zConverted);
36368 sqlite3_free(zTemp);
36369 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36370 "winFullPathname2", zRelative);
36372 sqlite3_free(zConverted);
36373 zOut = winUnicodeToUtf8(zTemp);
36374 sqlite3_free(zTemp);
36376 #ifdef SQLITE_WIN32_HAS_ANSI
36377 else{
36378 char *zTemp;
36379 nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
36380 if( nByte==0 ){
36381 sqlite3_free(zConverted);
36382 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36383 "winFullPathname3", zRelative);
36385 nByte += 3;
36386 zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
36387 if( zTemp==0 ){
36388 sqlite3_free(zConverted);
36389 return SQLITE_IOERR_NOMEM;
36391 nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
36392 if( nByte==0 ){
36393 sqlite3_free(zConverted);
36394 sqlite3_free(zTemp);
36395 return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
36396 "winFullPathname4", zRelative);
36398 sqlite3_free(zConverted);
36399 zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
36400 sqlite3_free(zTemp);
36402 #endif
36403 if( zOut ){
36404 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
36405 sqlite3_free(zOut);
36406 return SQLITE_OK;
36407 }else{
36408 return SQLITE_IOERR_NOMEM;
36410 #endif
36413 #ifndef SQLITE_OMIT_LOAD_EXTENSION
36415 ** Interfaces for opening a shared library, finding entry points
36416 ** within the shared library, and closing the shared library.
36419 ** Interfaces for opening a shared library, finding entry points
36420 ** within the shared library, and closing the shared library.
36422 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
36423 HANDLE h;
36424 void *zConverted = winConvertFromUtf8Filename(zFilename);
36425 UNUSED_PARAMETER(pVfs);
36426 if( zConverted==0 ){
36427 return 0;
36429 if( osIsNT() ){
36430 #if SQLITE_OS_WINRT
36431 h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
36432 #else
36433 h = osLoadLibraryW((LPCWSTR)zConverted);
36434 #endif
36436 #ifdef SQLITE_WIN32_HAS_ANSI
36437 else{
36438 h = osLoadLibraryA((char*)zConverted);
36440 #endif
36441 sqlite3_free(zConverted);
36442 return (void*)h;
36444 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
36445 UNUSED_PARAMETER(pVfs);
36446 winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
36448 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
36449 UNUSED_PARAMETER(pVfs);
36450 return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
36452 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
36453 UNUSED_PARAMETER(pVfs);
36454 osFreeLibrary((HANDLE)pHandle);
36456 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
36457 #define winDlOpen 0
36458 #define winDlError 0
36459 #define winDlSym 0
36460 #define winDlClose 0
36461 #endif
36465 ** Write up to nBuf bytes of randomness into zBuf.
36467 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36468 int n = 0;
36469 UNUSED_PARAMETER(pVfs);
36470 #if defined(SQLITE_TEST)
36471 n = nBuf;
36472 memset(zBuf, 0, nBuf);
36473 #else
36474 if( sizeof(SYSTEMTIME)<=nBuf-n ){
36475 SYSTEMTIME x;
36476 osGetSystemTime(&x);
36477 memcpy(&zBuf[n], &x, sizeof(x));
36478 n += sizeof(x);
36480 if( sizeof(DWORD)<=nBuf-n ){
36481 DWORD pid = osGetCurrentProcessId();
36482 memcpy(&zBuf[n], &pid, sizeof(pid));
36483 n += sizeof(pid);
36485 #if SQLITE_OS_WINRT
36486 if( sizeof(ULONGLONG)<=nBuf-n ){
36487 ULONGLONG cnt = osGetTickCount64();
36488 memcpy(&zBuf[n], &cnt, sizeof(cnt));
36489 n += sizeof(cnt);
36491 #else
36492 if( sizeof(DWORD)<=nBuf-n ){
36493 DWORD cnt = osGetTickCount();
36494 memcpy(&zBuf[n], &cnt, sizeof(cnt));
36495 n += sizeof(cnt);
36497 #endif
36498 if( sizeof(LARGE_INTEGER)<=nBuf-n ){
36499 LARGE_INTEGER i;
36500 osQueryPerformanceCounter(&i);
36501 memcpy(&zBuf[n], &i, sizeof(i));
36502 n += sizeof(i);
36504 #endif
36505 return n;
36510 ** Sleep for a little while. Return the amount of time slept.
36512 static int winSleep(sqlite3_vfs *pVfs, int microsec){
36513 sqlite3_win32_sleep((microsec+999)/1000);
36514 UNUSED_PARAMETER(pVfs);
36515 return ((microsec+999)/1000)*1000;
36519 ** The following variable, if set to a non-zero value, is interpreted as
36520 ** the number of seconds since 1970 and is used to set the result of
36521 ** sqlite3OsCurrentTime() during testing.
36523 #ifdef SQLITE_TEST
36524 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
36525 #endif
36528 ** Find the current time (in Universal Coordinated Time). Write into *piNow
36529 ** the current time and date as a Julian Day number times 86_400_000. In
36530 ** other words, write into *piNow the number of milliseconds since the Julian
36531 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
36532 ** proleptic Gregorian calendar.
36534 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
36535 ** cannot be found.
36537 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
36538 /* FILETIME structure is a 64-bit value representing the number of
36539 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
36541 FILETIME ft;
36542 static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
36543 #ifdef SQLITE_TEST
36544 static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
36545 #endif
36546 /* 2^32 - to avoid use of LL and warnings in gcc */
36547 static const sqlite3_int64 max32BitValue =
36548 (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
36549 (sqlite3_int64)294967296;
36551 #if SQLITE_OS_WINCE
36552 SYSTEMTIME time;
36553 osGetSystemTime(&time);
36554 /* if SystemTimeToFileTime() fails, it returns zero. */
36555 if (!osSystemTimeToFileTime(&time,&ft)){
36556 return SQLITE_ERROR;
36558 #else
36559 osGetSystemTimeAsFileTime( &ft );
36560 #endif
36562 *piNow = winFiletimeEpoch +
36563 ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
36564 (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
36566 #ifdef SQLITE_TEST
36567 if( sqlite3_current_time ){
36568 *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
36570 #endif
36571 UNUSED_PARAMETER(pVfs);
36572 return SQLITE_OK;
36576 ** Find the current time (in Universal Coordinated Time). Write the
36577 ** current time and date as a Julian Day number into *prNow and
36578 ** return 0. Return 1 if the time and date cannot be found.
36580 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
36581 int rc;
36582 sqlite3_int64 i;
36583 rc = winCurrentTimeInt64(pVfs, &i);
36584 if( !rc ){
36585 *prNow = i/86400000.0;
36587 return rc;
36591 ** The idea is that this function works like a combination of
36592 ** GetLastError() and FormatMessage() on Windows (or errno and
36593 ** strerror_r() on Unix). After an error is returned by an OS
36594 ** function, SQLite calls this function with zBuf pointing to
36595 ** a buffer of nBuf bytes. The OS layer should populate the
36596 ** buffer with a nul-terminated UTF-8 encoded error message
36597 ** describing the last IO error to have occurred within the calling
36598 ** thread.
36600 ** If the error message is too large for the supplied buffer,
36601 ** it should be truncated. The return value of xGetLastError
36602 ** is zero if the error message fits in the buffer, or non-zero
36603 ** otherwise (if the message was truncated). If non-zero is returned,
36604 ** then it is not necessary to include the nul-terminator character
36605 ** in the output buffer.
36607 ** Not supplying an error message will have no adverse effect
36608 ** on SQLite. It is fine to have an implementation that never
36609 ** returns an error message:
36611 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36612 ** assert(zBuf[0]=='\0');
36613 ** return 0;
36614 ** }
36616 ** However if an error message is supplied, it will be incorporated
36617 ** by sqlite into the error message available to the user using
36618 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
36620 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
36621 UNUSED_PARAMETER(pVfs);
36622 return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
36626 ** Initialize and deinitialize the operating system interface.
36628 SQLITE_API int sqlite3_os_init(void){
36629 static sqlite3_vfs winVfs = {
36630 3, /* iVersion */
36631 sizeof(winFile), /* szOsFile */
36632 SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
36633 0, /* pNext */
36634 "win32", /* zName */
36635 0, /* pAppData */
36636 winOpen, /* xOpen */
36637 winDelete, /* xDelete */
36638 winAccess, /* xAccess */
36639 winFullPathname, /* xFullPathname */
36640 winDlOpen, /* xDlOpen */
36641 winDlError, /* xDlError */
36642 winDlSym, /* xDlSym */
36643 winDlClose, /* xDlClose */
36644 winRandomness, /* xRandomness */
36645 winSleep, /* xSleep */
36646 winCurrentTime, /* xCurrentTime */
36647 winGetLastError, /* xGetLastError */
36648 winCurrentTimeInt64, /* xCurrentTimeInt64 */
36649 winSetSystemCall, /* xSetSystemCall */
36650 winGetSystemCall, /* xGetSystemCall */
36651 winNextSystemCall, /* xNextSystemCall */
36653 #if defined(SQLITE_WIN32_HAS_WIDE)
36654 static sqlite3_vfs winLongPathVfs = {
36655 3, /* iVersion */
36656 sizeof(winFile), /* szOsFile */
36657 SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
36658 0, /* pNext */
36659 "win32-longpath", /* zName */
36660 0, /* pAppData */
36661 winOpen, /* xOpen */
36662 winDelete, /* xDelete */
36663 winAccess, /* xAccess */
36664 winFullPathname, /* xFullPathname */
36665 winDlOpen, /* xDlOpen */
36666 winDlError, /* xDlError */
36667 winDlSym, /* xDlSym */
36668 winDlClose, /* xDlClose */
36669 winRandomness, /* xRandomness */
36670 winSleep, /* xSleep */
36671 winCurrentTime, /* xCurrentTime */
36672 winGetLastError, /* xGetLastError */
36673 winCurrentTimeInt64, /* xCurrentTimeInt64 */
36674 winSetSystemCall, /* xSetSystemCall */
36675 winGetSystemCall, /* xGetSystemCall */
36676 winNextSystemCall, /* xNextSystemCall */
36678 #endif
36680 /* Double-check that the aSyscall[] array has been constructed
36681 ** correctly. See ticket [bb3a86e890c8e96ab] */
36682 assert( ArraySize(aSyscall)==76 );
36684 /* get memory map allocation granularity */
36685 memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
36686 #if SQLITE_OS_WINRT
36687 osGetNativeSystemInfo(&winSysInfo);
36688 #else
36689 osGetSystemInfo(&winSysInfo);
36690 #endif
36691 assert( winSysInfo.dwAllocationGranularity>0 );
36692 assert( winSysInfo.dwPageSize>0 );
36694 sqlite3_vfs_register(&winVfs, 1);
36696 #if defined(SQLITE_WIN32_HAS_WIDE)
36697 sqlite3_vfs_register(&winLongPathVfs, 0);
36698 #endif
36700 return SQLITE_OK;
36703 SQLITE_API int sqlite3_os_end(void){
36704 #if SQLITE_OS_WINRT
36705 if( sleepObj!=NULL ){
36706 osCloseHandle(sleepObj);
36707 sleepObj = NULL;
36709 #endif
36710 return SQLITE_OK;
36713 #endif /* SQLITE_OS_WIN */
36715 /************** End of os_win.c **********************************************/
36716 /************** Begin file bitvec.c ******************************************/
36718 ** 2008 February 16
36720 ** The author disclaims copyright to this source code. In place of
36721 ** a legal notice, here is a blessing:
36723 ** May you do good and not evil.
36724 ** May you find forgiveness for yourself and forgive others.
36725 ** May you share freely, never taking more than you give.
36727 *************************************************************************
36728 ** This file implements an object that represents a fixed-length
36729 ** bitmap. Bits are numbered starting with 1.
36731 ** A bitmap is used to record which pages of a database file have been
36732 ** journalled during a transaction, or which pages have the "dont-write"
36733 ** property. Usually only a few pages are meet either condition.
36734 ** So the bitmap is usually sparse and has low cardinality.
36735 ** But sometimes (for example when during a DROP of a large table) most
36736 ** or all of the pages in a database can get journalled. In those cases,
36737 ** the bitmap becomes dense with high cardinality. The algorithm needs
36738 ** to handle both cases well.
36740 ** The size of the bitmap is fixed when the object is created.
36742 ** All bits are clear when the bitmap is created. Individual bits
36743 ** may be set or cleared one at a time.
36745 ** Test operations are about 100 times more common that set operations.
36746 ** Clear operations are exceedingly rare. There are usually between
36747 ** 5 and 500 set operations per Bitvec object, though the number of sets can
36748 ** sometimes grow into tens of thousands or larger. The size of the
36749 ** Bitvec object is the number of pages in the database file at the
36750 ** start of a transaction, and is thus usually less than a few thousand,
36751 ** but can be as large as 2 billion for a really big database.
36754 /* Size of the Bitvec structure in bytes. */
36755 #define BITVEC_SZ 512
36757 /* Round the union size down to the nearest pointer boundary, since that's how
36758 ** it will be aligned within the Bitvec struct. */
36759 #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
36761 /* Type of the array "element" for the bitmap representation.
36762 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
36763 ** Setting this to the "natural word" size of your CPU may improve
36764 ** performance. */
36765 #define BITVEC_TELEM u8
36766 /* Size, in bits, of the bitmap element. */
36767 #define BITVEC_SZELEM 8
36768 /* Number of elements in a bitmap array. */
36769 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
36770 /* Number of bits in the bitmap array. */
36771 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
36773 /* Number of u32 values in hash table. */
36774 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
36775 /* Maximum number of entries in hash table before
36776 ** sub-dividing and re-hashing. */
36777 #define BITVEC_MXHASH (BITVEC_NINT/2)
36778 /* Hashing function for the aHash representation.
36779 ** Empirical testing showed that the *37 multiplier
36780 ** (an arbitrary prime)in the hash function provided
36781 ** no fewer collisions than the no-op *1. */
36782 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
36784 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
36788 ** A bitmap is an instance of the following structure.
36790 ** This bitmap records the existence of zero or more bits
36791 ** with values between 1 and iSize, inclusive.
36793 ** There are three possible representations of the bitmap.
36794 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
36795 ** bitmap. The least significant bit is bit 1.
36797 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
36798 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
36800 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
36801 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
36802 ** handles up to iDivisor separate values of i. apSub[0] holds
36803 ** values between 1 and iDivisor. apSub[1] holds values between
36804 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
36805 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
36806 ** to hold deal with values between 1 and iDivisor.
36808 struct Bitvec {
36809 u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
36810 u32 nSet; /* Number of bits that are set - only valid for aHash
36811 ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
36812 ** this would be 125. */
36813 u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
36814 /* Should >=0 for apSub element. */
36815 /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
36816 /* For a BITVEC_SZ of 512, this would be 34,359,739. */
36817 union {
36818 BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
36819 u32 aHash[BITVEC_NINT]; /* Hash table representation */
36820 Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
36821 } u;
36825 ** Create a new bitmap object able to handle bits between 0 and iSize,
36826 ** inclusive. Return a pointer to the new object. Return NULL if
36827 ** malloc fails.
36829 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
36830 Bitvec *p;
36831 assert( sizeof(*p)==BITVEC_SZ );
36832 p = sqlite3MallocZero( sizeof(*p) );
36833 if( p ){
36834 p->iSize = iSize;
36836 return p;
36840 ** Check to see if the i-th bit is set. Return true or false.
36841 ** If p is NULL (if the bitmap has not been created) or if
36842 ** i is out of range, then return false.
36844 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
36845 if( p==0 ) return 0;
36846 if( i>p->iSize || i==0 ) return 0;
36847 i--;
36848 while( p->iDivisor ){
36849 u32 bin = i/p->iDivisor;
36850 i = i%p->iDivisor;
36851 p = p->u.apSub[bin];
36852 if (!p) {
36853 return 0;
36856 if( p->iSize<=BITVEC_NBIT ){
36857 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
36858 } else{
36859 u32 h = BITVEC_HASH(i++);
36860 while( p->u.aHash[h] ){
36861 if( p->u.aHash[h]==i ) return 1;
36862 h = (h+1) % BITVEC_NINT;
36864 return 0;
36869 ** Set the i-th bit. Return 0 on success and an error code if
36870 ** anything goes wrong.
36872 ** This routine might cause sub-bitmaps to be allocated. Failing
36873 ** to get the memory needed to hold the sub-bitmap is the only
36874 ** that can go wrong with an insert, assuming p and i are valid.
36876 ** The calling function must ensure that p is a valid Bitvec object
36877 ** and that the value for "i" is within range of the Bitvec object.
36878 ** Otherwise the behavior is undefined.
36880 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
36881 u32 h;
36882 if( p==0 ) return SQLITE_OK;
36883 assert( i>0 );
36884 assert( i<=p->iSize );
36885 i--;
36886 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
36887 u32 bin = i/p->iDivisor;
36888 i = i%p->iDivisor;
36889 if( p->u.apSub[bin]==0 ){
36890 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
36891 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
36893 p = p->u.apSub[bin];
36895 if( p->iSize<=BITVEC_NBIT ){
36896 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
36897 return SQLITE_OK;
36899 h = BITVEC_HASH(i++);
36900 /* if there wasn't a hash collision, and this doesn't */
36901 /* completely fill the hash, then just add it without */
36902 /* worring about sub-dividing and re-hashing. */
36903 if( !p->u.aHash[h] ){
36904 if (p->nSet<(BITVEC_NINT-1)) {
36905 goto bitvec_set_end;
36906 } else {
36907 goto bitvec_set_rehash;
36910 /* there was a collision, check to see if it's already */
36911 /* in hash, if not, try to find a spot for it */
36912 do {
36913 if( p->u.aHash[h]==i ) return SQLITE_OK;
36914 h++;
36915 if( h>=BITVEC_NINT ) h = 0;
36916 } while( p->u.aHash[h] );
36917 /* we didn't find it in the hash. h points to the first */
36918 /* available free spot. check to see if this is going to */
36919 /* make our hash too "full". */
36920 bitvec_set_rehash:
36921 if( p->nSet>=BITVEC_MXHASH ){
36922 unsigned int j;
36923 int rc;
36924 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
36925 if( aiValues==0 ){
36926 return SQLITE_NOMEM;
36927 }else{
36928 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36929 memset(p->u.apSub, 0, sizeof(p->u.apSub));
36930 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
36931 rc = sqlite3BitvecSet(p, i);
36932 for(j=0; j<BITVEC_NINT; j++){
36933 if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
36935 sqlite3StackFree(0, aiValues);
36936 return rc;
36939 bitvec_set_end:
36940 p->nSet++;
36941 p->u.aHash[h] = i;
36942 return SQLITE_OK;
36946 ** Clear the i-th bit.
36948 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
36949 ** that BitvecClear can use to rebuilt its hash table.
36951 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
36952 if( p==0 ) return;
36953 assert( i>0 );
36954 i--;
36955 while( p->iDivisor ){
36956 u32 bin = i/p->iDivisor;
36957 i = i%p->iDivisor;
36958 p = p->u.apSub[bin];
36959 if (!p) {
36960 return;
36963 if( p->iSize<=BITVEC_NBIT ){
36964 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
36965 }else{
36966 unsigned int j;
36967 u32 *aiValues = pBuf;
36968 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36969 memset(p->u.aHash, 0, sizeof(p->u.aHash));
36970 p->nSet = 0;
36971 for(j=0; j<BITVEC_NINT; j++){
36972 if( aiValues[j] && aiValues[j]!=(i+1) ){
36973 u32 h = BITVEC_HASH(aiValues[j]-1);
36974 p->nSet++;
36975 while( p->u.aHash[h] ){
36976 h++;
36977 if( h>=BITVEC_NINT ) h = 0;
36979 p->u.aHash[h] = aiValues[j];
36986 ** Destroy a bitmap object. Reclaim all memory used.
36988 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
36989 if( p==0 ) return;
36990 if( p->iDivisor ){
36991 unsigned int i;
36992 for(i=0; i<BITVEC_NPTR; i++){
36993 sqlite3BitvecDestroy(p->u.apSub[i]);
36996 sqlite3_free(p);
37000 ** Return the value of the iSize parameter specified when Bitvec *p
37001 ** was created.
37003 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
37004 return p->iSize;
37007 #ifndef SQLITE_OMIT_BUILTIN_TEST
37009 ** Let V[] be an array of unsigned characters sufficient to hold
37010 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
37011 ** Then the following macros can be used to set, clear, or test
37012 ** individual bits within V.
37014 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
37015 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
37016 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
37019 ** This routine runs an extensive test of the Bitvec code.
37021 ** The input is an array of integers that acts as a program
37022 ** to test the Bitvec. The integers are opcodes followed
37023 ** by 0, 1, or 3 operands, depending on the opcode. Another
37024 ** opcode follows immediately after the last operand.
37026 ** There are 6 opcodes numbered from 0 through 5. 0 is the
37027 ** "halt" opcode and causes the test to end.
37029 ** 0 Halt and return the number of errors
37030 ** 1 N S X Set N bits beginning with S and incrementing by X
37031 ** 2 N S X Clear N bits beginning with S and incrementing by X
37032 ** 3 N Set N randomly chosen bits
37033 ** 4 N Clear N randomly chosen bits
37034 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
37036 ** The opcodes 1 through 4 perform set and clear operations are performed
37037 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
37038 ** Opcode 5 works on the linear array only, not on the Bitvec.
37039 ** Opcode 5 is used to deliberately induce a fault in order to
37040 ** confirm that error detection works.
37042 ** At the conclusion of the test the linear array is compared
37043 ** against the Bitvec object. If there are any differences,
37044 ** an error is returned. If they are the same, zero is returned.
37046 ** If a memory allocation error occurs, return -1.
37048 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
37049 Bitvec *pBitvec = 0;
37050 unsigned char *pV = 0;
37051 int rc = -1;
37052 int i, nx, pc, op;
37053 void *pTmpSpace;
37055 /* Allocate the Bitvec to be tested and a linear array of
37056 ** bits to act as the reference */
37057 pBitvec = sqlite3BitvecCreate( sz );
37058 pV = sqlite3MallocZero( (sz+7)/8 + 1 );
37059 pTmpSpace = sqlite3_malloc(BITVEC_SZ);
37060 if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
37062 /* NULL pBitvec tests */
37063 sqlite3BitvecSet(0, 1);
37064 sqlite3BitvecClear(0, 1, pTmpSpace);
37066 /* Run the program */
37067 pc = 0;
37068 while( (op = aOp[pc])!=0 ){
37069 switch( op ){
37070 case 1:
37071 case 2:
37072 case 5: {
37073 nx = 4;
37074 i = aOp[pc+2] - 1;
37075 aOp[pc+2] += aOp[pc+3];
37076 break;
37078 case 3:
37079 case 4:
37080 default: {
37081 nx = 2;
37082 sqlite3_randomness(sizeof(i), &i);
37083 break;
37086 if( (--aOp[pc+1]) > 0 ) nx = 0;
37087 pc += nx;
37088 i = (i & 0x7fffffff)%sz;
37089 if( (op & 1)!=0 ){
37090 SETBIT(pV, (i+1));
37091 if( op!=5 ){
37092 if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
37094 }else{
37095 CLEARBIT(pV, (i+1));
37096 sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
37100 /* Test to make sure the linear array exactly matches the
37101 ** Bitvec object. Start with the assumption that they do
37102 ** match (rc==0). Change rc to non-zero if a discrepancy
37103 ** is found.
37105 rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
37106 + sqlite3BitvecTest(pBitvec, 0)
37107 + (sqlite3BitvecSize(pBitvec) - sz);
37108 for(i=1; i<=sz; i++){
37109 if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
37110 rc = i;
37111 break;
37115 /* Free allocated structure */
37116 bitvec_end:
37117 sqlite3_free(pTmpSpace);
37118 sqlite3_free(pV);
37119 sqlite3BitvecDestroy(pBitvec);
37120 return rc;
37122 #endif /* SQLITE_OMIT_BUILTIN_TEST */
37124 /************** End of bitvec.c **********************************************/
37125 /************** Begin file pcache.c ******************************************/
37127 ** 2008 August 05
37129 ** The author disclaims copyright to this source code. In place of
37130 ** a legal notice, here is a blessing:
37132 ** May you do good and not evil.
37133 ** May you find forgiveness for yourself and forgive others.
37134 ** May you share freely, never taking more than you give.
37136 *************************************************************************
37137 ** This file implements that page cache.
37141 ** A complete page cache is an instance of this structure.
37143 struct PCache {
37144 PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
37145 PgHdr *pSynced; /* Last synced page in dirty page list */
37146 int nRef; /* Number of referenced pages */
37147 int szCache; /* Configured cache size */
37148 int szPage; /* Size of every page in this cache */
37149 int szExtra; /* Size of extra space for each page */
37150 int bPurgeable; /* True if pages are on backing store */
37151 int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
37152 void *pStress; /* Argument to xStress */
37153 sqlite3_pcache *pCache; /* Pluggable cache module */
37154 PgHdr *pPage1; /* Reference to page 1 */
37158 ** Some of the assert() macros in this code are too expensive to run
37159 ** even during normal debugging. Use them only rarely on long-running
37160 ** tests. Enable the expensive asserts using the
37161 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
37163 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
37164 # define expensive_assert(X) assert(X)
37165 #else
37166 # define expensive_assert(X)
37167 #endif
37169 /********************************** Linked List Management ********************/
37171 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
37173 ** Check that the pCache->pSynced variable is set correctly. If it
37174 ** is not, either fail an assert or return zero. Otherwise, return
37175 ** non-zero. This is only used in debugging builds, as follows:
37177 ** expensive_assert( pcacheCheckSynced(pCache) );
37179 static int pcacheCheckSynced(PCache *pCache){
37180 PgHdr *p;
37181 for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
37182 assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
37184 return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
37186 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
37189 ** Remove page pPage from the list of dirty pages.
37191 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
37192 PCache *p = pPage->pCache;
37194 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
37195 assert( pPage->pDirtyPrev || pPage==p->pDirty );
37197 /* Update the PCache1.pSynced variable if necessary. */
37198 if( p->pSynced==pPage ){
37199 PgHdr *pSynced = pPage->pDirtyPrev;
37200 while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
37201 pSynced = pSynced->pDirtyPrev;
37203 p->pSynced = pSynced;
37206 if( pPage->pDirtyNext ){
37207 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
37208 }else{
37209 assert( pPage==p->pDirtyTail );
37210 p->pDirtyTail = pPage->pDirtyPrev;
37212 if( pPage->pDirtyPrev ){
37213 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
37214 }else{
37215 assert( pPage==p->pDirty );
37216 p->pDirty = pPage->pDirtyNext;
37218 pPage->pDirtyNext = 0;
37219 pPage->pDirtyPrev = 0;
37221 expensive_assert( pcacheCheckSynced(p) );
37225 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
37226 ** pPage).
37228 static void pcacheAddToDirtyList(PgHdr *pPage){
37229 PCache *p = pPage->pCache;
37231 assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
37233 pPage->pDirtyNext = p->pDirty;
37234 if( pPage->pDirtyNext ){
37235 assert( pPage->pDirtyNext->pDirtyPrev==0 );
37236 pPage->pDirtyNext->pDirtyPrev = pPage;
37238 p->pDirty = pPage;
37239 if( !p->pDirtyTail ){
37240 p->pDirtyTail = pPage;
37242 if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
37243 p->pSynced = pPage;
37245 expensive_assert( pcacheCheckSynced(p) );
37249 ** Wrapper around the pluggable caches xUnpin method. If the cache is
37250 ** being used for an in-memory database, this function is a no-op.
37252 static void pcacheUnpin(PgHdr *p){
37253 PCache *pCache = p->pCache;
37254 if( pCache->bPurgeable ){
37255 if( p->pgno==1 ){
37256 pCache->pPage1 = 0;
37258 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
37262 /*************************************************** General Interfaces ******
37264 ** Initialize and shutdown the page cache subsystem. Neither of these
37265 ** functions are threadsafe.
37267 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
37268 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
37269 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
37270 ** built-in default page cache is used instead of the application defined
37271 ** page cache. */
37272 sqlite3PCacheSetDefault();
37274 return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
37276 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
37277 if( sqlite3GlobalConfig.pcache2.xShutdown ){
37278 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
37279 sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
37284 ** Return the size in bytes of a PCache object.
37286 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
37289 ** Create a new PCache object. Storage space to hold the object
37290 ** has already been allocated and is passed in as the p pointer.
37291 ** The caller discovers how much space needs to be allocated by
37292 ** calling sqlite3PcacheSize().
37294 SQLITE_PRIVATE void sqlite3PcacheOpen(
37295 int szPage, /* Size of every page */
37296 int szExtra, /* Extra space associated with each page */
37297 int bPurgeable, /* True if pages are on backing store */
37298 int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
37299 void *pStress, /* Argument to xStress */
37300 PCache *p /* Preallocated space for the PCache */
37302 memset(p, 0, sizeof(PCache));
37303 p->szPage = szPage;
37304 p->szExtra = szExtra;
37305 p->bPurgeable = bPurgeable;
37306 p->xStress = xStress;
37307 p->pStress = pStress;
37308 p->szCache = 100;
37312 ** Change the page size for PCache object. The caller must ensure that there
37313 ** are no outstanding page references when this function is called.
37315 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
37316 assert( pCache->nRef==0 && pCache->pDirty==0 );
37317 if( pCache->pCache ){
37318 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37319 pCache->pCache = 0;
37320 pCache->pPage1 = 0;
37322 pCache->szPage = szPage;
37326 ** Compute the number of pages of cache requested.
37328 static int numberOfCachePages(PCache *p){
37329 if( p->szCache>=0 ){
37330 return p->szCache;
37331 }else{
37332 return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
37337 ** Try to obtain a page from the cache.
37339 SQLITE_PRIVATE int sqlite3PcacheFetch(
37340 PCache *pCache, /* Obtain the page from this cache */
37341 Pgno pgno, /* Page number to obtain */
37342 int createFlag, /* If true, create page if it does not exist already */
37343 PgHdr **ppPage /* Write the page here */
37345 sqlite3_pcache_page *pPage = 0;
37346 PgHdr *pPgHdr = 0;
37347 int eCreate;
37349 assert( pCache!=0 );
37350 assert( createFlag==1 || createFlag==0 );
37351 assert( pgno>0 );
37353 /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
37354 ** allocate it now.
37356 if( !pCache->pCache && createFlag ){
37357 sqlite3_pcache *p;
37358 p = sqlite3GlobalConfig.pcache2.xCreate(
37359 pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
37361 if( !p ){
37362 return SQLITE_NOMEM;
37364 sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
37365 pCache->pCache = p;
37368 eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
37369 if( pCache->pCache ){
37370 pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
37373 if( !pPage && eCreate==1 ){
37374 PgHdr *pPg;
37376 /* Find a dirty page to write-out and recycle. First try to find a
37377 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
37378 ** cleared), but if that is not possible settle for any other
37379 ** unreferenced dirty page.
37381 expensive_assert( pcacheCheckSynced(pCache) );
37382 for(pPg=pCache->pSynced;
37383 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
37384 pPg=pPg->pDirtyPrev
37386 pCache->pSynced = pPg;
37387 if( !pPg ){
37388 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
37390 if( pPg ){
37391 int rc;
37392 #ifdef SQLITE_LOG_CACHE_SPILL
37393 sqlite3_log(SQLITE_FULL,
37394 "spill page %d making room for %d - cache used: %d/%d",
37395 pPg->pgno, pgno,
37396 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
37397 numberOfCachePages(pCache));
37398 #endif
37399 rc = pCache->xStress(pCache->pStress, pPg);
37400 if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
37401 return rc;
37405 pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
37408 if( pPage ){
37409 pPgHdr = (PgHdr *)pPage->pExtra;
37411 if( !pPgHdr->pPage ){
37412 memset(pPgHdr, 0, sizeof(PgHdr));
37413 pPgHdr->pPage = pPage;
37414 pPgHdr->pData = pPage->pBuf;
37415 pPgHdr->pExtra = (void *)&pPgHdr[1];
37416 memset(pPgHdr->pExtra, 0, pCache->szExtra);
37417 pPgHdr->pCache = pCache;
37418 pPgHdr->pgno = pgno;
37420 assert( pPgHdr->pCache==pCache );
37421 assert( pPgHdr->pgno==pgno );
37422 assert( pPgHdr->pData==pPage->pBuf );
37423 assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
37425 if( 0==pPgHdr->nRef ){
37426 pCache->nRef++;
37428 pPgHdr->nRef++;
37429 if( pgno==1 ){
37430 pCache->pPage1 = pPgHdr;
37433 *ppPage = pPgHdr;
37434 return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
37438 ** Decrement the reference count on a page. If the page is clean and the
37439 ** reference count drops to 0, then it is made elible for recycling.
37441 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
37442 assert( p->nRef>0 );
37443 p->nRef--;
37444 if( p->nRef==0 ){
37445 PCache *pCache = p->pCache;
37446 pCache->nRef--;
37447 if( (p->flags&PGHDR_DIRTY)==0 ){
37448 pcacheUnpin(p);
37449 }else{
37450 /* Move the page to the head of the dirty list. */
37451 pcacheRemoveFromDirtyList(p);
37452 pcacheAddToDirtyList(p);
37458 ** Increase the reference count of a supplied page by 1.
37460 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
37461 assert(p->nRef>0);
37462 p->nRef++;
37466 ** Drop a page from the cache. There must be exactly one reference to the
37467 ** page. This function deletes that reference, so after it returns the
37468 ** page pointed to by p is invalid.
37470 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
37471 PCache *pCache;
37472 assert( p->nRef==1 );
37473 if( p->flags&PGHDR_DIRTY ){
37474 pcacheRemoveFromDirtyList(p);
37476 pCache = p->pCache;
37477 pCache->nRef--;
37478 if( p->pgno==1 ){
37479 pCache->pPage1 = 0;
37481 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
37485 ** Make sure the page is marked as dirty. If it isn't dirty already,
37486 ** make it so.
37488 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
37489 p->flags &= ~PGHDR_DONT_WRITE;
37490 assert( p->nRef>0 );
37491 if( 0==(p->flags & PGHDR_DIRTY) ){
37492 p->flags |= PGHDR_DIRTY;
37493 pcacheAddToDirtyList( p);
37498 ** Make sure the page is marked as clean. If it isn't clean already,
37499 ** make it so.
37501 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
37502 if( (p->flags & PGHDR_DIRTY) ){
37503 pcacheRemoveFromDirtyList(p);
37504 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
37505 if( p->nRef==0 ){
37506 pcacheUnpin(p);
37512 ** Make every page in the cache clean.
37514 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
37515 PgHdr *p;
37516 while( (p = pCache->pDirty)!=0 ){
37517 sqlite3PcacheMakeClean(p);
37522 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
37524 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
37525 PgHdr *p;
37526 for(p=pCache->pDirty; p; p=p->pDirtyNext){
37527 p->flags &= ~PGHDR_NEED_SYNC;
37529 pCache->pSynced = pCache->pDirtyTail;
37533 ** Change the page number of page p to newPgno.
37535 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
37536 PCache *pCache = p->pCache;
37537 assert( p->nRef>0 );
37538 assert( newPgno>0 );
37539 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
37540 p->pgno = newPgno;
37541 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
37542 pcacheRemoveFromDirtyList(p);
37543 pcacheAddToDirtyList(p);
37548 ** Drop every cache entry whose page number is greater than "pgno". The
37549 ** caller must ensure that there are no outstanding references to any pages
37550 ** other than page 1 with a page number greater than pgno.
37552 ** If there is a reference to page 1 and the pgno parameter passed to this
37553 ** function is 0, then the data area associated with page 1 is zeroed, but
37554 ** the page object is not dropped.
37556 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
37557 if( pCache->pCache ){
37558 PgHdr *p;
37559 PgHdr *pNext;
37560 for(p=pCache->pDirty; p; p=pNext){
37561 pNext = p->pDirtyNext;
37562 /* This routine never gets call with a positive pgno except right
37563 ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
37564 ** it must be that pgno==0.
37566 assert( p->pgno>0 );
37567 if( ALWAYS(p->pgno>pgno) ){
37568 assert( p->flags&PGHDR_DIRTY );
37569 sqlite3PcacheMakeClean(p);
37572 if( pgno==0 && pCache->pPage1 ){
37573 memset(pCache->pPage1->pData, 0, pCache->szPage);
37574 pgno = 1;
37576 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
37581 ** Close a cache.
37583 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
37584 if( pCache->pCache ){
37585 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
37590 ** Discard the contents of the cache.
37592 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
37593 sqlite3PcacheTruncate(pCache, 0);
37597 ** Merge two lists of pages connected by pDirty and in pgno order.
37598 ** Do not both fixing the pDirtyPrev pointers.
37600 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
37601 PgHdr result, *pTail;
37602 pTail = &result;
37603 while( pA && pB ){
37604 if( pA->pgno<pB->pgno ){
37605 pTail->pDirty = pA;
37606 pTail = pA;
37607 pA = pA->pDirty;
37608 }else{
37609 pTail->pDirty = pB;
37610 pTail = pB;
37611 pB = pB->pDirty;
37614 if( pA ){
37615 pTail->pDirty = pA;
37616 }else if( pB ){
37617 pTail->pDirty = pB;
37618 }else{
37619 pTail->pDirty = 0;
37621 return result.pDirty;
37625 ** Sort the list of pages in accending order by pgno. Pages are
37626 ** connected by pDirty pointers. The pDirtyPrev pointers are
37627 ** corrupted by this sort.
37629 ** Since there cannot be more than 2^31 distinct pages in a database,
37630 ** there cannot be more than 31 buckets required by the merge sorter.
37631 ** One extra bucket is added to catch overflow in case something
37632 ** ever changes to make the previous sentence incorrect.
37634 #define N_SORT_BUCKET 32
37635 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
37636 PgHdr *a[N_SORT_BUCKET], *p;
37637 int i;
37638 memset(a, 0, sizeof(a));
37639 while( pIn ){
37640 p = pIn;
37641 pIn = p->pDirty;
37642 p->pDirty = 0;
37643 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
37644 if( a[i]==0 ){
37645 a[i] = p;
37646 break;
37647 }else{
37648 p = pcacheMergeDirtyList(a[i], p);
37649 a[i] = 0;
37652 if( NEVER(i==N_SORT_BUCKET-1) ){
37653 /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
37654 ** the input list. But that is impossible.
37656 a[i] = pcacheMergeDirtyList(a[i], p);
37659 p = a[0];
37660 for(i=1; i<N_SORT_BUCKET; i++){
37661 p = pcacheMergeDirtyList(p, a[i]);
37663 return p;
37667 ** Return a list of all dirty pages in the cache, sorted by page number.
37669 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
37670 PgHdr *p;
37671 for(p=pCache->pDirty; p; p=p->pDirtyNext){
37672 p->pDirty = p->pDirtyNext;
37674 return pcacheSortDirtyList(pCache->pDirty);
37678 ** Return the total number of referenced pages held by the cache.
37680 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
37681 return pCache->nRef;
37685 ** Return the number of references to the page supplied as an argument.
37687 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
37688 return p->nRef;
37692 ** Return the total number of pages in the cache.
37694 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
37695 int nPage = 0;
37696 if( pCache->pCache ){
37697 nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
37699 return nPage;
37702 #ifdef SQLITE_TEST
37704 ** Get the suggested cache-size value.
37706 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
37707 return numberOfCachePages(pCache);
37709 #endif
37712 ** Set the suggested cache-size value.
37714 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
37715 pCache->szCache = mxPage;
37716 if( pCache->pCache ){
37717 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
37718 numberOfCachePages(pCache));
37723 ** Free up as much memory as possible from the page cache.
37725 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
37726 if( pCache->pCache ){
37727 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
37731 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
37733 ** For all dirty pages currently in the cache, invoke the specified
37734 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
37735 ** defined.
37737 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
37738 PgHdr *pDirty;
37739 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
37740 xIter(pDirty);
37743 #endif
37745 /************** End of pcache.c **********************************************/
37746 /************** Begin file pcache1.c *****************************************/
37748 ** 2008 November 05
37750 ** The author disclaims copyright to this source code. In place of
37751 ** a legal notice, here is a blessing:
37753 ** May you do good and not evil.
37754 ** May you find forgiveness for yourself and forgive others.
37755 ** May you share freely, never taking more than you give.
37757 *************************************************************************
37759 ** This file implements the default page cache implementation (the
37760 ** sqlite3_pcache interface). It also contains part of the implementation
37761 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
37762 ** If the default page cache implementation is overriden, then neither of
37763 ** these two features are available.
37767 typedef struct PCache1 PCache1;
37768 typedef struct PgHdr1 PgHdr1;
37769 typedef struct PgFreeslot PgFreeslot;
37770 typedef struct PGroup PGroup;
37772 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
37773 ** of one or more PCaches that are able to recycle each others unpinned
37774 ** pages when they are under memory pressure. A PGroup is an instance of
37775 ** the following object.
37777 ** This page cache implementation works in one of two modes:
37779 ** (1) Every PCache is the sole member of its own PGroup. There is
37780 ** one PGroup per PCache.
37782 ** (2) There is a single global PGroup that all PCaches are a member
37783 ** of.
37785 ** Mode 1 uses more memory (since PCache instances are not able to rob
37786 ** unused pages from other PCaches) but it also operates without a mutex,
37787 ** and is therefore often faster. Mode 2 requires a mutex in order to be
37788 ** threadsafe, but recycles pages more efficiently.
37790 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
37791 ** PGroup which is the pcache1.grp global variable and its mutex is
37792 ** SQLITE_MUTEX_STATIC_LRU.
37794 struct PGroup {
37795 sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
37796 unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
37797 unsigned int nMinPage; /* Sum of nMin for purgeable caches */
37798 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
37799 unsigned int nCurrentPage; /* Number of purgeable pages allocated */
37800 PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
37803 /* Each page cache is an instance of the following object. Every
37804 ** open database file (including each in-memory database and each
37805 ** temporary or transient database) has a single page cache which
37806 ** is an instance of this object.
37808 ** Pointers to structures of this type are cast and returned as
37809 ** opaque sqlite3_pcache* handles.
37811 struct PCache1 {
37812 /* Cache configuration parameters. Page size (szPage) and the purgeable
37813 ** flag (bPurgeable) are set when the cache is created. nMax may be
37814 ** modified at any time by a call to the pcache1Cachesize() method.
37815 ** The PGroup mutex must be held when accessing nMax.
37817 PGroup *pGroup; /* PGroup this cache belongs to */
37818 int szPage; /* Size of allocated pages in bytes */
37819 int szExtra; /* Size of extra space in bytes */
37820 int bPurgeable; /* True if cache is purgeable */
37821 unsigned int nMin; /* Minimum number of pages reserved */
37822 unsigned int nMax; /* Configured "cache_size" value */
37823 unsigned int n90pct; /* nMax*9/10 */
37824 unsigned int iMaxKey; /* Largest key seen since xTruncate() */
37826 /* Hash table of all pages. The following variables may only be accessed
37827 ** when the accessor is holding the PGroup mutex.
37829 unsigned int nRecyclable; /* Number of pages in the LRU list */
37830 unsigned int nPage; /* Total number of pages in apHash */
37831 unsigned int nHash; /* Number of slots in apHash[] */
37832 PgHdr1 **apHash; /* Hash table for fast lookup by key */
37836 ** Each cache entry is represented by an instance of the following
37837 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
37838 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
37839 ** in memory.
37841 struct PgHdr1 {
37842 sqlite3_pcache_page page;
37843 unsigned int iKey; /* Key value (page number) */
37844 u8 isPinned; /* Page in use, not on the LRU list */
37845 PgHdr1 *pNext; /* Next in hash table chain */
37846 PCache1 *pCache; /* Cache that currently owns this page */
37847 PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
37848 PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
37852 ** Free slots in the allocator used to divide up the buffer provided using
37853 ** the SQLITE_CONFIG_PAGECACHE mechanism.
37855 struct PgFreeslot {
37856 PgFreeslot *pNext; /* Next free slot */
37860 ** Global data used by this cache.
37862 static SQLITE_WSD struct PCacheGlobal {
37863 PGroup grp; /* The global PGroup for mode (2) */
37865 /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
37866 ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
37867 ** fixed at sqlite3_initialize() time and do not require mutex protection.
37868 ** The nFreeSlot and pFree values do require mutex protection.
37870 int isInit; /* True if initialized */
37871 int szSlot; /* Size of each free slot */
37872 int nSlot; /* The number of pcache slots */
37873 int nReserve; /* Try to keep nFreeSlot above this */
37874 void *pStart, *pEnd; /* Bounds of pagecache malloc range */
37875 /* Above requires no mutex. Use mutex below for variable that follow. */
37876 sqlite3_mutex *mutex; /* Mutex for accessing the following: */
37877 PgFreeslot *pFree; /* Free page blocks */
37878 int nFreeSlot; /* Number of unused pcache slots */
37879 /* The following value requires a mutex to change. We skip the mutex on
37880 ** reading because (1) most platforms read a 32-bit integer atomically and
37881 ** (2) even if an incorrect value is read, no great harm is done since this
37882 ** is really just an optimization. */
37883 int bUnderPressure; /* True if low on PAGECACHE memory */
37884 } pcache1_g;
37887 ** All code in this file should access the global structure above via the
37888 ** alias "pcache1". This ensures that the WSD emulation is used when
37889 ** compiling for systems that do not support real WSD.
37891 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
37894 ** Macros to enter and leave the PCache LRU mutex.
37896 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
37897 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
37899 /******************************************************************************/
37900 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
37903 ** This function is called during initialization if a static buffer is
37904 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
37905 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
37906 ** enough to contain 'n' buffers of 'sz' bytes each.
37908 ** This routine is called from sqlite3_initialize() and so it is guaranteed
37909 ** to be serialized already. There is no need for further mutexing.
37911 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
37912 if( pcache1.isInit ){
37913 PgFreeslot *p;
37914 sz = ROUNDDOWN8(sz);
37915 pcache1.szSlot = sz;
37916 pcache1.nSlot = pcache1.nFreeSlot = n;
37917 pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
37918 pcache1.pStart = pBuf;
37919 pcache1.pFree = 0;
37920 pcache1.bUnderPressure = 0;
37921 while( n-- ){
37922 p = (PgFreeslot*)pBuf;
37923 p->pNext = pcache1.pFree;
37924 pcache1.pFree = p;
37925 pBuf = (void*)&((char*)pBuf)[sz];
37927 pcache1.pEnd = pBuf;
37932 ** Malloc function used within this file to allocate space from the buffer
37933 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
37934 ** such buffer exists or there is no space left in it, this function falls
37935 ** back to sqlite3Malloc().
37937 ** Multiple threads can run this routine at the same time. Global variables
37938 ** in pcache1 need to be protected via mutex.
37940 static void *pcache1Alloc(int nByte){
37941 void *p = 0;
37942 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37943 sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
37944 if( nByte<=pcache1.szSlot ){
37945 sqlite3_mutex_enter(pcache1.mutex);
37946 p = (PgHdr1 *)pcache1.pFree;
37947 if( p ){
37948 pcache1.pFree = pcache1.pFree->pNext;
37949 pcache1.nFreeSlot--;
37950 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37951 assert( pcache1.nFreeSlot>=0 );
37952 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
37954 sqlite3_mutex_leave(pcache1.mutex);
37956 if( p==0 ){
37957 /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
37958 ** it from sqlite3Malloc instead.
37960 p = sqlite3Malloc(nByte);
37961 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
37962 if( p ){
37963 int sz = sqlite3MallocSize(p);
37964 sqlite3_mutex_enter(pcache1.mutex);
37965 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
37966 sqlite3_mutex_leave(pcache1.mutex);
37968 #endif
37969 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37971 return p;
37975 ** Free an allocated buffer obtained from pcache1Alloc().
37977 static int pcache1Free(void *p){
37978 int nFreed = 0;
37979 if( p==0 ) return 0;
37980 if( p>=pcache1.pStart && p<pcache1.pEnd ){
37981 PgFreeslot *pSlot;
37982 sqlite3_mutex_enter(pcache1.mutex);
37983 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
37984 pSlot = (PgFreeslot*)p;
37985 pSlot->pNext = pcache1.pFree;
37986 pcache1.pFree = pSlot;
37987 pcache1.nFreeSlot++;
37988 pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37989 assert( pcache1.nFreeSlot<=pcache1.nSlot );
37990 sqlite3_mutex_leave(pcache1.mutex);
37991 }else{
37992 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37993 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37994 nFreed = sqlite3MallocSize(p);
37995 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
37996 sqlite3_mutex_enter(pcache1.mutex);
37997 sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
37998 sqlite3_mutex_leave(pcache1.mutex);
37999 #endif
38000 sqlite3_free(p);
38002 return nFreed;
38005 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38007 ** Return the size of a pcache allocation
38009 static int pcache1MemSize(void *p){
38010 if( p>=pcache1.pStart && p<pcache1.pEnd ){
38011 return pcache1.szSlot;
38012 }else{
38013 int iSize;
38014 assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
38015 sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
38016 iSize = sqlite3MallocSize(p);
38017 sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
38018 return iSize;
38021 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38024 ** Allocate a new page object initially associated with cache pCache.
38026 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
38027 PgHdr1 *p = 0;
38028 void *pPg;
38030 /* The group mutex must be released before pcache1Alloc() is called. This
38031 ** is because it may call sqlite3_release_memory(), which assumes that
38032 ** this mutex is not held. */
38033 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38034 pcache1LeaveMutex(pCache->pGroup);
38035 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38036 pPg = pcache1Alloc(pCache->szPage);
38037 p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
38038 if( !pPg || !p ){
38039 pcache1Free(pPg);
38040 sqlite3_free(p);
38041 pPg = 0;
38043 #else
38044 pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
38045 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
38046 #endif
38047 pcache1EnterMutex(pCache->pGroup);
38049 if( pPg ){
38050 p->page.pBuf = pPg;
38051 p->page.pExtra = &p[1];
38052 if( pCache->bPurgeable ){
38053 pCache->pGroup->nCurrentPage++;
38055 return p;
38057 return 0;
38061 ** Free a page object allocated by pcache1AllocPage().
38063 ** The pointer is allowed to be NULL, which is prudent. But it turns out
38064 ** that the current implementation happens to never call this routine
38065 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
38067 static void pcache1FreePage(PgHdr1 *p){
38068 if( ALWAYS(p) ){
38069 PCache1 *pCache = p->pCache;
38070 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
38071 pcache1Free(p->page.pBuf);
38072 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38073 sqlite3_free(p);
38074 #endif
38075 if( pCache->bPurgeable ){
38076 pCache->pGroup->nCurrentPage--;
38082 ** Malloc function used by SQLite to obtain space from the buffer configured
38083 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
38084 ** exists, this function falls back to sqlite3Malloc().
38086 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
38087 return pcache1Alloc(sz);
38091 ** Free an allocated buffer obtained from sqlite3PageMalloc().
38093 SQLITE_PRIVATE void sqlite3PageFree(void *p){
38094 pcache1Free(p);
38099 ** Return true if it desirable to avoid allocating a new page cache
38100 ** entry.
38102 ** If memory was allocated specifically to the page cache using
38103 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
38104 ** it is desirable to avoid allocating a new page cache entry because
38105 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
38106 ** for all page cache needs and we should not need to spill the
38107 ** allocation onto the heap.
38109 ** Or, the heap is used for all page cache memory but the heap is
38110 ** under memory pressure, then again it is desirable to avoid
38111 ** allocating a new page cache entry in order to avoid stressing
38112 ** the heap even further.
38114 static int pcache1UnderMemoryPressure(PCache1 *pCache){
38115 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
38116 return pcache1.bUnderPressure;
38117 }else{
38118 return sqlite3HeapNearlyFull();
38122 /******************************************************************************/
38123 /******** General Implementation Functions ************************************/
38126 ** This function is used to resize the hash table used by the cache passed
38127 ** as the first argument.
38129 ** The PCache mutex must be held when this function is called.
38131 static int pcache1ResizeHash(PCache1 *p){
38132 PgHdr1 **apNew;
38133 unsigned int nNew;
38134 unsigned int i;
38136 assert( sqlite3_mutex_held(p->pGroup->mutex) );
38138 nNew = p->nHash*2;
38139 if( nNew<256 ){
38140 nNew = 256;
38143 pcache1LeaveMutex(p->pGroup);
38144 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
38145 apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
38146 if( p->nHash ){ sqlite3EndBenignMalloc(); }
38147 pcache1EnterMutex(p->pGroup);
38148 if( apNew ){
38149 for(i=0; i<p->nHash; i++){
38150 PgHdr1 *pPage;
38151 PgHdr1 *pNext = p->apHash[i];
38152 while( (pPage = pNext)!=0 ){
38153 unsigned int h = pPage->iKey % nNew;
38154 pNext = pPage->pNext;
38155 pPage->pNext = apNew[h];
38156 apNew[h] = pPage;
38159 sqlite3_free(p->apHash);
38160 p->apHash = apNew;
38161 p->nHash = nNew;
38164 return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
38168 ** This function is used internally to remove the page pPage from the
38169 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
38170 ** LRU list, then this function is a no-op.
38172 ** The PGroup mutex must be held when this function is called.
38174 static void pcache1PinPage(PgHdr1 *pPage){
38175 PCache1 *pCache;
38176 PGroup *pGroup;
38178 assert( pPage!=0 );
38179 assert( pPage->isPinned==0 );
38180 pCache = pPage->pCache;
38181 pGroup = pCache->pGroup;
38182 assert( pPage->pLruNext || pPage==pGroup->pLruTail );
38183 assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
38184 assert( sqlite3_mutex_held(pGroup->mutex) );
38185 if( pPage->pLruPrev ){
38186 pPage->pLruPrev->pLruNext = pPage->pLruNext;
38187 }else{
38188 pGroup->pLruHead = pPage->pLruNext;
38190 if( pPage->pLruNext ){
38191 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
38192 }else{
38193 pGroup->pLruTail = pPage->pLruPrev;
38195 pPage->pLruNext = 0;
38196 pPage->pLruPrev = 0;
38197 pPage->isPinned = 1;
38198 pCache->nRecyclable--;
38203 ** Remove the page supplied as an argument from the hash table
38204 ** (PCache1.apHash structure) that it is currently stored in.
38206 ** The PGroup mutex must be held when this function is called.
38208 static void pcache1RemoveFromHash(PgHdr1 *pPage){
38209 unsigned int h;
38210 PCache1 *pCache = pPage->pCache;
38211 PgHdr1 **pp;
38213 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38214 h = pPage->iKey % pCache->nHash;
38215 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
38216 *pp = (*pp)->pNext;
38218 pCache->nPage--;
38222 ** If there are currently more than nMaxPage pages allocated, try
38223 ** to recycle pages to reduce the number allocated to nMaxPage.
38225 static void pcache1EnforceMaxPage(PGroup *pGroup){
38226 assert( sqlite3_mutex_held(pGroup->mutex) );
38227 while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
38228 PgHdr1 *p = pGroup->pLruTail;
38229 assert( p->pCache->pGroup==pGroup );
38230 assert( p->isPinned==0 );
38231 pcache1PinPage(p);
38232 pcache1RemoveFromHash(p);
38233 pcache1FreePage(p);
38238 ** Discard all pages from cache pCache with a page number (key value)
38239 ** greater than or equal to iLimit. Any pinned pages that meet this
38240 ** criteria are unpinned before they are discarded.
38242 ** The PCache mutex must be held when this function is called.
38244 static void pcache1TruncateUnsafe(
38245 PCache1 *pCache, /* The cache to truncate */
38246 unsigned int iLimit /* Drop pages with this pgno or larger */
38248 TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
38249 unsigned int h;
38250 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
38251 for(h=0; h<pCache->nHash; h++){
38252 PgHdr1 **pp = &pCache->apHash[h];
38253 PgHdr1 *pPage;
38254 while( (pPage = *pp)!=0 ){
38255 if( pPage->iKey>=iLimit ){
38256 pCache->nPage--;
38257 *pp = pPage->pNext;
38258 if( !pPage->isPinned ) pcache1PinPage(pPage);
38259 pcache1FreePage(pPage);
38260 }else{
38261 pp = &pPage->pNext;
38262 TESTONLY( nPage++; )
38266 assert( pCache->nPage==nPage );
38269 /******************************************************************************/
38270 /******** sqlite3_pcache Methods **********************************************/
38273 ** Implementation of the sqlite3_pcache.xInit method.
38275 static int pcache1Init(void *NotUsed){
38276 UNUSED_PARAMETER(NotUsed);
38277 assert( pcache1.isInit==0 );
38278 memset(&pcache1, 0, sizeof(pcache1));
38279 if( sqlite3GlobalConfig.bCoreMutex ){
38280 pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
38281 pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
38283 pcache1.grp.mxPinned = 10;
38284 pcache1.isInit = 1;
38285 return SQLITE_OK;
38289 ** Implementation of the sqlite3_pcache.xShutdown method.
38290 ** Note that the static mutex allocated in xInit does
38291 ** not need to be freed.
38293 static void pcache1Shutdown(void *NotUsed){
38294 UNUSED_PARAMETER(NotUsed);
38295 assert( pcache1.isInit!=0 );
38296 memset(&pcache1, 0, sizeof(pcache1));
38300 ** Implementation of the sqlite3_pcache.xCreate method.
38302 ** Allocate a new cache.
38304 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
38305 PCache1 *pCache; /* The newly created page cache */
38306 PGroup *pGroup; /* The group the new page cache will belong to */
38307 int sz; /* Bytes of memory required to allocate the new cache */
38310 ** The separateCache variable is true if each PCache has its own private
38311 ** PGroup. In other words, separateCache is true for mode (1) where no
38312 ** mutexing is required.
38314 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
38316 ** * Always use a unified cache in single-threaded applications
38318 ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
38319 ** use separate caches (mode-1)
38321 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
38322 const int separateCache = 0;
38323 #else
38324 int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
38325 #endif
38327 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
38328 assert( szExtra < 300 );
38330 sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
38331 pCache = (PCache1 *)sqlite3MallocZero(sz);
38332 if( pCache ){
38333 if( separateCache ){
38334 pGroup = (PGroup*)&pCache[1];
38335 pGroup->mxPinned = 10;
38336 }else{
38337 pGroup = &pcache1.grp;
38339 pCache->pGroup = pGroup;
38340 pCache->szPage = szPage;
38341 pCache->szExtra = szExtra;
38342 pCache->bPurgeable = (bPurgeable ? 1 : 0);
38343 if( bPurgeable ){
38344 pCache->nMin = 10;
38345 pcache1EnterMutex(pGroup);
38346 pGroup->nMinPage += pCache->nMin;
38347 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38348 pcache1LeaveMutex(pGroup);
38351 return (sqlite3_pcache *)pCache;
38355 ** Implementation of the sqlite3_pcache.xCachesize method.
38357 ** Configure the cache_size limit for a cache.
38359 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
38360 PCache1 *pCache = (PCache1 *)p;
38361 if( pCache->bPurgeable ){
38362 PGroup *pGroup = pCache->pGroup;
38363 pcache1EnterMutex(pGroup);
38364 pGroup->nMaxPage += (nMax - pCache->nMax);
38365 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38366 pCache->nMax = nMax;
38367 pCache->n90pct = pCache->nMax*9/10;
38368 pcache1EnforceMaxPage(pGroup);
38369 pcache1LeaveMutex(pGroup);
38374 ** Implementation of the sqlite3_pcache.xShrink method.
38376 ** Free up as much memory as possible.
38378 static void pcache1Shrink(sqlite3_pcache *p){
38379 PCache1 *pCache = (PCache1*)p;
38380 if( pCache->bPurgeable ){
38381 PGroup *pGroup = pCache->pGroup;
38382 int savedMaxPage;
38383 pcache1EnterMutex(pGroup);
38384 savedMaxPage = pGroup->nMaxPage;
38385 pGroup->nMaxPage = 0;
38386 pcache1EnforceMaxPage(pGroup);
38387 pGroup->nMaxPage = savedMaxPage;
38388 pcache1LeaveMutex(pGroup);
38393 ** Implementation of the sqlite3_pcache.xPagecount method.
38395 static int pcache1Pagecount(sqlite3_pcache *p){
38396 int n;
38397 PCache1 *pCache = (PCache1*)p;
38398 pcache1EnterMutex(pCache->pGroup);
38399 n = pCache->nPage;
38400 pcache1LeaveMutex(pCache->pGroup);
38401 return n;
38405 ** Implementation of the sqlite3_pcache.xFetch method.
38407 ** Fetch a page by key value.
38409 ** Whether or not a new page may be allocated by this function depends on
38410 ** the value of the createFlag argument. 0 means do not allocate a new
38411 ** page. 1 means allocate a new page if space is easily available. 2
38412 ** means to try really hard to allocate a new page.
38414 ** For a non-purgeable cache (a cache used as the storage for an in-memory
38415 ** database) there is really no difference between createFlag 1 and 2. So
38416 ** the calling function (pcache.c) will never have a createFlag of 1 on
38417 ** a non-purgeable cache.
38419 ** There are three different approaches to obtaining space for a page,
38420 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
38422 ** 1. Regardless of the value of createFlag, the cache is searched for a
38423 ** copy of the requested page. If one is found, it is returned.
38425 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
38426 ** returned.
38428 ** 3. If createFlag is 1, and the page is not already in the cache, then
38429 ** return NULL (do not allocate a new page) if any of the following
38430 ** conditions are true:
38432 ** (a) the number of pages pinned by the cache is greater than
38433 ** PCache1.nMax, or
38435 ** (b) the number of pages pinned by the cache is greater than
38436 ** the sum of nMax for all purgeable caches, less the sum of
38437 ** nMin for all other purgeable caches, or
38439 ** 4. If none of the first three conditions apply and the cache is marked
38440 ** as purgeable, and if one of the following is true:
38442 ** (a) The number of pages allocated for the cache is already
38443 ** PCache1.nMax, or
38445 ** (b) The number of pages allocated for all purgeable caches is
38446 ** already equal to or greater than the sum of nMax for all
38447 ** purgeable caches,
38449 ** (c) The system is under memory pressure and wants to avoid
38450 ** unnecessary pages cache entry allocations
38452 ** then attempt to recycle a page from the LRU list. If it is the right
38453 ** size, return the recycled buffer. Otherwise, free the buffer and
38454 ** proceed to step 5.
38456 ** 5. Otherwise, allocate and return a new page buffer.
38458 static sqlite3_pcache_page *pcache1Fetch(
38459 sqlite3_pcache *p,
38460 unsigned int iKey,
38461 int createFlag
38463 unsigned int nPinned;
38464 PCache1 *pCache = (PCache1 *)p;
38465 PGroup *pGroup;
38466 PgHdr1 *pPage = 0;
38468 assert( offsetof(PgHdr1,page)==0 );
38469 assert( pCache->bPurgeable || createFlag!=1 );
38470 assert( pCache->bPurgeable || pCache->nMin==0 );
38471 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
38472 assert( pCache->nMin==0 || pCache->bPurgeable );
38473 pcache1EnterMutex(pGroup = pCache->pGroup);
38475 /* Step 1: Search the hash table for an existing entry. */
38476 if( pCache->nHash>0 ){
38477 unsigned int h = iKey % pCache->nHash;
38478 for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
38481 /* Step 2: Abort if no existing page is found and createFlag is 0 */
38482 if( pPage ){
38483 if( !pPage->isPinned ) pcache1PinPage(pPage);
38484 goto fetch_out;
38486 if( createFlag==0 ){
38487 goto fetch_out;
38490 /* The pGroup local variable will normally be initialized by the
38491 ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
38492 ** then pcache1EnterMutex() is a no-op, so we have to initialize the
38493 ** local variable here. Delaying the initialization of pGroup is an
38494 ** optimization: The common case is to exit the module before reaching
38495 ** this point.
38497 #ifdef SQLITE_MUTEX_OMIT
38498 pGroup = pCache->pGroup;
38499 #endif
38501 /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
38502 assert( pCache->nPage >= pCache->nRecyclable );
38503 nPinned = pCache->nPage - pCache->nRecyclable;
38504 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
38505 assert( pCache->n90pct == pCache->nMax*9/10 );
38506 if( createFlag==1 && (
38507 nPinned>=pGroup->mxPinned
38508 || nPinned>=pCache->n90pct
38509 || pcache1UnderMemoryPressure(pCache)
38511 goto fetch_out;
38514 if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
38515 goto fetch_out;
38517 assert( pCache->nHash>0 && pCache->apHash );
38519 /* Step 4. Try to recycle a page. */
38520 if( pCache->bPurgeable && pGroup->pLruTail && (
38521 (pCache->nPage+1>=pCache->nMax)
38522 || pGroup->nCurrentPage>=pGroup->nMaxPage
38523 || pcache1UnderMemoryPressure(pCache)
38525 PCache1 *pOther;
38526 pPage = pGroup->pLruTail;
38527 assert( pPage->isPinned==0 );
38528 pcache1RemoveFromHash(pPage);
38529 pcache1PinPage(pPage);
38530 pOther = pPage->pCache;
38532 /* We want to verify that szPage and szExtra are the same for pOther
38533 ** and pCache. Assert that we can verify this by comparing sums. */
38534 assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
38535 assert( pCache->szExtra<512 );
38536 assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
38537 assert( pOther->szExtra<512 );
38539 if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
38540 pcache1FreePage(pPage);
38541 pPage = 0;
38542 }else{
38543 pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
38547 /* Step 5. If a usable page buffer has still not been found,
38548 ** attempt to allocate a new one.
38550 if( !pPage ){
38551 if( createFlag==1 ) sqlite3BeginBenignMalloc();
38552 pPage = pcache1AllocPage(pCache);
38553 if( createFlag==1 ) sqlite3EndBenignMalloc();
38556 if( pPage ){
38557 unsigned int h = iKey % pCache->nHash;
38558 pCache->nPage++;
38559 pPage->iKey = iKey;
38560 pPage->pNext = pCache->apHash[h];
38561 pPage->pCache = pCache;
38562 pPage->pLruPrev = 0;
38563 pPage->pLruNext = 0;
38564 pPage->isPinned = 1;
38565 *(void **)pPage->page.pExtra = 0;
38566 pCache->apHash[h] = pPage;
38569 fetch_out:
38570 if( pPage && iKey>pCache->iMaxKey ){
38571 pCache->iMaxKey = iKey;
38573 pcache1LeaveMutex(pGroup);
38574 return (sqlite3_pcache_page*)pPage;
38579 ** Implementation of the sqlite3_pcache.xUnpin method.
38581 ** Mark a page as unpinned (eligible for asynchronous recycling).
38583 static void pcache1Unpin(
38584 sqlite3_pcache *p,
38585 sqlite3_pcache_page *pPg,
38586 int reuseUnlikely
38588 PCache1 *pCache = (PCache1 *)p;
38589 PgHdr1 *pPage = (PgHdr1 *)pPg;
38590 PGroup *pGroup = pCache->pGroup;
38592 assert( pPage->pCache==pCache );
38593 pcache1EnterMutex(pGroup);
38595 /* It is an error to call this function if the page is already
38596 ** part of the PGroup LRU list.
38598 assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
38599 assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
38600 assert( pPage->isPinned==1 );
38602 if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
38603 pcache1RemoveFromHash(pPage);
38604 pcache1FreePage(pPage);
38605 }else{
38606 /* Add the page to the PGroup LRU list. */
38607 if( pGroup->pLruHead ){
38608 pGroup->pLruHead->pLruPrev = pPage;
38609 pPage->pLruNext = pGroup->pLruHead;
38610 pGroup->pLruHead = pPage;
38611 }else{
38612 pGroup->pLruTail = pPage;
38613 pGroup->pLruHead = pPage;
38615 pCache->nRecyclable++;
38616 pPage->isPinned = 0;
38619 pcache1LeaveMutex(pCache->pGroup);
38623 ** Implementation of the sqlite3_pcache.xRekey method.
38625 static void pcache1Rekey(
38626 sqlite3_pcache *p,
38627 sqlite3_pcache_page *pPg,
38628 unsigned int iOld,
38629 unsigned int iNew
38631 PCache1 *pCache = (PCache1 *)p;
38632 PgHdr1 *pPage = (PgHdr1 *)pPg;
38633 PgHdr1 **pp;
38634 unsigned int h;
38635 assert( pPage->iKey==iOld );
38636 assert( pPage->pCache==pCache );
38638 pcache1EnterMutex(pCache->pGroup);
38640 h = iOld%pCache->nHash;
38641 pp = &pCache->apHash[h];
38642 while( (*pp)!=pPage ){
38643 pp = &(*pp)->pNext;
38645 *pp = pPage->pNext;
38647 h = iNew%pCache->nHash;
38648 pPage->iKey = iNew;
38649 pPage->pNext = pCache->apHash[h];
38650 pCache->apHash[h] = pPage;
38651 if( iNew>pCache->iMaxKey ){
38652 pCache->iMaxKey = iNew;
38655 pcache1LeaveMutex(pCache->pGroup);
38659 ** Implementation of the sqlite3_pcache.xTruncate method.
38661 ** Discard all unpinned pages in the cache with a page number equal to
38662 ** or greater than parameter iLimit. Any pinned pages with a page number
38663 ** equal to or greater than iLimit are implicitly unpinned.
38665 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
38666 PCache1 *pCache = (PCache1 *)p;
38667 pcache1EnterMutex(pCache->pGroup);
38668 if( iLimit<=pCache->iMaxKey ){
38669 pcache1TruncateUnsafe(pCache, iLimit);
38670 pCache->iMaxKey = iLimit-1;
38672 pcache1LeaveMutex(pCache->pGroup);
38676 ** Implementation of the sqlite3_pcache.xDestroy method.
38678 ** Destroy a cache allocated using pcache1Create().
38680 static void pcache1Destroy(sqlite3_pcache *p){
38681 PCache1 *pCache = (PCache1 *)p;
38682 PGroup *pGroup = pCache->pGroup;
38683 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
38684 pcache1EnterMutex(pGroup);
38685 pcache1TruncateUnsafe(pCache, 0);
38686 assert( pGroup->nMaxPage >= pCache->nMax );
38687 pGroup->nMaxPage -= pCache->nMax;
38688 assert( pGroup->nMinPage >= pCache->nMin );
38689 pGroup->nMinPage -= pCache->nMin;
38690 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
38691 pcache1EnforceMaxPage(pGroup);
38692 pcache1LeaveMutex(pGroup);
38693 sqlite3_free(pCache->apHash);
38694 sqlite3_free(pCache);
38698 ** This function is called during initialization (sqlite3_initialize()) to
38699 ** install the default pluggable cache module, assuming the user has not
38700 ** already provided an alternative.
38702 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
38703 static const sqlite3_pcache_methods2 defaultMethods = {
38704 1, /* iVersion */
38705 0, /* pArg */
38706 pcache1Init, /* xInit */
38707 pcache1Shutdown, /* xShutdown */
38708 pcache1Create, /* xCreate */
38709 pcache1Cachesize, /* xCachesize */
38710 pcache1Pagecount, /* xPagecount */
38711 pcache1Fetch, /* xFetch */
38712 pcache1Unpin, /* xUnpin */
38713 pcache1Rekey, /* xRekey */
38714 pcache1Truncate, /* xTruncate */
38715 pcache1Destroy, /* xDestroy */
38716 pcache1Shrink /* xShrink */
38718 sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
38721 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
38723 ** This function is called to free superfluous dynamically allocated memory
38724 ** held by the pager system. Memory in use by any SQLite pager allocated
38725 ** by the current thread may be sqlite3_free()ed.
38727 ** nReq is the number of bytes of memory required. Once this much has
38728 ** been released, the function returns. The return value is the total number
38729 ** of bytes of memory released.
38731 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
38732 int nFree = 0;
38733 assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
38734 assert( sqlite3_mutex_notheld(pcache1.mutex) );
38735 if( pcache1.pStart==0 ){
38736 PgHdr1 *p;
38737 pcache1EnterMutex(&pcache1.grp);
38738 while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
38739 nFree += pcache1MemSize(p->page.pBuf);
38740 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
38741 nFree += sqlite3MemSize(p);
38742 #endif
38743 assert( p->isPinned==0 );
38744 pcache1PinPage(p);
38745 pcache1RemoveFromHash(p);
38746 pcache1FreePage(p);
38748 pcache1LeaveMutex(&pcache1.grp);
38750 return nFree;
38752 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
38754 #ifdef SQLITE_TEST
38756 ** This function is used by test procedures to inspect the internal state
38757 ** of the global cache.
38759 SQLITE_PRIVATE void sqlite3PcacheStats(
38760 int *pnCurrent, /* OUT: Total number of pages cached */
38761 int *pnMax, /* OUT: Global maximum cache size */
38762 int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
38763 int *pnRecyclable /* OUT: Total number of pages available for recycling */
38765 PgHdr1 *p;
38766 int nRecyclable = 0;
38767 for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
38768 assert( p->isPinned==0 );
38769 nRecyclable++;
38771 *pnCurrent = pcache1.grp.nCurrentPage;
38772 *pnMax = (int)pcache1.grp.nMaxPage;
38773 *pnMin = (int)pcache1.grp.nMinPage;
38774 *pnRecyclable = nRecyclable;
38776 #endif
38778 /************** End of pcache1.c *********************************************/
38779 /************** Begin file rowset.c ******************************************/
38781 ** 2008 December 3
38783 ** The author disclaims copyright to this source code. In place of
38784 ** a legal notice, here is a blessing:
38786 ** May you do good and not evil.
38787 ** May you find forgiveness for yourself and forgive others.
38788 ** May you share freely, never taking more than you give.
38790 *************************************************************************
38792 ** This module implements an object we call a "RowSet".
38794 ** The RowSet object is a collection of rowids. Rowids
38795 ** are inserted into the RowSet in an arbitrary order. Inserts
38796 ** can be intermixed with tests to see if a given rowid has been
38797 ** previously inserted into the RowSet.
38799 ** After all inserts are finished, it is possible to extract the
38800 ** elements of the RowSet in sorted order. Once this extraction
38801 ** process has started, no new elements may be inserted.
38803 ** Hence, the primitive operations for a RowSet are:
38805 ** CREATE
38806 ** INSERT
38807 ** TEST
38808 ** SMALLEST
38809 ** DESTROY
38811 ** The CREATE and DESTROY primitives are the constructor and destructor,
38812 ** obviously. The INSERT primitive adds a new element to the RowSet.
38813 ** TEST checks to see if an element is already in the RowSet. SMALLEST
38814 ** extracts the least value from the RowSet.
38816 ** The INSERT primitive might allocate additional memory. Memory is
38817 ** allocated in chunks so most INSERTs do no allocation. There is an
38818 ** upper bound on the size of allocated memory. No memory is freed
38819 ** until DESTROY.
38821 ** The TEST primitive includes a "batch" number. The TEST primitive
38822 ** will only see elements that were inserted before the last change
38823 ** in the batch number. In other words, if an INSERT occurs between
38824 ** two TESTs where the TESTs have the same batch nubmer, then the
38825 ** value added by the INSERT will not be visible to the second TEST.
38826 ** The initial batch number is zero, so if the very first TEST contains
38827 ** a non-zero batch number, it will see all prior INSERTs.
38829 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
38830 ** that is attempted.
38832 ** The cost of an INSERT is roughly constant. (Sometime new memory
38833 ** has to be allocated on an INSERT.) The cost of a TEST with a new
38834 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
38835 ** The cost of a TEST using the same batch number is O(logN). The cost
38836 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
38837 ** primitives are constant time. The cost of DESTROY is O(N).
38839 ** There is an added cost of O(N) when switching between TEST and
38840 ** SMALLEST primitives.
38845 ** Target size for allocation chunks.
38847 #define ROWSET_ALLOCATION_SIZE 1024
38850 ** The number of rowset entries per allocation chunk.
38852 #define ROWSET_ENTRY_PER_CHUNK \
38853 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
38856 ** Each entry in a RowSet is an instance of the following object.
38858 ** This same object is reused to store a linked list of trees of RowSetEntry
38859 ** objects. In that alternative use, pRight points to the next entry
38860 ** in the list, pLeft points to the tree, and v is unused. The
38861 ** RowSet.pForest value points to the head of this forest list.
38863 struct RowSetEntry {
38864 i64 v; /* ROWID value for this entry */
38865 struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
38866 struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
38870 ** RowSetEntry objects are allocated in large chunks (instances of the
38871 ** following structure) to reduce memory allocation overhead. The
38872 ** chunks are kept on a linked list so that they can be deallocated
38873 ** when the RowSet is destroyed.
38875 struct RowSetChunk {
38876 struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
38877 struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
38881 ** A RowSet in an instance of the following structure.
38883 ** A typedef of this structure if found in sqliteInt.h.
38885 struct RowSet {
38886 struct RowSetChunk *pChunk; /* List of all chunk allocations */
38887 sqlite3 *db; /* The database connection */
38888 struct RowSetEntry *pEntry; /* List of entries using pRight */
38889 struct RowSetEntry *pLast; /* Last entry on the pEntry list */
38890 struct RowSetEntry *pFresh; /* Source of new entry objects */
38891 struct RowSetEntry *pForest; /* List of binary trees of entries */
38892 u16 nFresh; /* Number of objects on pFresh */
38893 u8 rsFlags; /* Various flags */
38894 u8 iBatch; /* Current insert batch */
38898 ** Allowed values for RowSet.rsFlags
38900 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
38901 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
38904 ** Turn bulk memory into a RowSet object. N bytes of memory
38905 ** are available at pSpace. The db pointer is used as a memory context
38906 ** for any subsequent allocations that need to occur.
38907 ** Return a pointer to the new RowSet object.
38909 ** It must be the case that N is sufficient to make a Rowset. If not
38910 ** an assertion fault occurs.
38912 ** If N is larger than the minimum, use the surplus as an initial
38913 ** allocation of entries available to be filled.
38915 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
38916 RowSet *p;
38917 assert( N >= ROUND8(sizeof(*p)) );
38918 p = pSpace;
38919 p->pChunk = 0;
38920 p->db = db;
38921 p->pEntry = 0;
38922 p->pLast = 0;
38923 p->pForest = 0;
38924 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
38925 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38926 p->rsFlags = ROWSET_SORTED;
38927 p->iBatch = 0;
38928 return p;
38932 ** Deallocate all chunks from a RowSet. This frees all memory that
38933 ** the RowSet has allocated over its lifetime. This routine is
38934 ** the destructor for the RowSet.
38936 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
38937 struct RowSetChunk *pChunk, *pNextChunk;
38938 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38939 pNextChunk = pChunk->pNextChunk;
38940 sqlite3DbFree(p->db, pChunk);
38942 p->pChunk = 0;
38943 p->nFresh = 0;
38944 p->pEntry = 0;
38945 p->pLast = 0;
38946 p->pForest = 0;
38947 p->rsFlags = ROWSET_SORTED;
38951 ** Allocate a new RowSetEntry object that is associated with the
38952 ** given RowSet. Return a pointer to the new and completely uninitialized
38953 ** objected.
38955 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
38956 ** routine returns NULL.
38958 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
38959 assert( p!=0 );
38960 if( p->nFresh==0 ){
38961 struct RowSetChunk *pNew;
38962 pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
38963 if( pNew==0 ){
38964 return 0;
38966 pNew->pNextChunk = p->pChunk;
38967 p->pChunk = pNew;
38968 p->pFresh = pNew->aEntry;
38969 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
38971 p->nFresh--;
38972 return p->pFresh++;
38976 ** Insert a new value into a RowSet.
38978 ** The mallocFailed flag of the database connection is set if a
38979 ** memory allocation fails.
38981 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
38982 struct RowSetEntry *pEntry; /* The new entry */
38983 struct RowSetEntry *pLast; /* The last prior entry */
38985 /* This routine is never called after sqlite3RowSetNext() */
38986 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38988 pEntry = rowSetEntryAlloc(p);
38989 if( pEntry==0 ) return;
38990 pEntry->v = rowid;
38991 pEntry->pRight = 0;
38992 pLast = p->pLast;
38993 if( pLast ){
38994 if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
38995 p->rsFlags &= ~ROWSET_SORTED;
38997 pLast->pRight = pEntry;
38998 }else{
38999 p->pEntry = pEntry;
39001 p->pLast = pEntry;
39005 ** Merge two lists of RowSetEntry objects. Remove duplicates.
39007 ** The input lists are connected via pRight pointers and are
39008 ** assumed to each already be in sorted order.
39010 static struct RowSetEntry *rowSetEntryMerge(
39011 struct RowSetEntry *pA, /* First sorted list to be merged */
39012 struct RowSetEntry *pB /* Second sorted list to be merged */
39014 struct RowSetEntry head;
39015 struct RowSetEntry *pTail;
39017 pTail = &head;
39018 while( pA && pB ){
39019 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39020 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
39021 if( pA->v<pB->v ){
39022 pTail->pRight = pA;
39023 pA = pA->pRight;
39024 pTail = pTail->pRight;
39025 }else if( pB->v<pA->v ){
39026 pTail->pRight = pB;
39027 pB = pB->pRight;
39028 pTail = pTail->pRight;
39029 }else{
39030 pA = pA->pRight;
39033 if( pA ){
39034 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
39035 pTail->pRight = pA;
39036 }else{
39037 assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
39038 pTail->pRight = pB;
39040 return head.pRight;
39044 ** Sort all elements on the list of RowSetEntry objects into order of
39045 ** increasing v.
39047 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
39048 unsigned int i;
39049 struct RowSetEntry *pNext, *aBucket[40];
39051 memset(aBucket, 0, sizeof(aBucket));
39052 while( pIn ){
39053 pNext = pIn->pRight;
39054 pIn->pRight = 0;
39055 for(i=0; aBucket[i]; i++){
39056 pIn = rowSetEntryMerge(aBucket[i], pIn);
39057 aBucket[i] = 0;
39059 aBucket[i] = pIn;
39060 pIn = pNext;
39062 pIn = 0;
39063 for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
39064 pIn = rowSetEntryMerge(pIn, aBucket[i]);
39066 return pIn;
39071 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
39072 ** Convert this tree into a linked list connected by the pRight pointers
39073 ** and return pointers to the first and last elements of the new list.
39075 static void rowSetTreeToList(
39076 struct RowSetEntry *pIn, /* Root of the input tree */
39077 struct RowSetEntry **ppFirst, /* Write head of the output list here */
39078 struct RowSetEntry **ppLast /* Write tail of the output list here */
39080 assert( pIn!=0 );
39081 if( pIn->pLeft ){
39082 struct RowSetEntry *p;
39083 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
39084 p->pRight = pIn;
39085 }else{
39086 *ppFirst = pIn;
39088 if( pIn->pRight ){
39089 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
39090 }else{
39091 *ppLast = pIn;
39093 assert( (*ppLast)->pRight==0 );
39098 ** Convert a sorted list of elements (connected by pRight) into a binary
39099 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
39100 ** node taken from the head of *ppList. A depth of 2 means a tree with
39101 ** three nodes. And so forth.
39103 ** Use as many entries from the input list as required and update the
39104 ** *ppList to point to the unused elements of the list. If the input
39105 ** list contains too few elements, then construct an incomplete tree
39106 ** and leave *ppList set to NULL.
39108 ** Return a pointer to the root of the constructed binary tree.
39110 static struct RowSetEntry *rowSetNDeepTree(
39111 struct RowSetEntry **ppList,
39112 int iDepth
39114 struct RowSetEntry *p; /* Root of the new tree */
39115 struct RowSetEntry *pLeft; /* Left subtree */
39116 if( *ppList==0 ){
39117 return 0;
39119 if( iDepth==1 ){
39120 p = *ppList;
39121 *ppList = p->pRight;
39122 p->pLeft = p->pRight = 0;
39123 return p;
39125 pLeft = rowSetNDeepTree(ppList, iDepth-1);
39126 p = *ppList;
39127 if( p==0 ){
39128 return pLeft;
39130 p->pLeft = pLeft;
39131 *ppList = p->pRight;
39132 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
39133 return p;
39137 ** Convert a sorted list of elements into a binary tree. Make the tree
39138 ** as deep as it needs to be in order to contain the entire list.
39140 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
39141 int iDepth; /* Depth of the tree so far */
39142 struct RowSetEntry *p; /* Current tree root */
39143 struct RowSetEntry *pLeft; /* Left subtree */
39145 assert( pList!=0 );
39146 p = pList;
39147 pList = p->pRight;
39148 p->pLeft = p->pRight = 0;
39149 for(iDepth=1; pList; iDepth++){
39150 pLeft = p;
39151 p = pList;
39152 pList = p->pRight;
39153 p->pLeft = pLeft;
39154 p->pRight = rowSetNDeepTree(&pList, iDepth);
39156 return p;
39160 ** Take all the entries on p->pEntry and on the trees in p->pForest and
39161 ** sort them all together into one big ordered list on p->pEntry.
39163 ** This routine should only be called once in the life of a RowSet.
39165 static void rowSetToList(RowSet *p){
39167 /* This routine is called only once */
39168 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
39170 if( (p->rsFlags & ROWSET_SORTED)==0 ){
39171 p->pEntry = rowSetEntrySort(p->pEntry);
39174 /* While this module could theoretically support it, sqlite3RowSetNext()
39175 ** is never called after sqlite3RowSetText() for the same RowSet. So
39176 ** there is never a forest to deal with. Should this change, simply
39177 ** remove the assert() and the #if 0. */
39178 assert( p->pForest==0 );
39179 #if 0
39180 while( p->pForest ){
39181 struct RowSetEntry *pTree = p->pForest->pLeft;
39182 if( pTree ){
39183 struct RowSetEntry *pHead, *pTail;
39184 rowSetTreeToList(pTree, &pHead, &pTail);
39185 p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
39187 p->pForest = p->pForest->pRight;
39189 #endif
39190 p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
39194 ** Extract the smallest element from the RowSet.
39195 ** Write the element into *pRowid. Return 1 on success. Return
39196 ** 0 if the RowSet is already empty.
39198 ** After this routine has been called, the sqlite3RowSetInsert()
39199 ** routine may not be called again.
39201 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
39202 assert( p!=0 );
39204 /* Merge the forest into a single sorted list on first call */
39205 if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
39207 /* Return the next entry on the list */
39208 if( p->pEntry ){
39209 *pRowid = p->pEntry->v;
39210 p->pEntry = p->pEntry->pRight;
39211 if( p->pEntry==0 ){
39212 sqlite3RowSetClear(p);
39214 return 1;
39215 }else{
39216 return 0;
39221 ** Check to see if element iRowid was inserted into the rowset as
39222 ** part of any insert batch prior to iBatch. Return 1 or 0.
39224 ** If this is the first test of a new batch and if there exist entires
39225 ** on pRowSet->pEntry, then sort those entires into the forest at
39226 ** pRowSet->pForest so that they can be tested.
39228 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
39229 struct RowSetEntry *p, *pTree;
39231 /* This routine is never called after sqlite3RowSetNext() */
39232 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
39234 /* Sort entries into the forest on the first test of a new batch
39236 if( iBatch!=pRowSet->iBatch ){
39237 p = pRowSet->pEntry;
39238 if( p ){
39239 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
39240 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
39241 p = rowSetEntrySort(p);
39243 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39244 ppPrevTree = &pTree->pRight;
39245 if( pTree->pLeft==0 ){
39246 pTree->pLeft = rowSetListToTree(p);
39247 break;
39248 }else{
39249 struct RowSetEntry *pAux, *pTail;
39250 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
39251 pTree->pLeft = 0;
39252 p = rowSetEntryMerge(pAux, p);
39255 if( pTree==0 ){
39256 *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
39257 if( pTree ){
39258 pTree->v = 0;
39259 pTree->pRight = 0;
39260 pTree->pLeft = rowSetListToTree(p);
39263 pRowSet->pEntry = 0;
39264 pRowSet->pLast = 0;
39265 pRowSet->rsFlags |= ROWSET_SORTED;
39267 pRowSet->iBatch = iBatch;
39270 /* Test to see if the iRowid value appears anywhere in the forest.
39271 ** Return 1 if it does and 0 if not.
39273 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
39274 p = pTree->pLeft;
39275 while( p ){
39276 if( p->v<iRowid ){
39277 p = p->pRight;
39278 }else if( p->v>iRowid ){
39279 p = p->pLeft;
39280 }else{
39281 return 1;
39285 return 0;
39288 /************** End of rowset.c **********************************************/
39289 /************** Begin file pager.c *******************************************/
39291 ** 2001 September 15
39293 ** The author disclaims copyright to this source code. In place of
39294 ** a legal notice, here is a blessing:
39296 ** May you do good and not evil.
39297 ** May you find forgiveness for yourself and forgive others.
39298 ** May you share freely, never taking more than you give.
39300 *************************************************************************
39301 ** This is the implementation of the page cache subsystem or "pager".
39303 ** The pager is used to access a database disk file. It implements
39304 ** atomic commit and rollback through the use of a journal file that
39305 ** is separate from the database file. The pager also implements file
39306 ** locking to prevent two processes from writing the same database
39307 ** file simultaneously, or one process from reading the database while
39308 ** another is writing.
39310 #ifndef SQLITE_OMIT_DISKIO
39311 /************** Include wal.h in the middle of pager.c ***********************/
39312 /************** Begin file wal.h *********************************************/
39314 ** 2010 February 1
39316 ** The author disclaims copyright to this source code. In place of
39317 ** a legal notice, here is a blessing:
39319 ** May you do good and not evil.
39320 ** May you find forgiveness for yourself and forgive others.
39321 ** May you share freely, never taking more than you give.
39323 *************************************************************************
39324 ** This header file defines the interface to the write-ahead logging
39325 ** system. Refer to the comments below and the header comment attached to
39326 ** the implementation of each function in log.c for further details.
39329 #ifndef _WAL_H_
39330 #define _WAL_H_
39333 /* Additional values that can be added to the sync_flags argument of
39334 ** sqlite3WalFrames():
39336 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
39337 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
39339 #ifdef SQLITE_OMIT_WAL
39340 # define sqlite3WalOpen(x,y,z) 0
39341 # define sqlite3WalLimit(x,y)
39342 # define sqlite3WalClose(w,x,y,z) 0
39343 # define sqlite3WalBeginReadTransaction(y,z) 0
39344 # define sqlite3WalEndReadTransaction(z)
39345 # define sqlite3WalDbsize(y) 0
39346 # define sqlite3WalBeginWriteTransaction(y) 0
39347 # define sqlite3WalEndWriteTransaction(x) 0
39348 # define sqlite3WalUndo(x,y,z) 0
39349 # define sqlite3WalSavepoint(y,z)
39350 # define sqlite3WalSavepointUndo(y,z) 0
39351 # define sqlite3WalFrames(u,v,w,x,y,z) 0
39352 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
39353 # define sqlite3WalCallback(z) 0
39354 # define sqlite3WalExclusiveMode(y,z) 0
39355 # define sqlite3WalHeapMemory(z) 0
39356 # define sqlite3WalFramesize(z) 0
39357 # define sqlite3WalFindFrame(x,y,z) 0
39358 #else
39360 #define WAL_SAVEPOINT_NDATA 4
39362 /* Connection to a write-ahead log (WAL) file.
39363 ** There is one object of this type for each pager.
39365 typedef struct Wal Wal;
39367 /* Open and close a connection to a write-ahead log. */
39368 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
39369 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
39371 /* Set the limiting size of a WAL file. */
39372 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
39374 /* Used by readers to open (lock) and close (unlock) a snapshot. A
39375 ** snapshot is like a read-transaction. It is the state of the database
39376 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
39377 ** preserves the current state even if the other threads or processes
39378 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
39379 ** transaction and releases the lock.
39381 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
39382 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
39384 /* Read a page from the write-ahead log, if it is present. */
39385 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
39386 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
39388 /* If the WAL is not empty, return the size of the database. */
39389 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
39391 /* Obtain or release the WRITER lock. */
39392 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
39393 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
39395 /* Undo any frames written (but not committed) to the log */
39396 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
39398 /* Return an integer that records the current (uncommitted) write
39399 ** position in the WAL */
39400 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
39402 /* Move the write position of the WAL back to iFrame. Called in
39403 ** response to a ROLLBACK TO command. */
39404 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
39406 /* Write a frame or frames to the log. */
39407 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
39409 /* Copy pages from the log to the database file */
39410 SQLITE_PRIVATE int sqlite3WalCheckpoint(
39411 Wal *pWal, /* Write-ahead log connection */
39412 int eMode, /* One of PASSIVE, FULL and RESTART */
39413 int (*xBusy)(void*), /* Function to call when busy */
39414 void *pBusyArg, /* Context argument for xBusyHandler */
39415 int sync_flags, /* Flags to sync db file with (or 0) */
39416 int nBuf, /* Size of buffer nBuf */
39417 u8 *zBuf, /* Temporary buffer to use */
39418 int *pnLog, /* OUT: Number of frames in WAL */
39419 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
39422 /* Return the value to pass to a sqlite3_wal_hook callback, the
39423 ** number of frames in the WAL at the point of the last commit since
39424 ** sqlite3WalCallback() was called. If no commits have occurred since
39425 ** the last call, then return 0.
39427 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
39429 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
39430 ** by the pager layer on the database file.
39432 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
39434 /* Return true if the argument is non-NULL and the WAL module is using
39435 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
39436 ** WAL module is using shared-memory, return false.
39438 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
39440 #ifdef SQLITE_ENABLE_ZIPVFS
39441 /* If the WAL file is not empty, return the number of bytes of content
39442 ** stored in each frame (i.e. the db page-size when the WAL was created).
39444 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
39445 #endif
39447 #endif /* ifndef SQLITE_OMIT_WAL */
39448 #endif /* _WAL_H_ */
39450 /************** End of wal.h *************************************************/
39451 /************** Continuing where we left off in pager.c **********************/
39454 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
39456 ** This comment block describes invariants that hold when using a rollback
39457 ** journal. These invariants do not apply for journal_mode=WAL,
39458 ** journal_mode=MEMORY, or journal_mode=OFF.
39460 ** Within this comment block, a page is deemed to have been synced
39461 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
39462 ** Otherwise, the page is not synced until the xSync method of the VFS
39463 ** is called successfully on the file containing the page.
39465 ** Definition: A page of the database file is said to be "overwriteable" if
39466 ** one or more of the following are true about the page:
39468 ** (a) The original content of the page as it was at the beginning of
39469 ** the transaction has been written into the rollback journal and
39470 ** synced.
39472 ** (b) The page was a freelist leaf page at the start of the transaction.
39474 ** (c) The page number is greater than the largest page that existed in
39475 ** the database file at the start of the transaction.
39477 ** (1) A page of the database file is never overwritten unless one of the
39478 ** following are true:
39480 ** (a) The page and all other pages on the same sector are overwriteable.
39482 ** (b) The atomic page write optimization is enabled, and the entire
39483 ** transaction other than the update of the transaction sequence
39484 ** number consists of a single page change.
39486 ** (2) The content of a page written into the rollback journal exactly matches
39487 ** both the content in the database when the rollback journal was written
39488 ** and the content in the database at the beginning of the current
39489 ** transaction.
39491 ** (3) Writes to the database file are an integer multiple of the page size
39492 ** in length and are aligned on a page boundary.
39494 ** (4) Reads from the database file are either aligned on a page boundary and
39495 ** an integer multiple of the page size in length or are taken from the
39496 ** first 100 bytes of the database file.
39498 ** (5) All writes to the database file are synced prior to the rollback journal
39499 ** being deleted, truncated, or zeroed.
39501 ** (6) If a master journal file is used, then all writes to the database file
39502 ** are synced prior to the master journal being deleted.
39504 ** Definition: Two databases (or the same database at two points it time)
39505 ** are said to be "logically equivalent" if they give the same answer to
39506 ** all queries. Note in particular the content of freelist leaf
39507 ** pages can be changed arbitarily without effecting the logical equivalence
39508 ** of the database.
39510 ** (7) At any time, if any subset, including the empty set and the total set,
39511 ** of the unsynced changes to a rollback journal are removed and the
39512 ** journal is rolled back, the resulting database file will be logical
39513 ** equivalent to the database file at the beginning of the transaction.
39515 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
39516 ** is called to restore the database file to the same size it was at
39517 ** the beginning of the transaction. (In some VFSes, the xTruncate
39518 ** method is a no-op, but that does not change the fact the SQLite will
39519 ** invoke it.)
39521 ** (9) Whenever the database file is modified, at least one bit in the range
39522 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
39523 ** the EXCLUSIVE lock, thus signaling other connections on the same
39524 ** database to flush their caches.
39526 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
39527 ** than one billion transactions.
39529 ** (11) A database file is well-formed at the beginning and at the conclusion
39530 ** of every transaction.
39532 ** (12) An EXCLUSIVE lock is held on the database file when writing to
39533 ** the database file.
39535 ** (13) A SHARED lock is held on the database file while reading any
39536 ** content out of the database file.
39538 ******************************************************************************/
39541 ** Macros for troubleshooting. Normally turned off
39543 #if 0
39544 int sqlite3PagerTrace=1; /* True to enable tracing */
39545 #define sqlite3DebugPrintf printf
39546 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
39547 #else
39548 #define PAGERTRACE(X)
39549 #endif
39552 ** The following two macros are used within the PAGERTRACE() macros above
39553 ** to print out file-descriptors.
39555 ** PAGERID() takes a pointer to a Pager struct as its argument. The
39556 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
39557 ** struct as its argument.
39559 #define PAGERID(p) ((int)(p->fd))
39560 #define FILEHANDLEID(fd) ((int)fd)
39563 ** The Pager.eState variable stores the current 'state' of a pager. A
39564 ** pager may be in any one of the seven states shown in the following
39565 ** state diagram.
39567 ** OPEN <------+------+
39568 ** | | |
39569 ** V | |
39570 ** +---------> READER-------+ |
39571 ** | | |
39572 ** | V |
39573 ** |<-------WRITER_LOCKED------> ERROR
39574 ** | | ^
39575 ** | V |
39576 ** |<------WRITER_CACHEMOD-------->|
39577 ** | | |
39578 ** | V |
39579 ** |<-------WRITER_DBMOD---------->|
39580 ** | | |
39581 ** | V |
39582 ** +<------WRITER_FINISHED-------->+
39585 ** List of state transitions and the C [function] that performs each:
39587 ** OPEN -> READER [sqlite3PagerSharedLock]
39588 ** READER -> OPEN [pager_unlock]
39590 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
39591 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
39592 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
39593 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
39594 ** WRITER_*** -> READER [pager_end_transaction]
39596 ** WRITER_*** -> ERROR [pager_error]
39597 ** ERROR -> OPEN [pager_unlock]
39600 ** OPEN:
39602 ** The pager starts up in this state. Nothing is guaranteed in this
39603 ** state - the file may or may not be locked and the database size is
39604 ** unknown. The database may not be read or written.
39606 ** * No read or write transaction is active.
39607 ** * Any lock, or no lock at all, may be held on the database file.
39608 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
39610 ** READER:
39612 ** In this state all the requirements for reading the database in
39613 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
39614 ** was) in exclusive-locking mode, a user-level read transaction is
39615 ** open. The database size is known in this state.
39617 ** A connection running with locking_mode=normal enters this state when
39618 ** it opens a read-transaction on the database and returns to state
39619 ** OPEN after the read-transaction is completed. However a connection
39620 ** running in locking_mode=exclusive (including temp databases) remains in
39621 ** this state even after the read-transaction is closed. The only way
39622 ** a locking_mode=exclusive connection can transition from READER to OPEN
39623 ** is via the ERROR state (see below).
39625 ** * A read transaction may be active (but a write-transaction cannot).
39626 ** * A SHARED or greater lock is held on the database file.
39627 ** * The dbSize variable may be trusted (even if a user-level read
39628 ** transaction is not active). The dbOrigSize and dbFileSize variables
39629 ** may not be trusted at this point.
39630 ** * If the database is a WAL database, then the WAL connection is open.
39631 ** * Even if a read-transaction is not open, it is guaranteed that
39632 ** there is no hot-journal in the file-system.
39634 ** WRITER_LOCKED:
39636 ** The pager moves to this state from READER when a write-transaction
39637 ** is first opened on the database. In WRITER_LOCKED state, all locks
39638 ** required to start a write-transaction are held, but no actual
39639 ** modifications to the cache or database have taken place.
39641 ** In rollback mode, a RESERVED or (if the transaction was opened with
39642 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
39643 ** moving to this state, but the journal file is not written to or opened
39644 ** to in this state. If the transaction is committed or rolled back while
39645 ** in WRITER_LOCKED state, all that is required is to unlock the database
39646 ** file.
39648 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
39649 ** If the connection is running with locking_mode=exclusive, an attempt
39650 ** is made to obtain an EXCLUSIVE lock on the database file.
39652 ** * A write transaction is active.
39653 ** * If the connection is open in rollback-mode, a RESERVED or greater
39654 ** lock is held on the database file.
39655 ** * If the connection is open in WAL-mode, a WAL write transaction
39656 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
39657 ** called).
39658 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
39659 ** * The contents of the pager cache have not been modified.
39660 ** * The journal file may or may not be open.
39661 ** * Nothing (not even the first header) has been written to the journal.
39663 ** WRITER_CACHEMOD:
39665 ** A pager moves from WRITER_LOCKED state to this state when a page is
39666 ** first modified by the upper layer. In rollback mode the journal file
39667 ** is opened (if it is not already open) and a header written to the
39668 ** start of it. The database file on disk has not been modified.
39670 ** * A write transaction is active.
39671 ** * A RESERVED or greater lock is held on the database file.
39672 ** * The journal file is open and the first header has been written
39673 ** to it, but the header has not been synced to disk.
39674 ** * The contents of the page cache have been modified.
39676 ** WRITER_DBMOD:
39678 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
39679 ** when it modifies the contents of the database file. WAL connections
39680 ** never enter this state (since they do not modify the database file,
39681 ** just the log file).
39683 ** * A write transaction is active.
39684 ** * An EXCLUSIVE or greater lock is held on the database file.
39685 ** * The journal file is open and the first header has been written
39686 ** and synced to disk.
39687 ** * The contents of the page cache have been modified (and possibly
39688 ** written to disk).
39690 ** WRITER_FINISHED:
39692 ** It is not possible for a WAL connection to enter this state.
39694 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
39695 ** state after the entire transaction has been successfully written into the
39696 ** database file. In this state the transaction may be committed simply
39697 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
39698 ** not possible to modify the database further. At this point, the upper
39699 ** layer must either commit or rollback the transaction.
39701 ** * A write transaction is active.
39702 ** * An EXCLUSIVE or greater lock is held on the database file.
39703 ** * All writing and syncing of journal and database data has finished.
39704 ** If no error occurred, all that remains is to finalize the journal to
39705 ** commit the transaction. If an error did occur, the caller will need
39706 ** to rollback the transaction.
39708 ** ERROR:
39710 ** The ERROR state is entered when an IO or disk-full error (including
39711 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
39712 ** difficult to be sure that the in-memory pager state (cache contents,
39713 ** db size etc.) are consistent with the contents of the file-system.
39715 ** Temporary pager files may enter the ERROR state, but in-memory pagers
39716 ** cannot.
39718 ** For example, if an IO error occurs while performing a rollback,
39719 ** the contents of the page-cache may be left in an inconsistent state.
39720 ** At this point it would be dangerous to change back to READER state
39721 ** (as usually happens after a rollback). Any subsequent readers might
39722 ** report database corruption (due to the inconsistent cache), and if
39723 ** they upgrade to writers, they may inadvertently corrupt the database
39724 ** file. To avoid this hazard, the pager switches into the ERROR state
39725 ** instead of READER following such an error.
39727 ** Once it has entered the ERROR state, any attempt to use the pager
39728 ** to read or write data returns an error. Eventually, once all
39729 ** outstanding transactions have been abandoned, the pager is able to
39730 ** transition back to OPEN state, discarding the contents of the
39731 ** page-cache and any other in-memory state at the same time. Everything
39732 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
39733 ** when a read-transaction is next opened on the pager (transitioning
39734 ** the pager into READER state). At that point the system has recovered
39735 ** from the error.
39737 ** Specifically, the pager jumps into the ERROR state if:
39739 ** 1. An error occurs while attempting a rollback. This happens in
39740 ** function sqlite3PagerRollback().
39742 ** 2. An error occurs while attempting to finalize a journal file
39743 ** following a commit in function sqlite3PagerCommitPhaseTwo().
39745 ** 3. An error occurs while attempting to write to the journal or
39746 ** database file in function pagerStress() in order to free up
39747 ** memory.
39749 ** In other cases, the error is returned to the b-tree layer. The b-tree
39750 ** layer then attempts a rollback operation. If the error condition
39751 ** persists, the pager enters the ERROR state via condition (1) above.
39753 ** Condition (3) is necessary because it can be triggered by a read-only
39754 ** statement executed within a transaction. In this case, if the error
39755 ** code were simply returned to the user, the b-tree layer would not
39756 ** automatically attempt a rollback, as it assumes that an error in a
39757 ** read-only statement cannot leave the pager in an internally inconsistent
39758 ** state.
39760 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
39761 ** * There are one or more outstanding references to pages (after the
39762 ** last reference is dropped the pager should move back to OPEN state).
39763 ** * The pager is not an in-memory pager.
39766 ** Notes:
39768 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
39769 ** connection is open in WAL mode. A WAL connection is always in one
39770 ** of the first four states.
39772 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
39773 ** state. There are two exceptions: immediately after exclusive-mode has
39774 ** been turned on (and before any read or write transactions are
39775 ** executed), and when the pager is leaving the "error state".
39777 ** * See also: assert_pager_state().
39779 #define PAGER_OPEN 0
39780 #define PAGER_READER 1
39781 #define PAGER_WRITER_LOCKED 2
39782 #define PAGER_WRITER_CACHEMOD 3
39783 #define PAGER_WRITER_DBMOD 4
39784 #define PAGER_WRITER_FINISHED 5
39785 #define PAGER_ERROR 6
39788 ** The Pager.eLock variable is almost always set to one of the
39789 ** following locking-states, according to the lock currently held on
39790 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39791 ** This variable is kept up to date as locks are taken and released by
39792 ** the pagerLockDb() and pagerUnlockDb() wrappers.
39794 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
39795 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
39796 ** the operation was successful. In these circumstances pagerLockDb() and
39797 ** pagerUnlockDb() take a conservative approach - eLock is always updated
39798 ** when unlocking the file, and only updated when locking the file if the
39799 ** VFS call is successful. This way, the Pager.eLock variable may be set
39800 ** to a less exclusive (lower) value than the lock that is actually held
39801 ** at the system level, but it is never set to a more exclusive value.
39803 ** This is usually safe. If an xUnlock fails or appears to fail, there may
39804 ** be a few redundant xLock() calls or a lock may be held for longer than
39805 ** required, but nothing really goes wrong.
39807 ** The exception is when the database file is unlocked as the pager moves
39808 ** from ERROR to OPEN state. At this point there may be a hot-journal file
39809 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
39810 ** transition, by the same pager or any other). If the call to xUnlock()
39811 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
39812 ** can confuse the call to xCheckReservedLock() call made later as part
39813 ** of hot-journal detection.
39815 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
39816 ** lock held by this process or any others". So xCheckReservedLock may
39817 ** return true because the caller itself is holding an EXCLUSIVE lock (but
39818 ** doesn't know it because of a previous error in xUnlock). If this happens
39819 ** a hot-journal may be mistaken for a journal being created by an active
39820 ** transaction in another process, causing SQLite to read from the database
39821 ** without rolling it back.
39823 ** To work around this, if a call to xUnlock() fails when unlocking the
39824 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
39825 ** is only changed back to a real locking state after a successful call
39826 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
39827 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
39828 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
39829 ** lock on the database file before attempting to roll it back. See function
39830 ** PagerSharedLock() for more detail.
39832 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
39833 ** PAGER_OPEN state.
39835 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
39838 ** A macro used for invoking the codec if there is one
39840 #ifdef SQLITE_HAS_CODEC
39841 # define CODEC1(P,D,N,X,E) \
39842 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
39843 # define CODEC2(P,D,N,X,E,O) \
39844 if( P->xCodec==0 ){ O=(char*)D; }else \
39845 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
39846 #else
39847 # define CODEC1(P,D,N,X,E) /* NO-OP */
39848 # define CODEC2(P,D,N,X,E,O) O=(char*)D
39849 #endif
39852 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
39853 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
39854 ** This could conceivably cause corruption following a power failure on
39855 ** such a system. This is currently an undocumented limit.
39857 #define MAX_SECTOR_SIZE 0x10000
39860 ** An instance of the following structure is allocated for each active
39861 ** savepoint and statement transaction in the system. All such structures
39862 ** are stored in the Pager.aSavepoint[] array, which is allocated and
39863 ** resized using sqlite3Realloc().
39865 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
39866 ** set to 0. If a journal-header is written into the main journal while
39867 ** the savepoint is active, then iHdrOffset is set to the byte offset
39868 ** immediately following the last journal record written into the main
39869 ** journal before the journal-header. This is required during savepoint
39870 ** rollback (see pagerPlaybackSavepoint()).
39872 typedef struct PagerSavepoint PagerSavepoint;
39873 struct PagerSavepoint {
39874 i64 iOffset; /* Starting offset in main journal */
39875 i64 iHdrOffset; /* See above */
39876 Bitvec *pInSavepoint; /* Set of pages in this savepoint */
39877 Pgno nOrig; /* Original number of pages in file */
39878 Pgno iSubRec; /* Index of first record in sub-journal */
39879 #ifndef SQLITE_OMIT_WAL
39880 u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
39881 #endif
39885 ** Bits of the Pager.doNotSpill flag. See further description below.
39887 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
39888 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
39889 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
39892 ** A open page cache is an instance of struct Pager. A description of
39893 ** some of the more important member variables follows:
39895 ** eState
39897 ** The current 'state' of the pager object. See the comment and state
39898 ** diagram above for a description of the pager state.
39900 ** eLock
39902 ** For a real on-disk database, the current lock held on the database file -
39903 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
39905 ** For a temporary or in-memory database (neither of which require any
39906 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
39907 ** databases always have Pager.exclusiveMode==1, this tricks the pager
39908 ** logic into thinking that it already has all the locks it will ever
39909 ** need (and no reason to release them).
39911 ** In some (obscure) circumstances, this variable may also be set to
39912 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
39913 ** details.
39915 ** changeCountDone
39917 ** This boolean variable is used to make sure that the change-counter
39918 ** (the 4-byte header field at byte offset 24 of the database file) is
39919 ** not updated more often than necessary.
39921 ** It is set to true when the change-counter field is updated, which
39922 ** can only happen if an exclusive lock is held on the database file.
39923 ** It is cleared (set to false) whenever an exclusive lock is
39924 ** relinquished on the database file. Each time a transaction is committed,
39925 ** The changeCountDone flag is inspected. If it is true, the work of
39926 ** updating the change-counter is omitted for the current transaction.
39928 ** This mechanism means that when running in exclusive mode, a connection
39929 ** need only update the change-counter once, for the first transaction
39930 ** committed.
39932 ** setMaster
39934 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
39935 ** (or may not) specify a master-journal name to be written into the
39936 ** journal file before it is synced to disk.
39938 ** Whether or not a journal file contains a master-journal pointer affects
39939 ** the way in which the journal file is finalized after the transaction is
39940 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
39941 ** If a journal file does not contain a master-journal pointer, it is
39942 ** finalized by overwriting the first journal header with zeroes. If
39943 ** it does contain a master-journal pointer the journal file is finalized
39944 ** by truncating it to zero bytes, just as if the connection were
39945 ** running in "journal_mode=truncate" mode.
39947 ** Journal files that contain master journal pointers cannot be finalized
39948 ** simply by overwriting the first journal-header with zeroes, as the
39949 ** master journal pointer could interfere with hot-journal rollback of any
39950 ** subsequently interrupted transaction that reuses the journal file.
39952 ** The flag is cleared as soon as the journal file is finalized (either
39953 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
39954 ** journal file from being successfully finalized, the setMaster flag
39955 ** is cleared anyway (and the pager will move to ERROR state).
39957 ** doNotSpill
39959 ** This variables control the behavior of cache-spills (calls made by
39960 ** the pcache module to the pagerStress() routine to write cached data
39961 ** to the file-system in order to free up memory).
39963 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
39964 ** writing to the database from pagerStress() is disabled altogether.
39965 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
39966 ** comes up during savepoint rollback that requires the pcache module
39967 ** to allocate a new page to prevent the journal file from being written
39968 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
39969 ** case is a user preference.
39971 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
39972 ** is permitted, but syncing the journal file is not. This flag is set
39973 ** by sqlite3PagerWrite() when the file-system sector-size is larger than
39974 ** the database page-size in order to prevent a journal sync from happening
39975 ** in between the journalling of two pages on the same sector.
39977 ** subjInMemory
39979 ** This is a boolean variable. If true, then any required sub-journal
39980 ** is opened as an in-memory journal file. If false, then in-memory
39981 ** sub-journals are only used for in-memory pager files.
39983 ** This variable is updated by the upper layer each time a new
39984 ** write-transaction is opened.
39986 ** dbSize, dbOrigSize, dbFileSize
39988 ** Variable dbSize is set to the number of pages in the database file.
39989 ** It is valid in PAGER_READER and higher states (all states except for
39990 ** OPEN and ERROR).
39992 ** dbSize is set based on the size of the database file, which may be
39993 ** larger than the size of the database (the value stored at offset
39994 ** 28 of the database header by the btree). If the size of the file
39995 ** is not an integer multiple of the page-size, the value stored in
39996 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
39997 ** Except, any file that is greater than 0 bytes in size is considered
39998 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
39999 ** to dbSize==1).
40001 ** During a write-transaction, if pages with page-numbers greater than
40002 ** dbSize are modified in the cache, dbSize is updated accordingly.
40003 ** Similarly, if the database is truncated using PagerTruncateImage(),
40004 ** dbSize is updated.
40006 ** Variables dbOrigSize and dbFileSize are valid in states
40007 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
40008 ** variable at the start of the transaction. It is used during rollback,
40009 ** and to determine whether or not pages need to be journalled before
40010 ** being modified.
40012 ** Throughout a write-transaction, dbFileSize contains the size of
40013 ** the file on disk in pages. It is set to a copy of dbSize when the
40014 ** write-transaction is first opened, and updated when VFS calls are made
40015 ** to write or truncate the database file on disk.
40017 ** The only reason the dbFileSize variable is required is to suppress
40018 ** unnecessary calls to xTruncate() after committing a transaction. If,
40019 ** when a transaction is committed, the dbFileSize variable indicates
40020 ** that the database file is larger than the database image (Pager.dbSize),
40021 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
40022 ** to measure the database file on disk, and then truncates it if required.
40023 ** dbFileSize is not used when rolling back a transaction. In this case
40024 ** pager_truncate() is called unconditionally (which means there may be
40025 ** a call to xFilesize() that is not strictly required). In either case,
40026 ** pager_truncate() may cause the file to become smaller or larger.
40028 ** dbHintSize
40030 ** The dbHintSize variable is used to limit the number of calls made to
40031 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
40033 ** dbHintSize is set to a copy of the dbSize variable when a
40034 ** write-transaction is opened (at the same time as dbFileSize and
40035 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
40036 ** dbHintSize is increased to the number of pages that correspond to the
40037 ** size-hint passed to the method call. See pager_write_pagelist() for
40038 ** details.
40040 ** errCode
40042 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
40043 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
40044 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
40045 ** sub-codes.
40047 struct Pager {
40048 sqlite3_vfs *pVfs; /* OS functions to use for IO */
40049 u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
40050 u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
40051 u8 useJournal; /* Use a rollback journal on this file */
40052 u8 noSync; /* Do not sync the journal if true */
40053 u8 fullSync; /* Do extra syncs of the journal for robustness */
40054 u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
40055 u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
40056 u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
40057 u8 tempFile; /* zFilename is a temporary file */
40058 u8 readOnly; /* True for a read-only database */
40059 u8 memDb; /* True to inhibit all file I/O */
40061 /**************************************************************************
40062 ** The following block contains those class members that change during
40063 ** routine opertion. Class members not in this block are either fixed
40064 ** when the pager is first created or else only change when there is a
40065 ** significant mode change (such as changing the page_size, locking_mode,
40066 ** or the journal_mode). From another view, these class members describe
40067 ** the "state" of the pager, while other class members describe the
40068 ** "configuration" of the pager.
40070 u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
40071 u8 eLock; /* Current lock held on database file */
40072 u8 changeCountDone; /* Set after incrementing the change-counter */
40073 u8 setMaster; /* True if a m-j name has been written to jrnl */
40074 u8 doNotSpill; /* Do not spill the cache when non-zero */
40075 u8 subjInMemory; /* True to use in-memory sub-journals */
40076 Pgno dbSize; /* Number of pages in the database */
40077 Pgno dbOrigSize; /* dbSize before the current transaction */
40078 Pgno dbFileSize; /* Number of pages in the database file */
40079 Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
40080 int errCode; /* One of several kinds of errors */
40081 int nRec; /* Pages journalled since last j-header written */
40082 u32 cksumInit; /* Quasi-random value added to every checksum */
40083 u32 nSubRec; /* Number of records written to sub-journal */
40084 Bitvec *pInJournal; /* One bit for each page in the database file */
40085 sqlite3_file *fd; /* File descriptor for database */
40086 sqlite3_file *jfd; /* File descriptor for main journal */
40087 sqlite3_file *sjfd; /* File descriptor for sub-journal */
40088 i64 journalOff; /* Current write offset in the journal file */
40089 i64 journalHdr; /* Byte offset to previous journal header */
40090 sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
40091 PagerSavepoint *aSavepoint; /* Array of active savepoints */
40092 int nSavepoint; /* Number of elements in aSavepoint[] */
40093 char dbFileVers[16]; /* Changes whenever database file changes */
40095 u8 bUseFetch; /* True to use xFetch() */
40096 int nMmapOut; /* Number of mmap pages currently outstanding */
40097 sqlite3_int64 szMmap; /* Desired maximum mmap size */
40098 PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
40100 ** End of the routinely-changing class members
40101 ***************************************************************************/
40103 u16 nExtra; /* Add this many bytes to each in-memory page */
40104 i16 nReserve; /* Number of unused bytes at end of each page */
40105 u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
40106 u32 sectorSize; /* Assumed sector size during rollback */
40107 int pageSize; /* Number of bytes in a page */
40108 Pgno mxPgno; /* Maximum allowed size of the database */
40109 i64 journalSizeLimit; /* Size limit for persistent journal files */
40110 char *zFilename; /* Name of the database file */
40111 char *zJournal; /* Name of the journal file */
40112 int (*xBusyHandler)(void*); /* Function to call when busy */
40113 void *pBusyHandlerArg; /* Context argument for xBusyHandler */
40114 int aStat[3]; /* Total cache hits, misses and writes */
40115 #ifdef SQLITE_TEST
40116 int nRead; /* Database pages read */
40117 #endif
40118 void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
40119 #ifdef SQLITE_HAS_CODEC
40120 void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
40121 void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
40122 void (*xCodecFree)(void*); /* Destructor for the codec */
40123 void *pCodec; /* First argument to xCodec... methods */
40124 #endif
40125 char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
40126 PCache *pPCache; /* Pointer to page cache object */
40127 #ifndef SQLITE_OMIT_WAL
40128 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
40129 char *zWal; /* File name for write-ahead log */
40130 #endif
40134 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
40135 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
40136 ** or CACHE_WRITE to sqlite3_db_status().
40138 #define PAGER_STAT_HIT 0
40139 #define PAGER_STAT_MISS 1
40140 #define PAGER_STAT_WRITE 2
40143 ** The following global variables hold counters used for
40144 ** testing purposes only. These variables do not exist in
40145 ** a non-testing build. These variables are not thread-safe.
40147 #ifdef SQLITE_TEST
40148 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
40149 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
40150 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
40151 # define PAGER_INCR(v) v++
40152 #else
40153 # define PAGER_INCR(v)
40154 #endif
40159 ** Journal files begin with the following magic string. The data
40160 ** was obtained from /dev/random. It is used only as a sanity check.
40162 ** Since version 2.8.0, the journal format contains additional sanity
40163 ** checking information. If the power fails while the journal is being
40164 ** written, semi-random garbage data might appear in the journal
40165 ** file after power is restored. If an attempt is then made
40166 ** to roll the journal back, the database could be corrupted. The additional
40167 ** sanity checking data is an attempt to discover the garbage in the
40168 ** journal and ignore it.
40170 ** The sanity checking information for the new journal format consists
40171 ** of a 32-bit checksum on each page of data. The checksum covers both
40172 ** the page number and the pPager->pageSize bytes of data for the page.
40173 ** This cksum is initialized to a 32-bit random value that appears in the
40174 ** journal file right after the header. The random initializer is important,
40175 ** because garbage data that appears at the end of a journal is likely
40176 ** data that was once in other files that have now been deleted. If the
40177 ** garbage data came from an obsolete journal file, the checksums might
40178 ** be correct. But by initializing the checksum to random value which
40179 ** is different for every journal, we minimize that risk.
40181 static const unsigned char aJournalMagic[] = {
40182 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
40186 ** The size of the of each page record in the journal is given by
40187 ** the following macro.
40189 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
40192 ** The journal header size for this pager. This is usually the same
40193 ** size as a single disk sector. See also setSectorSize().
40195 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
40198 ** The macro MEMDB is true if we are dealing with an in-memory database.
40199 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
40200 ** the value of MEMDB will be a constant and the compiler will optimize
40201 ** out code that would never execute.
40203 #ifdef SQLITE_OMIT_MEMORYDB
40204 # define MEMDB 0
40205 #else
40206 # define MEMDB pPager->memDb
40207 #endif
40210 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
40211 ** interfaces to access the database using memory-mapped I/O.
40213 #if SQLITE_MAX_MMAP_SIZE>0
40214 # define USEFETCH(x) ((x)->bUseFetch)
40215 #else
40216 # define USEFETCH(x) 0
40217 #endif
40220 ** The maximum legal page number is (2^31 - 1).
40222 #define PAGER_MAX_PGNO 2147483647
40225 ** The argument to this macro is a file descriptor (type sqlite3_file*).
40226 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
40228 ** This is so that expressions can be written as:
40230 ** if( isOpen(pPager->jfd) ){ ...
40232 ** instead of
40234 ** if( pPager->jfd->pMethods ){ ...
40236 #define isOpen(pFd) ((pFd)->pMethods)
40239 ** Return true if this pager uses a write-ahead log instead of the usual
40240 ** rollback journal. Otherwise false.
40242 #ifndef SQLITE_OMIT_WAL
40243 static int pagerUseWal(Pager *pPager){
40244 return (pPager->pWal!=0);
40246 #else
40247 # define pagerUseWal(x) 0
40248 # define pagerRollbackWal(x) 0
40249 # define pagerWalFrames(v,w,x,y) 0
40250 # define pagerOpenWalIfPresent(z) SQLITE_OK
40251 # define pagerBeginReadTransaction(z) SQLITE_OK
40252 #endif
40254 #ifndef NDEBUG
40256 ** Usage:
40258 ** assert( assert_pager_state(pPager) );
40260 ** This function runs many asserts to try to find inconsistencies in
40261 ** the internal state of the Pager object.
40263 static int assert_pager_state(Pager *p){
40264 Pager *pPager = p;
40266 /* State must be valid. */
40267 assert( p->eState==PAGER_OPEN
40268 || p->eState==PAGER_READER
40269 || p->eState==PAGER_WRITER_LOCKED
40270 || p->eState==PAGER_WRITER_CACHEMOD
40271 || p->eState==PAGER_WRITER_DBMOD
40272 || p->eState==PAGER_WRITER_FINISHED
40273 || p->eState==PAGER_ERROR
40276 /* Regardless of the current state, a temp-file connection always behaves
40277 ** as if it has an exclusive lock on the database file. It never updates
40278 ** the change-counter field, so the changeCountDone flag is always set.
40280 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
40281 assert( p->tempFile==0 || pPager->changeCountDone );
40283 /* If the useJournal flag is clear, the journal-mode must be "OFF".
40284 ** And if the journal-mode is "OFF", the journal file must not be open.
40286 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
40287 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
40289 /* Check that MEMDB implies noSync. And an in-memory journal. Since
40290 ** this means an in-memory pager performs no IO at all, it cannot encounter
40291 ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
40292 ** a journal file. (although the in-memory journal implementation may
40293 ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
40294 ** is therefore not possible for an in-memory pager to enter the ERROR
40295 ** state.
40297 if( MEMDB ){
40298 assert( p->noSync );
40299 assert( p->journalMode==PAGER_JOURNALMODE_OFF
40300 || p->journalMode==PAGER_JOURNALMODE_MEMORY
40302 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
40303 assert( pagerUseWal(p)==0 );
40306 /* If changeCountDone is set, a RESERVED lock or greater must be held
40307 ** on the file.
40309 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
40310 assert( p->eLock!=PENDING_LOCK );
40312 switch( p->eState ){
40313 case PAGER_OPEN:
40314 assert( !MEMDB );
40315 assert( pPager->errCode==SQLITE_OK );
40316 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
40317 break;
40319 case PAGER_READER:
40320 assert( pPager->errCode==SQLITE_OK );
40321 assert( p->eLock!=UNKNOWN_LOCK );
40322 assert( p->eLock>=SHARED_LOCK );
40323 break;
40325 case PAGER_WRITER_LOCKED:
40326 assert( p->eLock!=UNKNOWN_LOCK );
40327 assert( pPager->errCode==SQLITE_OK );
40328 if( !pagerUseWal(pPager) ){
40329 assert( p->eLock>=RESERVED_LOCK );
40331 assert( pPager->dbSize==pPager->dbOrigSize );
40332 assert( pPager->dbOrigSize==pPager->dbFileSize );
40333 assert( pPager->dbOrigSize==pPager->dbHintSize );
40334 assert( pPager->setMaster==0 );
40335 break;
40337 case PAGER_WRITER_CACHEMOD:
40338 assert( p->eLock!=UNKNOWN_LOCK );
40339 assert( pPager->errCode==SQLITE_OK );
40340 if( !pagerUseWal(pPager) ){
40341 /* It is possible that if journal_mode=wal here that neither the
40342 ** journal file nor the WAL file are open. This happens during
40343 ** a rollback transaction that switches from journal_mode=off
40344 ** to journal_mode=wal.
40346 assert( p->eLock>=RESERVED_LOCK );
40347 assert( isOpen(p->jfd)
40348 || p->journalMode==PAGER_JOURNALMODE_OFF
40349 || p->journalMode==PAGER_JOURNALMODE_WAL
40352 assert( pPager->dbOrigSize==pPager->dbFileSize );
40353 assert( pPager->dbOrigSize==pPager->dbHintSize );
40354 break;
40356 case PAGER_WRITER_DBMOD:
40357 assert( p->eLock==EXCLUSIVE_LOCK );
40358 assert( pPager->errCode==SQLITE_OK );
40359 assert( !pagerUseWal(pPager) );
40360 assert( p->eLock>=EXCLUSIVE_LOCK );
40361 assert( isOpen(p->jfd)
40362 || p->journalMode==PAGER_JOURNALMODE_OFF
40363 || p->journalMode==PAGER_JOURNALMODE_WAL
40365 assert( pPager->dbOrigSize<=pPager->dbHintSize );
40366 break;
40368 case PAGER_WRITER_FINISHED:
40369 assert( p->eLock==EXCLUSIVE_LOCK );
40370 assert( pPager->errCode==SQLITE_OK );
40371 assert( !pagerUseWal(pPager) );
40372 assert( isOpen(p->jfd)
40373 || p->journalMode==PAGER_JOURNALMODE_OFF
40374 || p->journalMode==PAGER_JOURNALMODE_WAL
40376 break;
40378 case PAGER_ERROR:
40379 /* There must be at least one outstanding reference to the pager if
40380 ** in ERROR state. Otherwise the pager should have already dropped
40381 ** back to OPEN state.
40383 assert( pPager->errCode!=SQLITE_OK );
40384 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
40385 break;
40388 return 1;
40390 #endif /* ifndef NDEBUG */
40392 #ifdef SQLITE_DEBUG
40394 ** Return a pointer to a human readable string in a static buffer
40395 ** containing the state of the Pager object passed as an argument. This
40396 ** is intended to be used within debuggers. For example, as an alternative
40397 ** to "print *pPager" in gdb:
40399 ** (gdb) printf "%s", print_pager_state(pPager)
40401 static char *print_pager_state(Pager *p){
40402 static char zRet[1024];
40404 sqlite3_snprintf(1024, zRet,
40405 "Filename: %s\n"
40406 "State: %s errCode=%d\n"
40407 "Lock: %s\n"
40408 "Locking mode: locking_mode=%s\n"
40409 "Journal mode: journal_mode=%s\n"
40410 "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
40411 "Journal: journalOff=%lld journalHdr=%lld\n"
40412 "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
40413 , p->zFilename
40414 , p->eState==PAGER_OPEN ? "OPEN" :
40415 p->eState==PAGER_READER ? "READER" :
40416 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
40417 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
40418 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
40419 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
40420 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
40421 , (int)p->errCode
40422 , p->eLock==NO_LOCK ? "NO_LOCK" :
40423 p->eLock==RESERVED_LOCK ? "RESERVED" :
40424 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
40425 p->eLock==SHARED_LOCK ? "SHARED" :
40426 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
40427 , p->exclusiveMode ? "exclusive" : "normal"
40428 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
40429 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
40430 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
40431 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
40432 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
40433 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
40434 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
40435 , p->journalOff, p->journalHdr
40436 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
40439 return zRet;
40441 #endif
40444 ** Return true if it is necessary to write page *pPg into the sub-journal.
40445 ** A page needs to be written into the sub-journal if there exists one
40446 ** or more open savepoints for which:
40448 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
40449 ** * The bit corresponding to the page-number is not set in
40450 ** PagerSavepoint.pInSavepoint.
40452 static int subjRequiresPage(PgHdr *pPg){
40453 Pager *pPager = pPg->pPager;
40454 PagerSavepoint *p;
40455 Pgno pgno = pPg->pgno;
40456 int i;
40457 for(i=0; i<pPager->nSavepoint; i++){
40458 p = &pPager->aSavepoint[i];
40459 if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
40460 return 1;
40463 return 0;
40467 ** Return true if the page is already in the journal file.
40469 static int pageInJournal(Pager *pPager, PgHdr *pPg){
40470 return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
40474 ** Read a 32-bit integer from the given file descriptor. Store the integer
40475 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
40476 ** error code is something goes wrong.
40478 ** All values are stored on disk as big-endian.
40480 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
40481 unsigned char ac[4];
40482 int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
40483 if( rc==SQLITE_OK ){
40484 *pRes = sqlite3Get4byte(ac);
40486 return rc;
40490 ** Write a 32-bit integer into a string buffer in big-endian byte order.
40492 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
40496 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
40497 ** on success or an error code is something goes wrong.
40499 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
40500 char ac[4];
40501 put32bits(ac, val);
40502 return sqlite3OsWrite(fd, ac, 4, offset);
40506 ** Unlock the database file to level eLock, which must be either NO_LOCK
40507 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
40508 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
40510 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40511 ** called, do not modify it. See the comment above the #define of
40512 ** UNKNOWN_LOCK for an explanation of this.
40514 static int pagerUnlockDb(Pager *pPager, int eLock){
40515 int rc = SQLITE_OK;
40517 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
40518 assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
40519 assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
40520 if( isOpen(pPager->fd) ){
40521 assert( pPager->eLock>=eLock );
40522 rc = sqlite3OsUnlock(pPager->fd, eLock);
40523 if( pPager->eLock!=UNKNOWN_LOCK ){
40524 pPager->eLock = (u8)eLock;
40526 IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
40528 return rc;
40532 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
40533 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
40534 ** Pager.eLock variable to the new locking state.
40536 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
40537 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
40538 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
40539 ** of this.
40541 static int pagerLockDb(Pager *pPager, int eLock){
40542 int rc = SQLITE_OK;
40544 assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
40545 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
40546 rc = sqlite3OsLock(pPager->fd, eLock);
40547 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
40548 pPager->eLock = (u8)eLock;
40549 IOTRACE(("LOCK %p %d\n", pPager, eLock))
40552 return rc;
40556 ** This function determines whether or not the atomic-write optimization
40557 ** can be used with this pager. The optimization can be used if:
40559 ** (a) the value returned by OsDeviceCharacteristics() indicates that
40560 ** a database page may be written atomically, and
40561 ** (b) the value returned by OsSectorSize() is less than or equal
40562 ** to the page size.
40564 ** The optimization is also always enabled for temporary files. It is
40565 ** an error to call this function if pPager is opened on an in-memory
40566 ** database.
40568 ** If the optimization cannot be used, 0 is returned. If it can be used,
40569 ** then the value returned is the size of the journal file when it
40570 ** contains rollback data for exactly one page.
40572 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
40573 static int jrnlBufferSize(Pager *pPager){
40574 assert( !MEMDB );
40575 if( !pPager->tempFile ){
40576 int dc; /* Device characteristics */
40577 int nSector; /* Sector size */
40578 int szPage; /* Page size */
40580 assert( isOpen(pPager->fd) );
40581 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
40582 nSector = pPager->sectorSize;
40583 szPage = pPager->pageSize;
40585 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
40586 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
40587 if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
40588 return 0;
40592 return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
40594 #endif
40597 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
40598 ** on the cache using a hash function. This is used for testing
40599 ** and debugging only.
40601 #ifdef SQLITE_CHECK_PAGES
40603 ** Return a 32-bit hash of the page data for pPage.
40605 static u32 pager_datahash(int nByte, unsigned char *pData){
40606 u32 hash = 0;
40607 int i;
40608 for(i=0; i<nByte; i++){
40609 hash = (hash*1039) + pData[i];
40611 return hash;
40613 static u32 pager_pagehash(PgHdr *pPage){
40614 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
40616 static void pager_set_pagehash(PgHdr *pPage){
40617 pPage->pageHash = pager_pagehash(pPage);
40621 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
40622 ** is defined, and NDEBUG is not defined, an assert() statement checks
40623 ** that the page is either dirty or still matches the calculated page-hash.
40625 #define CHECK_PAGE(x) checkPage(x)
40626 static void checkPage(PgHdr *pPg){
40627 Pager *pPager = pPg->pPager;
40628 assert( pPager->eState!=PAGER_ERROR );
40629 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
40632 #else
40633 #define pager_datahash(X,Y) 0
40634 #define pager_pagehash(X) 0
40635 #define pager_set_pagehash(X)
40636 #define CHECK_PAGE(x)
40637 #endif /* SQLITE_CHECK_PAGES */
40640 ** When this is called the journal file for pager pPager must be open.
40641 ** This function attempts to read a master journal file name from the
40642 ** end of the file and, if successful, copies it into memory supplied
40643 ** by the caller. See comments above writeMasterJournal() for the format
40644 ** used to store a master journal file name at the end of a journal file.
40646 ** zMaster must point to a buffer of at least nMaster bytes allocated by
40647 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
40648 ** enough space to write the master journal name). If the master journal
40649 ** name in the journal is longer than nMaster bytes (including a
40650 ** nul-terminator), then this is handled as if no master journal name
40651 ** were present in the journal.
40653 ** If a master journal file name is present at the end of the journal
40654 ** file, then it is copied into the buffer pointed to by zMaster. A
40655 ** nul-terminator byte is appended to the buffer following the master
40656 ** journal file name.
40658 ** If it is determined that no master journal file name is present
40659 ** zMaster[0] is set to 0 and SQLITE_OK returned.
40661 ** If an error occurs while reading from the journal file, an SQLite
40662 ** error code is returned.
40664 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
40665 int rc; /* Return code */
40666 u32 len; /* Length in bytes of master journal name */
40667 i64 szJ; /* Total size in bytes of journal file pJrnl */
40668 u32 cksum; /* MJ checksum value read from journal */
40669 u32 u; /* Unsigned loop counter */
40670 unsigned char aMagic[8]; /* A buffer to hold the magic header */
40671 zMaster[0] = '\0';
40673 if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
40674 || szJ<16
40675 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
40676 || len>=nMaster
40677 || len==0
40678 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
40679 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
40680 || memcmp(aMagic, aJournalMagic, 8)
40681 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
40683 return rc;
40686 /* See if the checksum matches the master journal name */
40687 for(u=0; u<len; u++){
40688 cksum -= zMaster[u];
40690 if( cksum ){
40691 /* If the checksum doesn't add up, then one or more of the disk sectors
40692 ** containing the master journal filename is corrupted. This means
40693 ** definitely roll back, so just return SQLITE_OK and report a (nul)
40694 ** master-journal filename.
40696 len = 0;
40698 zMaster[len] = '\0';
40700 return SQLITE_OK;
40704 ** Return the offset of the sector boundary at or immediately
40705 ** following the value in pPager->journalOff, assuming a sector
40706 ** size of pPager->sectorSize bytes.
40708 ** i.e for a sector size of 512:
40710 ** Pager.journalOff Return value
40711 ** ---------------------------------------
40712 ** 0 0
40713 ** 512 512
40714 ** 100 512
40715 ** 2000 2048
40718 static i64 journalHdrOffset(Pager *pPager){
40719 i64 offset = 0;
40720 i64 c = pPager->journalOff;
40721 if( c ){
40722 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
40724 assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
40725 assert( offset>=c );
40726 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
40727 return offset;
40731 ** The journal file must be open when this function is called.
40733 ** This function is a no-op if the journal file has not been written to
40734 ** within the current transaction (i.e. if Pager.journalOff==0).
40736 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
40737 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
40738 ** zero the 28-byte header at the start of the journal file. In either case,
40739 ** if the pager is not in no-sync mode, sync the journal file immediately
40740 ** after writing or truncating it.
40742 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
40743 ** following the truncation or zeroing described above the size of the
40744 ** journal file in bytes is larger than this value, then truncate the
40745 ** journal file to Pager.journalSizeLimit bytes. The journal file does
40746 ** not need to be synced following this operation.
40748 ** If an IO error occurs, abandon processing and return the IO error code.
40749 ** Otherwise, return SQLITE_OK.
40751 static int zeroJournalHdr(Pager *pPager, int doTruncate){
40752 int rc = SQLITE_OK; /* Return code */
40753 assert( isOpen(pPager->jfd) );
40754 if( pPager->journalOff ){
40755 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
40757 IOTRACE(("JZEROHDR %p\n", pPager))
40758 if( doTruncate || iLimit==0 ){
40759 rc = sqlite3OsTruncate(pPager->jfd, 0);
40760 }else{
40761 static const char zeroHdr[28] = {0};
40762 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
40764 if( rc==SQLITE_OK && !pPager->noSync ){
40765 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
40768 /* At this point the transaction is committed but the write lock
40769 ** is still held on the file. If there is a size limit configured for
40770 ** the persistent journal and the journal file currently consumes more
40771 ** space than that limit allows for, truncate it now. There is no need
40772 ** to sync the file following this operation.
40774 if( rc==SQLITE_OK && iLimit>0 ){
40775 i64 sz;
40776 rc = sqlite3OsFileSize(pPager->jfd, &sz);
40777 if( rc==SQLITE_OK && sz>iLimit ){
40778 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
40782 return rc;
40786 ** The journal file must be open when this routine is called. A journal
40787 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
40788 ** current location.
40790 ** The format for the journal header is as follows:
40791 ** - 8 bytes: Magic identifying journal format.
40792 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
40793 ** - 4 bytes: Random number used for page hash.
40794 ** - 4 bytes: Initial database page count.
40795 ** - 4 bytes: Sector size used by the process that wrote this journal.
40796 ** - 4 bytes: Database page size.
40798 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
40800 static int writeJournalHdr(Pager *pPager){
40801 int rc = SQLITE_OK; /* Return code */
40802 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
40803 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
40804 u32 nWrite; /* Bytes of header sector written */
40805 int ii; /* Loop counter */
40807 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
40809 if( nHeader>JOURNAL_HDR_SZ(pPager) ){
40810 nHeader = JOURNAL_HDR_SZ(pPager);
40813 /* If there are active savepoints and any of them were created
40814 ** since the most recent journal header was written, update the
40815 ** PagerSavepoint.iHdrOffset fields now.
40817 for(ii=0; ii<pPager->nSavepoint; ii++){
40818 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
40819 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
40823 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
40826 ** Write the nRec Field - the number of page records that follow this
40827 ** journal header. Normally, zero is written to this value at this time.
40828 ** After the records are added to the journal (and the journal synced,
40829 ** if in full-sync mode), the zero is overwritten with the true number
40830 ** of records (see syncJournal()).
40832 ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
40833 ** reading the journal this value tells SQLite to assume that the
40834 ** rest of the journal file contains valid page records. This assumption
40835 ** is dangerous, as if a failure occurred whilst writing to the journal
40836 ** file it may contain some garbage data. There are two scenarios
40837 ** where this risk can be ignored:
40839 ** * When the pager is in no-sync mode. Corruption can follow a
40840 ** power failure in this case anyway.
40842 ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
40843 ** that garbage data is never appended to the journal file.
40845 assert( isOpen(pPager->fd) || pPager->noSync );
40846 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
40847 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
40849 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
40850 put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
40851 }else{
40852 memset(zHeader, 0, sizeof(aJournalMagic)+4);
40855 /* The random check-hash initializer */
40856 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
40857 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
40858 /* The initial database size */
40859 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
40860 /* The assumed sector size for this process */
40861 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
40863 /* The page size */
40864 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
40866 /* Initializing the tail of the buffer is not necessary. Everything
40867 ** works find if the following memset() is omitted. But initializing
40868 ** the memory prevents valgrind from complaining, so we are willing to
40869 ** take the performance hit.
40871 memset(&zHeader[sizeof(aJournalMagic)+20], 0,
40872 nHeader-(sizeof(aJournalMagic)+20));
40874 /* In theory, it is only necessary to write the 28 bytes that the
40875 ** journal header consumes to the journal file here. Then increment the
40876 ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
40877 ** record is written to the following sector (leaving a gap in the file
40878 ** that will be implicitly filled in by the OS).
40880 ** However it has been discovered that on some systems this pattern can
40881 ** be significantly slower than contiguously writing data to the file,
40882 ** even if that means explicitly writing data to the block of
40883 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
40884 ** is done.
40886 ** The loop is required here in case the sector-size is larger than the
40887 ** database page size. Since the zHeader buffer is only Pager.pageSize
40888 ** bytes in size, more than one call to sqlite3OsWrite() may be required
40889 ** to populate the entire journal header sector.
40891 for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
40892 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
40893 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
40894 assert( pPager->journalHdr <= pPager->journalOff );
40895 pPager->journalOff += nHeader;
40898 return rc;
40902 ** The journal file must be open when this is called. A journal header file
40903 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
40904 ** file. The current location in the journal file is given by
40905 ** pPager->journalOff. See comments above function writeJournalHdr() for
40906 ** a description of the journal header format.
40908 ** If the header is read successfully, *pNRec is set to the number of
40909 ** page records following this header and *pDbSize is set to the size of the
40910 ** database before the transaction began, in pages. Also, pPager->cksumInit
40911 ** is set to the value read from the journal header. SQLITE_OK is returned
40912 ** in this case.
40914 ** If the journal header file appears to be corrupted, SQLITE_DONE is
40915 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
40916 ** cannot be read from the journal file an error code is returned.
40918 static int readJournalHdr(
40919 Pager *pPager, /* Pager object */
40920 int isHot,
40921 i64 journalSize, /* Size of the open journal file in bytes */
40922 u32 *pNRec, /* OUT: Value read from the nRec field */
40923 u32 *pDbSize /* OUT: Value of original database size field */
40925 int rc; /* Return code */
40926 unsigned char aMagic[8]; /* A buffer to hold the magic header */
40927 i64 iHdrOff; /* Offset of journal header being read */
40929 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
40931 /* Advance Pager.journalOff to the start of the next sector. If the
40932 ** journal file is too small for there to be a header stored at this
40933 ** point, return SQLITE_DONE.
40935 pPager->journalOff = journalHdrOffset(pPager);
40936 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
40937 return SQLITE_DONE;
40939 iHdrOff = pPager->journalOff;
40941 /* Read in the first 8 bytes of the journal header. If they do not match
40942 ** the magic string found at the start of each journal header, return
40943 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
40944 ** proceed.
40946 if( isHot || iHdrOff!=pPager->journalHdr ){
40947 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
40948 if( rc ){
40949 return rc;
40951 if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
40952 return SQLITE_DONE;
40956 /* Read the first three 32-bit fields of the journal header: The nRec
40957 ** field, the checksum-initializer and the database size at the start
40958 ** of the transaction. Return an error code if anything goes wrong.
40960 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
40961 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
40962 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
40964 return rc;
40967 if( pPager->journalOff==0 ){
40968 u32 iPageSize; /* Page-size field of journal header */
40969 u32 iSectorSize; /* Sector-size field of journal header */
40971 /* Read the page-size and sector-size journal header fields. */
40972 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
40973 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
40975 return rc;
40978 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
40979 ** journal header to zero. In this case, assume that the Pager.pageSize
40980 ** variable is already set to the correct page size.
40982 if( iPageSize==0 ){
40983 iPageSize = pPager->pageSize;
40986 /* Check that the values read from the page-size and sector-size fields
40987 ** are within range. To be 'in range', both values need to be a power
40988 ** of two greater than or equal to 512 or 32, and not greater than their
40989 ** respective compile time maximum limits.
40991 if( iPageSize<512 || iSectorSize<32
40992 || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
40993 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
40995 /* If the either the page-size or sector-size in the journal-header is
40996 ** invalid, then the process that wrote the journal-header must have
40997 ** crashed before the header was synced. In this case stop reading
40998 ** the journal file here.
41000 return SQLITE_DONE;
41003 /* Update the page-size to match the value read from the journal.
41004 ** Use a testcase() macro to make sure that malloc failure within
41005 ** PagerSetPagesize() is tested.
41007 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
41008 testcase( rc!=SQLITE_OK );
41010 /* Update the assumed sector-size to match the value used by
41011 ** the process that created this journal. If this journal was
41012 ** created by a process other than this one, then this routine
41013 ** is being called from within pager_playback(). The local value
41014 ** of Pager.sectorSize is restored at the end of that routine.
41016 pPager->sectorSize = iSectorSize;
41019 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
41020 return rc;
41025 ** Write the supplied master journal name into the journal file for pager
41026 ** pPager at the current location. The master journal name must be the last
41027 ** thing written to a journal file. If the pager is in full-sync mode, the
41028 ** journal file descriptor is advanced to the next sector boundary before
41029 ** anything is written. The format is:
41031 ** + 4 bytes: PAGER_MJ_PGNO.
41032 ** + N bytes: Master journal filename in utf-8.
41033 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
41034 ** + 4 bytes: Master journal name checksum.
41035 ** + 8 bytes: aJournalMagic[].
41037 ** The master journal page checksum is the sum of the bytes in the master
41038 ** journal name, where each byte is interpreted as a signed 8-bit integer.
41040 ** If zMaster is a NULL pointer (occurs for a single database transaction),
41041 ** this call is a no-op.
41043 static int writeMasterJournal(Pager *pPager, const char *zMaster){
41044 int rc; /* Return code */
41045 int nMaster; /* Length of string zMaster */
41046 i64 iHdrOff; /* Offset of header in journal file */
41047 i64 jrnlSize; /* Size of journal file on disk */
41048 u32 cksum = 0; /* Checksum of string zMaster */
41050 assert( pPager->setMaster==0 );
41051 assert( !pagerUseWal(pPager) );
41053 if( !zMaster
41054 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
41055 || pPager->journalMode==PAGER_JOURNALMODE_OFF
41057 return SQLITE_OK;
41059 pPager->setMaster = 1;
41060 assert( isOpen(pPager->jfd) );
41061 assert( pPager->journalHdr <= pPager->journalOff );
41063 /* Calculate the length in bytes and the checksum of zMaster */
41064 for(nMaster=0; zMaster[nMaster]; nMaster++){
41065 cksum += zMaster[nMaster];
41068 /* If in full-sync mode, advance to the next disk sector before writing
41069 ** the master journal name. This is in case the previous page written to
41070 ** the journal has already been synced.
41072 if( pPager->fullSync ){
41073 pPager->journalOff = journalHdrOffset(pPager);
41075 iHdrOff = pPager->journalOff;
41077 /* Write the master journal data to the end of the journal file. If
41078 ** an error occurs, return the error code to the caller.
41080 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
41081 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
41082 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
41083 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
41084 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
41086 return rc;
41088 pPager->journalOff += (nMaster+20);
41090 /* If the pager is in peristent-journal mode, then the physical
41091 ** journal-file may extend past the end of the master-journal name
41092 ** and 8 bytes of magic data just written to the file. This is
41093 ** dangerous because the code to rollback a hot-journal file
41094 ** will not be able to find the master-journal name to determine
41095 ** whether or not the journal is hot.
41097 ** Easiest thing to do in this scenario is to truncate the journal
41098 ** file to the required size.
41100 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
41101 && jrnlSize>pPager->journalOff
41103 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
41105 return rc;
41109 ** Find a page in the hash table given its page number. Return
41110 ** a pointer to the page or NULL if the requested page is not
41111 ** already in memory.
41113 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
41114 PgHdr *p = 0; /* Return value */
41116 /* It is not possible for a call to PcacheFetch() with createFlag==0 to
41117 ** fail, since no attempt to allocate dynamic memory will be made.
41119 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
41120 return p;
41124 ** Discard the entire contents of the in-memory page-cache.
41126 static void pager_reset(Pager *pPager){
41127 sqlite3BackupRestart(pPager->pBackup);
41128 sqlite3PcacheClear(pPager->pPCache);
41132 ** Free all structures in the Pager.aSavepoint[] array and set both
41133 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
41134 ** if it is open and the pager is not in exclusive mode.
41136 static void releaseAllSavepoints(Pager *pPager){
41137 int ii; /* Iterator for looping through Pager.aSavepoint */
41138 for(ii=0; ii<pPager->nSavepoint; ii++){
41139 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
41141 if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
41142 sqlite3OsClose(pPager->sjfd);
41144 sqlite3_free(pPager->aSavepoint);
41145 pPager->aSavepoint = 0;
41146 pPager->nSavepoint = 0;
41147 pPager->nSubRec = 0;
41151 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
41152 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
41153 ** or SQLITE_NOMEM if a malloc failure occurs.
41155 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
41156 int ii; /* Loop counter */
41157 int rc = SQLITE_OK; /* Result code */
41159 for(ii=0; ii<pPager->nSavepoint; ii++){
41160 PagerSavepoint *p = &pPager->aSavepoint[ii];
41161 if( pgno<=p->nOrig ){
41162 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
41163 testcase( rc==SQLITE_NOMEM );
41164 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
41167 return rc;
41171 ** This function is a no-op if the pager is in exclusive mode and not
41172 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
41173 ** state.
41175 ** If the pager is not in exclusive-access mode, the database file is
41176 ** completely unlocked. If the file is unlocked and the file-system does
41177 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
41178 ** closed (if it is open).
41180 ** If the pager is in ERROR state when this function is called, the
41181 ** contents of the pager cache are discarded before switching back to
41182 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
41183 ** or not, any journal file left in the file-system will be treated
41184 ** as a hot-journal and rolled back the next time a read-transaction
41185 ** is opened (by this or by any other connection).
41187 static void pager_unlock(Pager *pPager){
41189 assert( pPager->eState==PAGER_READER
41190 || pPager->eState==PAGER_OPEN
41191 || pPager->eState==PAGER_ERROR
41194 sqlite3BitvecDestroy(pPager->pInJournal);
41195 pPager->pInJournal = 0;
41196 releaseAllSavepoints(pPager);
41198 if( pagerUseWal(pPager) ){
41199 assert( !isOpen(pPager->jfd) );
41200 sqlite3WalEndReadTransaction(pPager->pWal);
41201 pPager->eState = PAGER_OPEN;
41202 }else if( !pPager->exclusiveMode ){
41203 int rc; /* Error code returned by pagerUnlockDb() */
41204 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
41206 /* If the operating system support deletion of open files, then
41207 ** close the journal file when dropping the database lock. Otherwise
41208 ** another connection with journal_mode=delete might delete the file
41209 ** out from under us.
41211 assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
41212 assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
41213 assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
41214 assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
41215 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
41216 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
41217 if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
41218 || 1!=(pPager->journalMode & 5)
41220 sqlite3OsClose(pPager->jfd);
41223 /* If the pager is in the ERROR state and the call to unlock the database
41224 ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
41225 ** above the #define for UNKNOWN_LOCK for an explanation of why this
41226 ** is necessary.
41228 rc = pagerUnlockDb(pPager, NO_LOCK);
41229 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
41230 pPager->eLock = UNKNOWN_LOCK;
41233 /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
41234 ** without clearing the error code. This is intentional - the error
41235 ** code is cleared and the cache reset in the block below.
41237 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
41238 pPager->changeCountDone = 0;
41239 pPager->eState = PAGER_OPEN;
41242 /* If Pager.errCode is set, the contents of the pager cache cannot be
41243 ** trusted. Now that there are no outstanding references to the pager,
41244 ** it can safely move back to PAGER_OPEN state. This happens in both
41245 ** normal and exclusive-locking mode.
41247 if( pPager->errCode ){
41248 assert( !MEMDB );
41249 pager_reset(pPager);
41250 pPager->changeCountDone = pPager->tempFile;
41251 pPager->eState = PAGER_OPEN;
41252 pPager->errCode = SQLITE_OK;
41253 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
41256 pPager->journalOff = 0;
41257 pPager->journalHdr = 0;
41258 pPager->setMaster = 0;
41262 ** This function is called whenever an IOERR or FULL error that requires
41263 ** the pager to transition into the ERROR state may ahve occurred.
41264 ** The first argument is a pointer to the pager structure, the second
41265 ** the error-code about to be returned by a pager API function. The
41266 ** value returned is a copy of the second argument to this function.
41268 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
41269 ** IOERR sub-codes, the pager enters the ERROR state and the error code
41270 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
41271 ** all major API calls on the Pager will immediately return Pager.errCode.
41273 ** The ERROR state indicates that the contents of the pager-cache
41274 ** cannot be trusted. This state can be cleared by completely discarding
41275 ** the contents of the pager-cache. If a transaction was active when
41276 ** the persistent error occurred, then the rollback journal may need
41277 ** to be replayed to restore the contents of the database file (as if
41278 ** it were a hot-journal).
41280 static int pager_error(Pager *pPager, int rc){
41281 int rc2 = rc & 0xff;
41282 assert( rc==SQLITE_OK || !MEMDB );
41283 assert(
41284 pPager->errCode==SQLITE_FULL ||
41285 pPager->errCode==SQLITE_OK ||
41286 (pPager->errCode & 0xff)==SQLITE_IOERR
41288 if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
41289 pPager->errCode = rc;
41290 pPager->eState = PAGER_ERROR;
41292 return rc;
41295 static int pager_truncate(Pager *pPager, Pgno nPage);
41298 ** This routine ends a transaction. A transaction is usually ended by
41299 ** either a COMMIT or a ROLLBACK operation. This routine may be called
41300 ** after rollback of a hot-journal, or if an error occurs while opening
41301 ** the journal file or writing the very first journal-header of a
41302 ** database transaction.
41304 ** This routine is never called in PAGER_ERROR state. If it is called
41305 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
41306 ** exclusive than a RESERVED lock, it is a no-op.
41308 ** Otherwise, any active savepoints are released.
41310 ** If the journal file is open, then it is "finalized". Once a journal
41311 ** file has been finalized it is not possible to use it to roll back a
41312 ** transaction. Nor will it be considered to be a hot-journal by this
41313 ** or any other database connection. Exactly how a journal is finalized
41314 ** depends on whether or not the pager is running in exclusive mode and
41315 ** the current journal-mode (Pager.journalMode value), as follows:
41317 ** journalMode==MEMORY
41318 ** Journal file descriptor is simply closed. This destroys an
41319 ** in-memory journal.
41321 ** journalMode==TRUNCATE
41322 ** Journal file is truncated to zero bytes in size.
41324 ** journalMode==PERSIST
41325 ** The first 28 bytes of the journal file are zeroed. This invalidates
41326 ** the first journal header in the file, and hence the entire journal
41327 ** file. An invalid journal file cannot be rolled back.
41329 ** journalMode==DELETE
41330 ** The journal file is closed and deleted using sqlite3OsDelete().
41332 ** If the pager is running in exclusive mode, this method of finalizing
41333 ** the journal file is never used. Instead, if the journalMode is
41334 ** DELETE and the pager is in exclusive mode, the method described under
41335 ** journalMode==PERSIST is used instead.
41337 ** After the journal is finalized, the pager moves to PAGER_READER state.
41338 ** If running in non-exclusive rollback mode, the lock on the file is
41339 ** downgraded to a SHARED_LOCK.
41341 ** SQLITE_OK is returned if no error occurs. If an error occurs during
41342 ** any of the IO operations to finalize the journal file or unlock the
41343 ** database then the IO error code is returned to the user. If the
41344 ** operation to finalize the journal file fails, then the code still
41345 ** tries to unlock the database file if not in exclusive mode. If the
41346 ** unlock operation fails as well, then the first error code related
41347 ** to the first error encountered (the journal finalization one) is
41348 ** returned.
41350 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
41351 int rc = SQLITE_OK; /* Error code from journal finalization operation */
41352 int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
41354 /* Do nothing if the pager does not have an open write transaction
41355 ** or at least a RESERVED lock. This function may be called when there
41356 ** is no write-transaction active but a RESERVED or greater lock is
41357 ** held under two circumstances:
41359 ** 1. After a successful hot-journal rollback, it is called with
41360 ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
41362 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
41363 ** lock switches back to locking_mode=normal and then executes a
41364 ** read-transaction, this function is called with eState==PAGER_READER
41365 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
41367 assert( assert_pager_state(pPager) );
41368 assert( pPager->eState!=PAGER_ERROR );
41369 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
41370 return SQLITE_OK;
41373 releaseAllSavepoints(pPager);
41374 assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
41375 if( isOpen(pPager->jfd) ){
41376 assert( !pagerUseWal(pPager) );
41378 /* Finalize the journal file. */
41379 if( sqlite3IsMemJournal(pPager->jfd) ){
41380 assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
41381 sqlite3OsClose(pPager->jfd);
41382 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
41383 if( pPager->journalOff==0 ){
41384 rc = SQLITE_OK;
41385 }else{
41386 rc = sqlite3OsTruncate(pPager->jfd, 0);
41388 pPager->journalOff = 0;
41389 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
41390 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
41392 rc = zeroJournalHdr(pPager, hasMaster);
41393 pPager->journalOff = 0;
41394 }else{
41395 /* This branch may be executed with Pager.journalMode==MEMORY if
41396 ** a hot-journal was just rolled back. In this case the journal
41397 ** file should be closed and deleted. If this connection writes to
41398 ** the database file, it will do so using an in-memory journal.
41400 int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
41401 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
41402 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
41403 || pPager->journalMode==PAGER_JOURNALMODE_WAL
41405 sqlite3OsClose(pPager->jfd);
41406 if( bDelete ){
41407 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
41412 #ifdef SQLITE_CHECK_PAGES
41413 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
41414 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
41415 PgHdr *p = pager_lookup(pPager, 1);
41416 if( p ){
41417 p->pageHash = 0;
41418 sqlite3PagerUnrefNotNull(p);
41421 #endif
41423 sqlite3BitvecDestroy(pPager->pInJournal);
41424 pPager->pInJournal = 0;
41425 pPager->nRec = 0;
41426 sqlite3PcacheCleanAll(pPager->pPCache);
41427 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
41429 if( pagerUseWal(pPager) ){
41430 /* Drop the WAL write-lock, if any. Also, if the connection was in
41431 ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
41432 ** lock held on the database file.
41434 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
41435 assert( rc2==SQLITE_OK );
41436 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
41437 /* This branch is taken when committing a transaction in rollback-journal
41438 ** mode if the database file on disk is larger than the database image.
41439 ** At this point the journal has been finalized and the transaction
41440 ** successfully committed, but the EXCLUSIVE lock is still held on the
41441 ** file. So it is safe to truncate the database file to its minimum
41442 ** required size. */
41443 assert( pPager->eLock==EXCLUSIVE_LOCK );
41444 rc = pager_truncate(pPager, pPager->dbSize);
41447 if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
41448 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
41449 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
41452 if( !pPager->exclusiveMode
41453 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
41455 rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
41456 pPager->changeCountDone = 0;
41458 pPager->eState = PAGER_READER;
41459 pPager->setMaster = 0;
41461 return (rc==SQLITE_OK?rc2:rc);
41465 ** Execute a rollback if a transaction is active and unlock the
41466 ** database file.
41468 ** If the pager has already entered the ERROR state, do not attempt
41469 ** the rollback at this time. Instead, pager_unlock() is called. The
41470 ** call to pager_unlock() will discard all in-memory pages, unlock
41471 ** the database file and move the pager back to OPEN state. If this
41472 ** means that there is a hot-journal left in the file-system, the next
41473 ** connection to obtain a shared lock on the pager (which may be this one)
41474 ** will roll it back.
41476 ** If the pager has not already entered the ERROR state, but an IO or
41477 ** malloc error occurs during a rollback, then this will itself cause
41478 ** the pager to enter the ERROR state. Which will be cleared by the
41479 ** call to pager_unlock(), as described above.
41481 static void pagerUnlockAndRollback(Pager *pPager){
41482 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
41483 assert( assert_pager_state(pPager) );
41484 if( pPager->eState>=PAGER_WRITER_LOCKED ){
41485 sqlite3BeginBenignMalloc();
41486 sqlite3PagerRollback(pPager);
41487 sqlite3EndBenignMalloc();
41488 }else if( !pPager->exclusiveMode ){
41489 assert( pPager->eState==PAGER_READER );
41490 pager_end_transaction(pPager, 0, 0);
41493 pager_unlock(pPager);
41497 ** Parameter aData must point to a buffer of pPager->pageSize bytes
41498 ** of data. Compute and return a checksum based ont the contents of the
41499 ** page of data and the current value of pPager->cksumInit.
41501 ** This is not a real checksum. It is really just the sum of the
41502 ** random initial value (pPager->cksumInit) and every 200th byte
41503 ** of the page data, starting with byte offset (pPager->pageSize%200).
41504 ** Each byte is interpreted as an 8-bit unsigned integer.
41506 ** Changing the formula used to compute this checksum results in an
41507 ** incompatible journal file format.
41509 ** If journal corruption occurs due to a power failure, the most likely
41510 ** scenario is that one end or the other of the record will be changed.
41511 ** It is much less likely that the two ends of the journal record will be
41512 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
41513 ** though fast and simple, catches the mostly likely kind of corruption.
41515 static u32 pager_cksum(Pager *pPager, const u8 *aData){
41516 u32 cksum = pPager->cksumInit; /* Checksum value to return */
41517 int i = pPager->pageSize-200; /* Loop counter */
41518 while( i>0 ){
41519 cksum += aData[i];
41520 i -= 200;
41522 return cksum;
41526 ** Report the current page size and number of reserved bytes back
41527 ** to the codec.
41529 #ifdef SQLITE_HAS_CODEC
41530 static void pagerReportSize(Pager *pPager){
41531 if( pPager->xCodecSizeChng ){
41532 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
41533 (int)pPager->nReserve);
41536 #else
41537 # define pagerReportSize(X) /* No-op if we do not support a codec */
41538 #endif
41541 ** Read a single page from either the journal file (if isMainJrnl==1) or
41542 ** from the sub-journal (if isMainJrnl==0) and playback that page.
41543 ** The page begins at offset *pOffset into the file. The *pOffset
41544 ** value is increased to the start of the next page in the journal.
41546 ** The main rollback journal uses checksums - the statement journal does
41547 ** not.
41549 ** If the page number of the page record read from the (sub-)journal file
41550 ** is greater than the current value of Pager.dbSize, then playback is
41551 ** skipped and SQLITE_OK is returned.
41553 ** If pDone is not NULL, then it is a record of pages that have already
41554 ** been played back. If the page at *pOffset has already been played back
41555 ** (if the corresponding pDone bit is set) then skip the playback.
41556 ** Make sure the pDone bit corresponding to the *pOffset page is set
41557 ** prior to returning.
41559 ** If the page record is successfully read from the (sub-)journal file
41560 ** and played back, then SQLITE_OK is returned. If an IO error occurs
41561 ** while reading the record from the (sub-)journal file or while writing
41562 ** to the database file, then the IO error code is returned. If data
41563 ** is successfully read from the (sub-)journal file but appears to be
41564 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
41565 ** two circumstances:
41567 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
41568 ** * If the record is being rolled back from the main journal file
41569 ** and the checksum field does not match the record content.
41571 ** Neither of these two scenarios are possible during a savepoint rollback.
41573 ** If this is a savepoint rollback, then memory may have to be dynamically
41574 ** allocated by this function. If this is the case and an allocation fails,
41575 ** SQLITE_NOMEM is returned.
41577 static int pager_playback_one_page(
41578 Pager *pPager, /* The pager being played back */
41579 i64 *pOffset, /* Offset of record to playback */
41580 Bitvec *pDone, /* Bitvec of pages already played back */
41581 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
41582 int isSavepnt /* True for a savepoint rollback */
41584 int rc;
41585 PgHdr *pPg; /* An existing page in the cache */
41586 Pgno pgno; /* The page number of a page in journal */
41587 u32 cksum; /* Checksum used for sanity checking */
41588 char *aData; /* Temporary storage for the page */
41589 sqlite3_file *jfd; /* The file descriptor for the journal file */
41590 int isSynced; /* True if journal page is synced */
41592 assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
41593 assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
41594 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
41595 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
41597 aData = pPager->pTmpSpace;
41598 assert( aData ); /* Temp storage must have already been allocated */
41599 assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
41601 /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
41602 ** or savepoint rollback done at the request of the caller) or this is
41603 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
41604 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
41605 ** only reads from the main journal, not the sub-journal.
41607 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
41608 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
41610 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
41612 /* Read the page number and page data from the journal or sub-journal
41613 ** file. Return an error code to the caller if an IO error occurs.
41615 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
41616 rc = read32bits(jfd, *pOffset, &pgno);
41617 if( rc!=SQLITE_OK ) return rc;
41618 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
41619 if( rc!=SQLITE_OK ) return rc;
41620 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
41622 /* Sanity checking on the page. This is more important that I originally
41623 ** thought. If a power failure occurs while the journal is being written,
41624 ** it could cause invalid data to be written into the journal. We need to
41625 ** detect this invalid data (with high probability) and ignore it.
41627 if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
41628 assert( !isSavepnt );
41629 return SQLITE_DONE;
41631 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
41632 return SQLITE_OK;
41634 if( isMainJrnl ){
41635 rc = read32bits(jfd, (*pOffset)-4, &cksum);
41636 if( rc ) return rc;
41637 if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
41638 return SQLITE_DONE;
41642 /* If this page has already been played by before during the current
41643 ** rollback, then don't bother to play it back again.
41645 if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
41646 return rc;
41649 /* When playing back page 1, restore the nReserve setting
41651 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
41652 pPager->nReserve = ((u8*)aData)[20];
41653 pagerReportSize(pPager);
41656 /* If the pager is in CACHEMOD state, then there must be a copy of this
41657 ** page in the pager cache. In this case just update the pager cache,
41658 ** not the database file. The page is left marked dirty in this case.
41660 ** An exception to the above rule: If the database is in no-sync mode
41661 ** and a page is moved during an incremental vacuum then the page may
41662 ** not be in the pager cache. Later: if a malloc() or IO error occurs
41663 ** during a Movepage() call, then the page may not be in the cache
41664 ** either. So the condition described in the above paragraph is not
41665 ** assert()able.
41667 ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
41668 ** pager cache if it exists and the main file. The page is then marked
41669 ** not dirty. Since this code is only executed in PAGER_OPEN state for
41670 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
41671 ** if the pager is in OPEN state.
41673 ** Ticket #1171: The statement journal might contain page content that is
41674 ** different from the page content at the start of the transaction.
41675 ** This occurs when a page is changed prior to the start of a statement
41676 ** then changed again within the statement. When rolling back such a
41677 ** statement we must not write to the original database unless we know
41678 ** for certain that original page contents are synced into the main rollback
41679 ** journal. Otherwise, a power loss might leave modified data in the
41680 ** database file without an entry in the rollback journal that can
41681 ** restore the database to its original form. Two conditions must be
41682 ** met before writing to the database files. (1) the database must be
41683 ** locked. (2) we know that the original page content is fully synced
41684 ** in the main journal either because the page is not in cache or else
41685 ** the page is marked as needSync==0.
41687 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
41688 ** is possible to fail a statement on a database that does not yet exist.
41689 ** Do not attempt to write if database file has never been opened.
41691 if( pagerUseWal(pPager) ){
41692 pPg = 0;
41693 }else{
41694 pPg = pager_lookup(pPager, pgno);
41696 assert( pPg || !MEMDB );
41697 assert( pPager->eState!=PAGER_OPEN || pPg==0 );
41698 PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
41699 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
41700 (isMainJrnl?"main-journal":"sub-journal")
41702 if( isMainJrnl ){
41703 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
41704 }else{
41705 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
41707 if( isOpen(pPager->fd)
41708 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41709 && isSynced
41711 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
41712 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
41713 assert( !pagerUseWal(pPager) );
41714 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
41715 if( pgno>pPager->dbFileSize ){
41716 pPager->dbFileSize = pgno;
41718 if( pPager->pBackup ){
41719 CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
41720 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
41721 CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
41723 }else if( !isMainJrnl && pPg==0 ){
41724 /* If this is a rollback of a savepoint and data was not written to
41725 ** the database and the page is not in-memory, there is a potential
41726 ** problem. When the page is next fetched by the b-tree layer, it
41727 ** will be read from the database file, which may or may not be
41728 ** current.
41730 ** There are a couple of different ways this can happen. All are quite
41731 ** obscure. When running in synchronous mode, this can only happen
41732 ** if the page is on the free-list at the start of the transaction, then
41733 ** populated, then moved using sqlite3PagerMovepage().
41735 ** The solution is to add an in-memory page to the cache containing
41736 ** the data just read from the sub-journal. Mark the page as dirty
41737 ** and if the pager requires a journal-sync, then mark the page as
41738 ** requiring a journal-sync before it is written.
41740 assert( isSavepnt );
41741 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
41742 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
41743 rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
41744 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
41745 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
41746 if( rc!=SQLITE_OK ) return rc;
41747 pPg->flags &= ~PGHDR_NEED_READ;
41748 sqlite3PcacheMakeDirty(pPg);
41750 if( pPg ){
41751 /* No page should ever be explicitly rolled back that is in use, except
41752 ** for page 1 which is held in use in order to keep the lock on the
41753 ** database active. However such a page may be rolled back as a result
41754 ** of an internal error resulting in an automatic call to
41755 ** sqlite3PagerRollback().
41757 void *pData;
41758 pData = pPg->pData;
41759 memcpy(pData, (u8*)aData, pPager->pageSize);
41760 pPager->xReiniter(pPg);
41761 if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
41762 /* If the contents of this page were just restored from the main
41763 ** journal file, then its content must be as they were when the
41764 ** transaction was first opened. In this case we can mark the page
41765 ** as clean, since there will be no need to write it out to the
41766 ** database.
41768 ** There is one exception to this rule. If the page is being rolled
41769 ** back as part of a savepoint (or statement) rollback from an
41770 ** unsynced portion of the main journal file, then it is not safe
41771 ** to mark the page as clean. This is because marking the page as
41772 ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
41773 ** already in the journal file (recorded in Pager.pInJournal) and
41774 ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
41775 ** again within this transaction, it will be marked as dirty but
41776 ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
41777 ** be written out into the database file before its journal file
41778 ** segment is synced. If a crash occurs during or following this,
41779 ** database corruption may ensue.
41781 assert( !pagerUseWal(pPager) );
41782 sqlite3PcacheMakeClean(pPg);
41784 pager_set_pagehash(pPg);
41786 /* If this was page 1, then restore the value of Pager.dbFileVers.
41787 ** Do this before any decoding. */
41788 if( pgno==1 ){
41789 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
41792 /* Decode the page just read from disk */
41793 CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
41794 sqlite3PcacheRelease(pPg);
41796 return rc;
41800 ** Parameter zMaster is the name of a master journal file. A single journal
41801 ** file that referred to the master journal file has just been rolled back.
41802 ** This routine checks if it is possible to delete the master journal file,
41803 ** and does so if it is.
41805 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
41806 ** available for use within this function.
41808 ** When a master journal file is created, it is populated with the names
41809 ** of all of its child journals, one after another, formatted as utf-8
41810 ** encoded text. The end of each child journal file is marked with a
41811 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
41812 ** file for a transaction involving two databases might be:
41814 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
41816 ** A master journal file may only be deleted once all of its child
41817 ** journals have been rolled back.
41819 ** This function reads the contents of the master-journal file into
41820 ** memory and loops through each of the child journal names. For
41821 ** each child journal, it checks if:
41823 ** * if the child journal exists, and if so
41824 ** * if the child journal contains a reference to master journal
41825 ** file zMaster
41827 ** If a child journal can be found that matches both of the criteria
41828 ** above, this function returns without doing anything. Otherwise, if
41829 ** no such child journal can be found, file zMaster is deleted from
41830 ** the file-system using sqlite3OsDelete().
41832 ** If an IO error within this function, an error code is returned. This
41833 ** function allocates memory by calling sqlite3Malloc(). If an allocation
41834 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
41835 ** occur, SQLITE_OK is returned.
41837 ** TODO: This function allocates a single block of memory to load
41838 ** the entire contents of the master journal file. This could be
41839 ** a couple of kilobytes or so - potentially larger than the page
41840 ** size.
41842 static int pager_delmaster(Pager *pPager, const char *zMaster){
41843 sqlite3_vfs *pVfs = pPager->pVfs;
41844 int rc; /* Return code */
41845 sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
41846 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
41847 char *zMasterJournal = 0; /* Contents of master journal file */
41848 i64 nMasterJournal; /* Size of master journal file */
41849 char *zJournal; /* Pointer to one journal within MJ file */
41850 char *zMasterPtr; /* Space to hold MJ filename from a journal file */
41851 int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
41853 /* Allocate space for both the pJournal and pMaster file descriptors.
41854 ** If successful, open the master journal file for reading.
41856 pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
41857 pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
41858 if( !pMaster ){
41859 rc = SQLITE_NOMEM;
41860 }else{
41861 const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
41862 rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
41864 if( rc!=SQLITE_OK ) goto delmaster_out;
41866 /* Load the entire master journal file into space obtained from
41867 ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
41868 ** sufficient space (in zMasterPtr) to hold the names of master
41869 ** journal files extracted from regular rollback-journals.
41871 rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
41872 if( rc!=SQLITE_OK ) goto delmaster_out;
41873 nMasterPtr = pVfs->mxPathname+1;
41874 zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
41875 if( !zMasterJournal ){
41876 rc = SQLITE_NOMEM;
41877 goto delmaster_out;
41879 zMasterPtr = &zMasterJournal[nMasterJournal+1];
41880 rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
41881 if( rc!=SQLITE_OK ) goto delmaster_out;
41882 zMasterJournal[nMasterJournal] = 0;
41884 zJournal = zMasterJournal;
41885 while( (zJournal-zMasterJournal)<nMasterJournal ){
41886 int exists;
41887 rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
41888 if( rc!=SQLITE_OK ){
41889 goto delmaster_out;
41891 if( exists ){
41892 /* One of the journals pointed to by the master journal exists.
41893 ** Open it and check if it points at the master journal. If
41894 ** so, return without deleting the master journal file.
41896 int c;
41897 int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
41898 rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
41899 if( rc!=SQLITE_OK ){
41900 goto delmaster_out;
41903 rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
41904 sqlite3OsClose(pJournal);
41905 if( rc!=SQLITE_OK ){
41906 goto delmaster_out;
41909 c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
41910 if( c ){
41911 /* We have a match. Do not delete the master journal file. */
41912 goto delmaster_out;
41915 zJournal += (sqlite3Strlen30(zJournal)+1);
41918 sqlite3OsClose(pMaster);
41919 rc = sqlite3OsDelete(pVfs, zMaster, 0);
41921 delmaster_out:
41922 sqlite3_free(zMasterJournal);
41923 if( pMaster ){
41924 sqlite3OsClose(pMaster);
41925 assert( !isOpen(pJournal) );
41926 sqlite3_free(pMaster);
41928 return rc;
41933 ** This function is used to change the actual size of the database
41934 ** file in the file-system. This only happens when committing a transaction,
41935 ** or rolling back a transaction (including rolling back a hot-journal).
41937 ** If the main database file is not open, or the pager is not in either
41938 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
41939 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
41940 ** If the file on disk is currently larger than nPage pages, then use the VFS
41941 ** xTruncate() method to truncate it.
41943 ** Or, it might might be the case that the file on disk is smaller than
41944 ** nPage pages. Some operating system implementations can get confused if
41945 ** you try to truncate a file to some size that is larger than it
41946 ** currently is, so detect this case and write a single zero byte to
41947 ** the end of the new file instead.
41949 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
41950 ** the database file, return the error code to the caller.
41952 static int pager_truncate(Pager *pPager, Pgno nPage){
41953 int rc = SQLITE_OK;
41954 assert( pPager->eState!=PAGER_ERROR );
41955 assert( pPager->eState!=PAGER_READER );
41957 if( isOpen(pPager->fd)
41958 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41960 i64 currentSize, newSize;
41961 int szPage = pPager->pageSize;
41962 assert( pPager->eLock==EXCLUSIVE_LOCK );
41963 /* TODO: Is it safe to use Pager.dbFileSize here? */
41964 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
41965 newSize = szPage*(i64)nPage;
41966 if( rc==SQLITE_OK && currentSize!=newSize ){
41967 if( currentSize>newSize ){
41968 rc = sqlite3OsTruncate(pPager->fd, newSize);
41969 }else if( (currentSize+szPage)<=newSize ){
41970 char *pTmp = pPager->pTmpSpace;
41971 memset(pTmp, 0, szPage);
41972 testcase( (newSize-szPage) == currentSize );
41973 testcase( (newSize-szPage) > currentSize );
41974 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
41976 if( rc==SQLITE_OK ){
41977 pPager->dbFileSize = nPage;
41981 return rc;
41985 ** Return a sanitized version of the sector-size of OS file pFile. The
41986 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
41988 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
41989 int iRet = sqlite3OsSectorSize(pFile);
41990 if( iRet<32 ){
41991 iRet = 512;
41992 }else if( iRet>MAX_SECTOR_SIZE ){
41993 assert( MAX_SECTOR_SIZE>=512 );
41994 iRet = MAX_SECTOR_SIZE;
41996 return iRet;
42000 ** Set the value of the Pager.sectorSize variable for the given
42001 ** pager based on the value returned by the xSectorSize method
42002 ** of the open database file. The sector size will be used used
42003 ** to determine the size and alignment of journal header and
42004 ** master journal pointers within created journal files.
42006 ** For temporary files the effective sector size is always 512 bytes.
42008 ** Otherwise, for non-temporary files, the effective sector size is
42009 ** the value returned by the xSectorSize() method rounded up to 32 if
42010 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
42011 ** is greater than MAX_SECTOR_SIZE.
42013 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
42014 ** the effective sector size to its minimum value (512). The purpose of
42015 ** pPager->sectorSize is to define the "blast radius" of bytes that
42016 ** might change if a crash occurs while writing to a single byte in
42017 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
42018 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
42019 ** size. For backwards compatibility of the rollback journal file format,
42020 ** we cannot reduce the effective sector size below 512.
42022 static void setSectorSize(Pager *pPager){
42023 assert( isOpen(pPager->fd) || pPager->tempFile );
42025 if( pPager->tempFile
42026 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
42027 SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
42029 /* Sector size doesn't matter for temporary files. Also, the file
42030 ** may not have been opened yet, in which case the OsSectorSize()
42031 ** call will segfault. */
42032 pPager->sectorSize = 512;
42033 }else{
42034 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
42039 ** Playback the journal and thus restore the database file to
42040 ** the state it was in before we started making changes.
42042 ** The journal file format is as follows:
42044 ** (1) 8 byte prefix. A copy of aJournalMagic[].
42045 ** (2) 4 byte big-endian integer which is the number of valid page records
42046 ** in the journal. If this value is 0xffffffff, then compute the
42047 ** number of page records from the journal size.
42048 ** (3) 4 byte big-endian integer which is the initial value for the
42049 ** sanity checksum.
42050 ** (4) 4 byte integer which is the number of pages to truncate the
42051 ** database to during a rollback.
42052 ** (5) 4 byte big-endian integer which is the sector size. The header
42053 ** is this many bytes in size.
42054 ** (6) 4 byte big-endian integer which is the page size.
42055 ** (7) zero padding out to the next sector size.
42056 ** (8) Zero or more pages instances, each as follows:
42057 ** + 4 byte page number.
42058 ** + pPager->pageSize bytes of data.
42059 ** + 4 byte checksum
42061 ** When we speak of the journal header, we mean the first 7 items above.
42062 ** Each entry in the journal is an instance of the 8th item.
42064 ** Call the value from the second bullet "nRec". nRec is the number of
42065 ** valid page entries in the journal. In most cases, you can compute the
42066 ** value of nRec from the size of the journal file. But if a power
42067 ** failure occurred while the journal was being written, it could be the
42068 ** case that the size of the journal file had already been increased but
42069 ** the extra entries had not yet made it safely to disk. In such a case,
42070 ** the value of nRec computed from the file size would be too large. For
42071 ** that reason, we always use the nRec value in the header.
42073 ** If the nRec value is 0xffffffff it means that nRec should be computed
42074 ** from the file size. This value is used when the user selects the
42075 ** no-sync option for the journal. A power failure could lead to corruption
42076 ** in this case. But for things like temporary table (which will be
42077 ** deleted when the power is restored) we don't care.
42079 ** If the file opened as the journal file is not a well-formed
42080 ** journal file then all pages up to the first corrupted page are rolled
42081 ** back (or no pages if the journal header is corrupted). The journal file
42082 ** is then deleted and SQLITE_OK returned, just as if no corruption had
42083 ** been encountered.
42085 ** If an I/O or malloc() error occurs, the journal-file is not deleted
42086 ** and an error code is returned.
42088 ** The isHot parameter indicates that we are trying to rollback a journal
42089 ** that might be a hot journal. Or, it could be that the journal is
42090 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
42091 ** If the journal really is hot, reset the pager cache prior rolling
42092 ** back any content. If the journal is merely persistent, no reset is
42093 ** needed.
42095 static int pager_playback(Pager *pPager, int isHot){
42096 sqlite3_vfs *pVfs = pPager->pVfs;
42097 i64 szJ; /* Size of the journal file in bytes */
42098 u32 nRec; /* Number of Records in the journal */
42099 u32 u; /* Unsigned loop counter */
42100 Pgno mxPg = 0; /* Size of the original file in pages */
42101 int rc; /* Result code of a subroutine */
42102 int res = 1; /* Value returned by sqlite3OsAccess() */
42103 char *zMaster = 0; /* Name of master journal file if any */
42104 int needPagerReset; /* True to reset page prior to first page rollback */
42105 int nPlayback = 0; /* Total number of pages restored from journal */
42107 /* Figure out how many records are in the journal. Abort early if
42108 ** the journal is empty.
42110 assert( isOpen(pPager->jfd) );
42111 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
42112 if( rc!=SQLITE_OK ){
42113 goto end_playback;
42116 /* Read the master journal name from the journal, if it is present.
42117 ** If a master journal file name is specified, but the file is not
42118 ** present on disk, then the journal is not hot and does not need to be
42119 ** played back.
42121 ** TODO: Technically the following is an error because it assumes that
42122 ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
42123 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
42124 ** mxPathname is 512, which is the same as the minimum allowable value
42125 ** for pageSize.
42127 zMaster = pPager->pTmpSpace;
42128 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42129 if( rc==SQLITE_OK && zMaster[0] ){
42130 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
42132 zMaster = 0;
42133 if( rc!=SQLITE_OK || !res ){
42134 goto end_playback;
42136 pPager->journalOff = 0;
42137 needPagerReset = isHot;
42139 /* This loop terminates either when a readJournalHdr() or
42140 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
42141 ** occurs.
42143 while( 1 ){
42144 /* Read the next journal header from the journal file. If there are
42145 ** not enough bytes left in the journal file for a complete header, or
42146 ** it is corrupted, then a process must have failed while writing it.
42147 ** This indicates nothing more needs to be rolled back.
42149 rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
42150 if( rc!=SQLITE_OK ){
42151 if( rc==SQLITE_DONE ){
42152 rc = SQLITE_OK;
42154 goto end_playback;
42157 /* If nRec is 0xffffffff, then this journal was created by a process
42158 ** working in no-sync mode. This means that the rest of the journal
42159 ** file consists of pages, there are no more journal headers. Compute
42160 ** the value of nRec based on this assumption.
42162 if( nRec==0xffffffff ){
42163 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
42164 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
42167 /* If nRec is 0 and this rollback is of a transaction created by this
42168 ** process and if this is the final header in the journal, then it means
42169 ** that this part of the journal was being filled but has not yet been
42170 ** synced to disk. Compute the number of pages based on the remaining
42171 ** size of the file.
42173 ** The third term of the test was added to fix ticket #2565.
42174 ** When rolling back a hot journal, nRec==0 always means that the next
42175 ** chunk of the journal contains zero pages to be rolled back. But
42176 ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
42177 ** the journal, it means that the journal might contain additional
42178 ** pages that need to be rolled back and that the number of pages
42179 ** should be computed based on the journal file size.
42181 if( nRec==0 && !isHot &&
42182 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
42183 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
42186 /* If this is the first header read from the journal, truncate the
42187 ** database file back to its original size.
42189 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
42190 rc = pager_truncate(pPager, mxPg);
42191 if( rc!=SQLITE_OK ){
42192 goto end_playback;
42194 pPager->dbSize = mxPg;
42197 /* Copy original pages out of the journal and back into the
42198 ** database file and/or page cache.
42200 for(u=0; u<nRec; u++){
42201 if( needPagerReset ){
42202 pager_reset(pPager);
42203 needPagerReset = 0;
42205 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
42206 if( rc==SQLITE_OK ){
42207 nPlayback++;
42208 }else{
42209 if( rc==SQLITE_DONE ){
42210 pPager->journalOff = szJ;
42211 break;
42212 }else if( rc==SQLITE_IOERR_SHORT_READ ){
42213 /* If the journal has been truncated, simply stop reading and
42214 ** processing the journal. This might happen if the journal was
42215 ** not completely written and synced prior to a crash. In that
42216 ** case, the database should have never been written in the
42217 ** first place so it is OK to simply abandon the rollback. */
42218 rc = SQLITE_OK;
42219 goto end_playback;
42220 }else{
42221 /* If we are unable to rollback, quit and return the error
42222 ** code. This will cause the pager to enter the error state
42223 ** so that no further harm will be done. Perhaps the next
42224 ** process to come along will be able to rollback the database.
42226 goto end_playback;
42231 /*NOTREACHED*/
42232 assert( 0 );
42234 end_playback:
42235 /* Following a rollback, the database file should be back in its original
42236 ** state prior to the start of the transaction, so invoke the
42237 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
42238 ** assertion that the transaction counter was modified.
42240 #ifdef SQLITE_DEBUG
42241 if( pPager->fd->pMethods ){
42242 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
42244 #endif
42246 /* If this playback is happening automatically as a result of an IO or
42247 ** malloc error that occurred after the change-counter was updated but
42248 ** before the transaction was committed, then the change-counter
42249 ** modification may just have been reverted. If this happens in exclusive
42250 ** mode, then subsequent transactions performed by the connection will not
42251 ** update the change-counter at all. This may lead to cache inconsistency
42252 ** problems for other processes at some point in the future. So, just
42253 ** in case this has happened, clear the changeCountDone flag now.
42255 pPager->changeCountDone = pPager->tempFile;
42257 if( rc==SQLITE_OK ){
42258 zMaster = pPager->pTmpSpace;
42259 rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
42260 testcase( rc!=SQLITE_OK );
42262 if( rc==SQLITE_OK
42263 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
42265 rc = sqlite3PagerSync(pPager, 0);
42267 if( rc==SQLITE_OK ){
42268 rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
42269 testcase( rc!=SQLITE_OK );
42271 if( rc==SQLITE_OK && zMaster[0] && res ){
42272 /* If there was a master journal and this routine will return success,
42273 ** see if it is possible to delete the master journal.
42275 rc = pager_delmaster(pPager, zMaster);
42276 testcase( rc!=SQLITE_OK );
42278 if( isHot && nPlayback ){
42279 sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
42280 nPlayback, pPager->zJournal);
42283 /* The Pager.sectorSize variable may have been updated while rolling
42284 ** back a journal created by a process with a different sector size
42285 ** value. Reset it to the correct value for this process.
42287 setSectorSize(pPager);
42288 return rc;
42293 ** Read the content for page pPg out of the database file and into
42294 ** pPg->pData. A shared lock or greater must be held on the database
42295 ** file before this function is called.
42297 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
42298 ** the value read from the database file.
42300 ** If an IO error occurs, then the IO error is returned to the caller.
42301 ** Otherwise, SQLITE_OK is returned.
42303 static int readDbPage(PgHdr *pPg, u32 iFrame){
42304 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
42305 Pgno pgno = pPg->pgno; /* Page number to read */
42306 int rc = SQLITE_OK; /* Return code */
42307 int pgsz = pPager->pageSize; /* Number of bytes to read */
42309 assert( pPager->eState>=PAGER_READER && !MEMDB );
42310 assert( isOpen(pPager->fd) );
42312 #ifndef SQLITE_OMIT_WAL
42313 if( iFrame ){
42314 /* Try to pull the page from the write-ahead log. */
42315 rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
42316 }else
42317 #endif
42319 i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
42320 rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
42321 if( rc==SQLITE_IOERR_SHORT_READ ){
42322 rc = SQLITE_OK;
42326 if( pgno==1 ){
42327 if( rc ){
42328 /* If the read is unsuccessful, set the dbFileVers[] to something
42329 ** that will never be a valid file version. dbFileVers[] is a copy
42330 ** of bytes 24..39 of the database. Bytes 28..31 should always be
42331 ** zero or the size of the database in page. Bytes 32..35 and 35..39
42332 ** should be page numbers which are never 0xffffffff. So filling
42333 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
42335 ** For an encrypted database, the situation is more complex: bytes
42336 ** 24..39 of the database are white noise. But the probability of
42337 ** white noising equaling 16 bytes of 0xff is vanishingly small so
42338 ** we should still be ok.
42340 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
42341 }else{
42342 u8 *dbFileVers = &((u8*)pPg->pData)[24];
42343 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
42346 CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
42348 PAGER_INCR(sqlite3_pager_readdb_count);
42349 PAGER_INCR(pPager->nRead);
42350 IOTRACE(("PGIN %p %d\n", pPager, pgno));
42351 PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
42352 PAGERID(pPager), pgno, pager_pagehash(pPg)));
42354 return rc;
42358 ** Update the value of the change-counter at offsets 24 and 92 in
42359 ** the header and the sqlite version number at offset 96.
42361 ** This is an unconditional update. See also the pager_incr_changecounter()
42362 ** routine which only updates the change-counter if the update is actually
42363 ** needed, as determined by the pPager->changeCountDone state variable.
42365 static void pager_write_changecounter(PgHdr *pPg){
42366 u32 change_counter;
42368 /* Increment the value just read and write it back to byte 24. */
42369 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
42370 put32bits(((char*)pPg->pData)+24, change_counter);
42372 /* Also store the SQLite version number in bytes 96..99 and in
42373 ** bytes 92..95 store the change counter for which the version number
42374 ** is valid. */
42375 put32bits(((char*)pPg->pData)+92, change_counter);
42376 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
42379 #ifndef SQLITE_OMIT_WAL
42381 ** This function is invoked once for each page that has already been
42382 ** written into the log file when a WAL transaction is rolled back.
42383 ** Parameter iPg is the page number of said page. The pCtx argument
42384 ** is actually a pointer to the Pager structure.
42386 ** If page iPg is present in the cache, and has no outstanding references,
42387 ** it is discarded. Otherwise, if there are one or more outstanding
42388 ** references, the page content is reloaded from the database. If the
42389 ** attempt to reload content from the database is required and fails,
42390 ** return an SQLite error code. Otherwise, SQLITE_OK.
42392 static int pagerUndoCallback(void *pCtx, Pgno iPg){
42393 int rc = SQLITE_OK;
42394 Pager *pPager = (Pager *)pCtx;
42395 PgHdr *pPg;
42397 assert( pagerUseWal(pPager) );
42398 pPg = sqlite3PagerLookup(pPager, iPg);
42399 if( pPg ){
42400 if( sqlite3PcachePageRefcount(pPg)==1 ){
42401 sqlite3PcacheDrop(pPg);
42402 }else{
42403 u32 iFrame = 0;
42404 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
42405 if( rc==SQLITE_OK ){
42406 rc = readDbPage(pPg, iFrame);
42408 if( rc==SQLITE_OK ){
42409 pPager->xReiniter(pPg);
42411 sqlite3PagerUnrefNotNull(pPg);
42415 /* Normally, if a transaction is rolled back, any backup processes are
42416 ** updated as data is copied out of the rollback journal and into the
42417 ** database. This is not generally possible with a WAL database, as
42418 ** rollback involves simply truncating the log file. Therefore, if one
42419 ** or more frames have already been written to the log (and therefore
42420 ** also copied into the backup databases) as part of this transaction,
42421 ** the backups must be restarted.
42423 sqlite3BackupRestart(pPager->pBackup);
42425 return rc;
42429 ** This function is called to rollback a transaction on a WAL database.
42431 static int pagerRollbackWal(Pager *pPager){
42432 int rc; /* Return Code */
42433 PgHdr *pList; /* List of dirty pages to revert */
42435 /* For all pages in the cache that are currently dirty or have already
42436 ** been written (but not committed) to the log file, do one of the
42437 ** following:
42439 ** + Discard the cached page (if refcount==0), or
42440 ** + Reload page content from the database (if refcount>0).
42442 pPager->dbSize = pPager->dbOrigSize;
42443 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
42444 pList = sqlite3PcacheDirtyList(pPager->pPCache);
42445 while( pList && rc==SQLITE_OK ){
42446 PgHdr *pNext = pList->pDirty;
42447 rc = pagerUndoCallback((void *)pPager, pList->pgno);
42448 pList = pNext;
42451 return rc;
42455 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
42456 ** the contents of the list of pages headed by pList (connected by pDirty),
42457 ** this function notifies any active backup processes that the pages have
42458 ** changed.
42460 ** The list of pages passed into this routine is always sorted by page number.
42461 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
42463 static int pagerWalFrames(
42464 Pager *pPager, /* Pager object */
42465 PgHdr *pList, /* List of frames to log */
42466 Pgno nTruncate, /* Database size after this commit */
42467 int isCommit /* True if this is a commit */
42469 int rc; /* Return code */
42470 int nList; /* Number of pages in pList */
42471 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
42472 PgHdr *p; /* For looping over pages */
42473 #endif
42475 assert( pPager->pWal );
42476 assert( pList );
42477 #ifdef SQLITE_DEBUG
42478 /* Verify that the page list is in accending order */
42479 for(p=pList; p && p->pDirty; p=p->pDirty){
42480 assert( p->pgno < p->pDirty->pgno );
42482 #endif
42484 assert( pList->pDirty==0 || isCommit );
42485 if( isCommit ){
42486 /* If a WAL transaction is being committed, there is no point in writing
42487 ** any pages with page numbers greater than nTruncate into the WAL file.
42488 ** They will never be read by any client. So remove them from the pDirty
42489 ** list here. */
42490 PgHdr *p;
42491 PgHdr **ppNext = &pList;
42492 nList = 0;
42493 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
42494 if( p->pgno<=nTruncate ){
42495 ppNext = &p->pDirty;
42496 nList++;
42499 assert( pList );
42500 }else{
42501 nList = 1;
42503 pPager->aStat[PAGER_STAT_WRITE] += nList;
42505 if( pList->pgno==1 ) pager_write_changecounter(pList);
42506 rc = sqlite3WalFrames(pPager->pWal,
42507 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
42509 if( rc==SQLITE_OK && pPager->pBackup ){
42510 PgHdr *p;
42511 for(p=pList; p; p=p->pDirty){
42512 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
42516 #ifdef SQLITE_CHECK_PAGES
42517 pList = sqlite3PcacheDirtyList(pPager->pPCache);
42518 for(p=pList; p; p=p->pDirty){
42519 pager_set_pagehash(p);
42521 #endif
42523 return rc;
42527 ** Begin a read transaction on the WAL.
42529 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
42530 ** makes a snapshot of the database at the current point in time and preserves
42531 ** that snapshot for use by the reader in spite of concurrently changes by
42532 ** other writers or checkpointers.
42534 static int pagerBeginReadTransaction(Pager *pPager){
42535 int rc; /* Return code */
42536 int changed = 0; /* True if cache must be reset */
42538 assert( pagerUseWal(pPager) );
42539 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42541 /* sqlite3WalEndReadTransaction() was not called for the previous
42542 ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
42543 ** are in locking_mode=NORMAL and EndRead() was previously called,
42544 ** the duplicate call is harmless.
42546 sqlite3WalEndReadTransaction(pPager->pWal);
42548 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
42549 if( rc!=SQLITE_OK || changed ){
42550 pager_reset(pPager);
42551 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
42554 return rc;
42556 #endif
42559 ** This function is called as part of the transition from PAGER_OPEN
42560 ** to PAGER_READER state to determine the size of the database file
42561 ** in pages (assuming the page size currently stored in Pager.pageSize).
42563 ** If no error occurs, SQLITE_OK is returned and the size of the database
42564 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
42565 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
42567 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
42568 Pgno nPage; /* Value to return via *pnPage */
42570 /* Query the WAL sub-system for the database size. The WalDbsize()
42571 ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
42572 ** if the database size is not available. The database size is not
42573 ** available from the WAL sub-system if the log file is empty or
42574 ** contains no valid committed transactions.
42576 assert( pPager->eState==PAGER_OPEN );
42577 assert( pPager->eLock>=SHARED_LOCK );
42578 nPage = sqlite3WalDbsize(pPager->pWal);
42580 /* If the database size was not available from the WAL sub-system,
42581 ** determine it based on the size of the database file. If the size
42582 ** of the database file is not an integer multiple of the page-size,
42583 ** round down to the nearest page. Except, any file larger than 0
42584 ** bytes in size is considered to contain at least one page.
42586 if( nPage==0 ){
42587 i64 n = 0; /* Size of db file in bytes */
42588 assert( isOpen(pPager->fd) || pPager->tempFile );
42589 if( isOpen(pPager->fd) ){
42590 int rc = sqlite3OsFileSize(pPager->fd, &n);
42591 if( rc!=SQLITE_OK ){
42592 return rc;
42595 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
42598 /* If the current number of pages in the file is greater than the
42599 ** configured maximum pager number, increase the allowed limit so
42600 ** that the file can be read.
42602 if( nPage>pPager->mxPgno ){
42603 pPager->mxPgno = (Pgno)nPage;
42606 *pnPage = nPage;
42607 return SQLITE_OK;
42610 #ifndef SQLITE_OMIT_WAL
42612 ** Check if the *-wal file that corresponds to the database opened by pPager
42613 ** exists if the database is not empy, or verify that the *-wal file does
42614 ** not exist (by deleting it) if the database file is empty.
42616 ** If the database is not empty and the *-wal file exists, open the pager
42617 ** in WAL mode. If the database is empty or if no *-wal file exists and
42618 ** if no error occurs, make sure Pager.journalMode is not set to
42619 ** PAGER_JOURNALMODE_WAL.
42621 ** Return SQLITE_OK or an error code.
42623 ** The caller must hold a SHARED lock on the database file to call this
42624 ** function. Because an EXCLUSIVE lock on the db file is required to delete
42625 ** a WAL on a none-empty database, this ensures there is no race condition
42626 ** between the xAccess() below and an xDelete() being executed by some
42627 ** other connection.
42629 static int pagerOpenWalIfPresent(Pager *pPager){
42630 int rc = SQLITE_OK;
42631 assert( pPager->eState==PAGER_OPEN );
42632 assert( pPager->eLock>=SHARED_LOCK );
42634 if( !pPager->tempFile ){
42635 int isWal; /* True if WAL file exists */
42636 Pgno nPage; /* Size of the database file */
42638 rc = pagerPagecount(pPager, &nPage);
42639 if( rc ) return rc;
42640 if( nPage==0 ){
42641 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
42642 if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
42643 isWal = 0;
42644 }else{
42645 rc = sqlite3OsAccess(
42646 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
42649 if( rc==SQLITE_OK ){
42650 if( isWal ){
42651 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
42652 rc = sqlite3PagerOpenWal(pPager, 0);
42653 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
42654 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
42658 return rc;
42660 #endif
42663 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
42664 ** the entire master journal file. The case pSavepoint==NULL occurs when
42665 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
42666 ** savepoint.
42668 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
42669 ** being rolled back), then the rollback consists of up to three stages,
42670 ** performed in the order specified:
42672 ** * Pages are played back from the main journal starting at byte
42673 ** offset PagerSavepoint.iOffset and continuing to
42674 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
42675 ** file if PagerSavepoint.iHdrOffset is zero.
42677 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
42678 ** back starting from the journal header immediately following
42679 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
42681 ** * Pages are then played back from the sub-journal file, starting
42682 ** with the PagerSavepoint.iSubRec and continuing to the end of
42683 ** the journal file.
42685 ** Throughout the rollback process, each time a page is rolled back, the
42686 ** corresponding bit is set in a bitvec structure (variable pDone in the
42687 ** implementation below). This is used to ensure that a page is only
42688 ** rolled back the first time it is encountered in either journal.
42690 ** If pSavepoint is NULL, then pages are only played back from the main
42691 ** journal file. There is no need for a bitvec in this case.
42693 ** In either case, before playback commences the Pager.dbSize variable
42694 ** is reset to the value that it held at the start of the savepoint
42695 ** (or transaction). No page with a page-number greater than this value
42696 ** is played back. If one is encountered it is simply skipped.
42698 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
42699 i64 szJ; /* Effective size of the main journal */
42700 i64 iHdrOff; /* End of first segment of main-journal records */
42701 int rc = SQLITE_OK; /* Return code */
42702 Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
42704 assert( pPager->eState!=PAGER_ERROR );
42705 assert( pPager->eState>=PAGER_WRITER_LOCKED );
42707 /* Allocate a bitvec to use to store the set of pages rolled back */
42708 if( pSavepoint ){
42709 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
42710 if( !pDone ){
42711 return SQLITE_NOMEM;
42715 /* Set the database size back to the value it was before the savepoint
42716 ** being reverted was opened.
42718 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
42719 pPager->changeCountDone = pPager->tempFile;
42721 if( !pSavepoint && pagerUseWal(pPager) ){
42722 return pagerRollbackWal(pPager);
42725 /* Use pPager->journalOff as the effective size of the main rollback
42726 ** journal. The actual file might be larger than this in
42727 ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
42728 ** past pPager->journalOff is off-limits to us.
42730 szJ = pPager->journalOff;
42731 assert( pagerUseWal(pPager)==0 || szJ==0 );
42733 /* Begin by rolling back records from the main journal starting at
42734 ** PagerSavepoint.iOffset and continuing to the next journal header.
42735 ** There might be records in the main journal that have a page number
42736 ** greater than the current database size (pPager->dbSize) but those
42737 ** will be skipped automatically. Pages are added to pDone as they
42738 ** are played back.
42740 if( pSavepoint && !pagerUseWal(pPager) ){
42741 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
42742 pPager->journalOff = pSavepoint->iOffset;
42743 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
42744 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42746 assert( rc!=SQLITE_DONE );
42747 }else{
42748 pPager->journalOff = 0;
42751 /* Continue rolling back records out of the main journal starting at
42752 ** the first journal header seen and continuing until the effective end
42753 ** of the main journal file. Continue to skip out-of-range pages and
42754 ** continue adding pages rolled back to pDone.
42756 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
42757 u32 ii; /* Loop counter */
42758 u32 nJRec = 0; /* Number of Journal Records */
42759 u32 dummy;
42760 rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
42761 assert( rc!=SQLITE_DONE );
42764 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
42765 ** test is related to ticket #2565. See the discussion in the
42766 ** pager_playback() function for additional information.
42768 if( nJRec==0
42769 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
42771 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
42773 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
42774 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
42776 assert( rc!=SQLITE_DONE );
42778 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
42780 /* Finally, rollback pages from the sub-journal. Page that were
42781 ** previously rolled back out of the main journal (and are hence in pDone)
42782 ** will be skipped. Out-of-range pages are also skipped.
42784 if( pSavepoint ){
42785 u32 ii; /* Loop counter */
42786 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
42788 if( pagerUseWal(pPager) ){
42789 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
42791 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
42792 assert( offset==(i64)ii*(4+pPager->pageSize) );
42793 rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
42795 assert( rc!=SQLITE_DONE );
42798 sqlite3BitvecDestroy(pDone);
42799 if( rc==SQLITE_OK ){
42800 pPager->journalOff = szJ;
42803 return rc;
42807 ** Change the maximum number of in-memory pages that are allowed.
42809 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
42810 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
42814 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
42816 static void pagerFixMaplimit(Pager *pPager){
42817 #if SQLITE_MAX_MMAP_SIZE>0
42818 sqlite3_file *fd = pPager->fd;
42819 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
42820 sqlite3_int64 sz;
42821 sz = pPager->szMmap;
42822 pPager->bUseFetch = (sz>0);
42823 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
42825 #endif
42829 ** Change the maximum size of any memory mapping made of the database file.
42831 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
42832 pPager->szMmap = szMmap;
42833 pagerFixMaplimit(pPager);
42837 ** Free as much memory as possible from the pager.
42839 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
42840 sqlite3PcacheShrink(pPager->pPCache);
42844 ** Adjust settings of the pager to those specified in the pgFlags parameter.
42846 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
42847 ** of the database to damage due to OS crashes or power failures by
42848 ** changing the number of syncs()s when writing the journals.
42849 ** There are three levels:
42851 ** OFF sqlite3OsSync() is never called. This is the default
42852 ** for temporary and transient files.
42854 ** NORMAL The journal is synced once before writes begin on the
42855 ** database. This is normally adequate protection, but
42856 ** it is theoretically possible, though very unlikely,
42857 ** that an inopertune power failure could leave the journal
42858 ** in a state which would cause damage to the database
42859 ** when it is rolled back.
42861 ** FULL The journal is synced twice before writes begin on the
42862 ** database (with some additional information - the nRec field
42863 ** of the journal header - being written in between the two
42864 ** syncs). If we assume that writing a
42865 ** single disk sector is atomic, then this mode provides
42866 ** assurance that the journal will not be corrupted to the
42867 ** point of causing damage to the database during rollback.
42869 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
42870 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
42871 ** prior to the start of checkpoint and that the database file is synced
42872 ** at the conclusion of the checkpoint if the entire content of the WAL
42873 ** was written back into the database. But no sync operations occur for
42874 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
42875 ** file is synced following each commit operation, in addition to the
42876 ** syncs associated with NORMAL.
42878 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
42879 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
42880 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
42881 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
42882 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
42883 ** synchronous=FULL versus synchronous=NORMAL setting determines when
42884 ** the xSync primitive is called and is relevant to all platforms.
42886 ** Numeric values associated with these states are OFF==1, NORMAL=2,
42887 ** and FULL=3.
42889 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
42890 SQLITE_PRIVATE void sqlite3PagerSetFlags(
42891 Pager *pPager, /* The pager to set safety level for */
42892 unsigned pgFlags /* Various flags */
42894 unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
42895 assert( level>=1 && level<=3 );
42896 pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
42897 pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
42898 if( pPager->noSync ){
42899 pPager->syncFlags = 0;
42900 pPager->ckptSyncFlags = 0;
42901 }else if( pgFlags & PAGER_FULLFSYNC ){
42902 pPager->syncFlags = SQLITE_SYNC_FULL;
42903 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
42904 }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
42905 pPager->syncFlags = SQLITE_SYNC_NORMAL;
42906 pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
42907 }else{
42908 pPager->syncFlags = SQLITE_SYNC_NORMAL;
42909 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
42911 pPager->walSyncFlags = pPager->syncFlags;
42912 if( pPager->fullSync ){
42913 pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
42915 if( pgFlags & PAGER_CACHESPILL ){
42916 pPager->doNotSpill &= ~SPILLFLAG_OFF;
42917 }else{
42918 pPager->doNotSpill |= SPILLFLAG_OFF;
42921 #endif
42924 ** The following global variable is incremented whenever the library
42925 ** attempts to open a temporary file. This information is used for
42926 ** testing and analysis only.
42928 #ifdef SQLITE_TEST
42929 SQLITE_API int sqlite3_opentemp_count = 0;
42930 #endif
42933 ** Open a temporary file.
42935 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
42936 ** or some other error code if we fail. The OS will automatically
42937 ** delete the temporary file when it is closed.
42939 ** The flags passed to the VFS layer xOpen() call are those specified
42940 ** by parameter vfsFlags ORed with the following:
42942 ** SQLITE_OPEN_READWRITE
42943 ** SQLITE_OPEN_CREATE
42944 ** SQLITE_OPEN_EXCLUSIVE
42945 ** SQLITE_OPEN_DELETEONCLOSE
42947 static int pagerOpentemp(
42948 Pager *pPager, /* The pager object */
42949 sqlite3_file *pFile, /* Write the file descriptor here */
42950 int vfsFlags /* Flags passed through to the VFS */
42952 int rc; /* Return code */
42954 #ifdef SQLITE_TEST
42955 sqlite3_opentemp_count++; /* Used for testing and analysis only */
42956 #endif
42958 vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
42959 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
42960 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
42961 assert( rc!=SQLITE_OK || isOpen(pFile) );
42962 return rc;
42966 ** Set the busy handler function.
42968 ** The pager invokes the busy-handler if sqlite3OsLock() returns
42969 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
42970 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
42971 ** lock. It does *not* invoke the busy handler when upgrading from
42972 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
42973 ** (which occurs during hot-journal rollback). Summary:
42975 ** Transition | Invokes xBusyHandler
42976 ** --------------------------------------------------------
42977 ** NO_LOCK -> SHARED_LOCK | Yes
42978 ** SHARED_LOCK -> RESERVED_LOCK | No
42979 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
42980 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
42982 ** If the busy-handler callback returns non-zero, the lock is
42983 ** retried. If it returns zero, then the SQLITE_BUSY error is
42984 ** returned to the caller of the pager API function.
42986 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
42987 Pager *pPager, /* Pager object */
42988 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
42989 void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
42991 pPager->xBusyHandler = xBusyHandler;
42992 pPager->pBusyHandlerArg = pBusyHandlerArg;
42994 if( isOpen(pPager->fd) ){
42995 void **ap = (void **)&pPager->xBusyHandler;
42996 assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
42997 assert( ap[1]==pBusyHandlerArg );
42998 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
43003 ** Change the page size used by the Pager object. The new page size
43004 ** is passed in *pPageSize.
43006 ** If the pager is in the error state when this function is called, it
43007 ** is a no-op. The value returned is the error state error code (i.e.
43008 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
43010 ** Otherwise, if all of the following are true:
43012 ** * the new page size (value of *pPageSize) is valid (a power
43013 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
43015 ** * there are no outstanding page references, and
43017 ** * the database is either not an in-memory database or it is
43018 ** an in-memory database that currently consists of zero pages.
43020 ** then the pager object page size is set to *pPageSize.
43022 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
43023 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
43024 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
43025 ** In all other cases, SQLITE_OK is returned.
43027 ** If the page size is not changed, either because one of the enumerated
43028 ** conditions above is not true, the pager was in error state when this
43029 ** function was called, or because the memory allocation attempt failed,
43030 ** then *pPageSize is set to the old, retained page size before returning.
43032 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
43033 int rc = SQLITE_OK;
43035 /* It is not possible to do a full assert_pager_state() here, as this
43036 ** function may be called from within PagerOpen(), before the state
43037 ** of the Pager object is internally consistent.
43039 ** At one point this function returned an error if the pager was in
43040 ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
43041 ** there is at least one outstanding page reference, this function
43042 ** is a no-op for that case anyhow.
43045 u32 pageSize = *pPageSize;
43046 assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
43047 if( (pPager->memDb==0 || pPager->dbSize==0)
43048 && sqlite3PcacheRefCount(pPager->pPCache)==0
43049 && pageSize && pageSize!=(u32)pPager->pageSize
43051 char *pNew = NULL; /* New temp space */
43052 i64 nByte = 0;
43054 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
43055 rc = sqlite3OsFileSize(pPager->fd, &nByte);
43057 if( rc==SQLITE_OK ){
43058 pNew = (char *)sqlite3PageMalloc(pageSize);
43059 if( !pNew ) rc = SQLITE_NOMEM;
43062 if( rc==SQLITE_OK ){
43063 pager_reset(pPager);
43064 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
43065 pPager->pageSize = pageSize;
43066 sqlite3PageFree(pPager->pTmpSpace);
43067 pPager->pTmpSpace = pNew;
43068 sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
43072 *pPageSize = pPager->pageSize;
43073 if( rc==SQLITE_OK ){
43074 if( nReserve<0 ) nReserve = pPager->nReserve;
43075 assert( nReserve>=0 && nReserve<1000 );
43076 pPager->nReserve = (i16)nReserve;
43077 pagerReportSize(pPager);
43078 pagerFixMaplimit(pPager);
43080 return rc;
43084 ** Return a pointer to the "temporary page" buffer held internally
43085 ** by the pager. This is a buffer that is big enough to hold the
43086 ** entire content of a database page. This buffer is used internally
43087 ** during rollback and will be overwritten whenever a rollback
43088 ** occurs. But other modules are free to use it too, as long as
43089 ** no rollbacks are happening.
43091 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
43092 return pPager->pTmpSpace;
43096 ** Attempt to set the maximum database page count if mxPage is positive.
43097 ** Make no changes if mxPage is zero or negative. And never reduce the
43098 ** maximum page count below the current size of the database.
43100 ** Regardless of mxPage, return the current maximum page count.
43102 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
43103 if( mxPage>0 ){
43104 pPager->mxPgno = mxPage;
43106 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
43107 assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
43108 return pPager->mxPgno;
43112 ** The following set of routines are used to disable the simulated
43113 ** I/O error mechanism. These routines are used to avoid simulated
43114 ** errors in places where we do not care about errors.
43116 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
43117 ** and generate no code.
43119 #ifdef SQLITE_TEST
43120 SQLITE_API extern int sqlite3_io_error_pending;
43121 SQLITE_API extern int sqlite3_io_error_hit;
43122 static int saved_cnt;
43123 void disable_simulated_io_errors(void){
43124 saved_cnt = sqlite3_io_error_pending;
43125 sqlite3_io_error_pending = -1;
43127 void enable_simulated_io_errors(void){
43128 sqlite3_io_error_pending = saved_cnt;
43130 #else
43131 # define disable_simulated_io_errors()
43132 # define enable_simulated_io_errors()
43133 #endif
43136 ** Read the first N bytes from the beginning of the file into memory
43137 ** that pDest points to.
43139 ** If the pager was opened on a transient file (zFilename==""), or
43140 ** opened on a file less than N bytes in size, the output buffer is
43141 ** zeroed and SQLITE_OK returned. The rationale for this is that this
43142 ** function is used to read database headers, and a new transient or
43143 ** zero sized database has a header than consists entirely of zeroes.
43145 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
43146 ** the error code is returned to the caller and the contents of the
43147 ** output buffer undefined.
43149 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
43150 int rc = SQLITE_OK;
43151 memset(pDest, 0, N);
43152 assert( isOpen(pPager->fd) || pPager->tempFile );
43154 /* This routine is only called by btree immediately after creating
43155 ** the Pager object. There has not been an opportunity to transition
43156 ** to WAL mode yet.
43158 assert( !pagerUseWal(pPager) );
43160 if( isOpen(pPager->fd) ){
43161 IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
43162 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
43163 if( rc==SQLITE_IOERR_SHORT_READ ){
43164 rc = SQLITE_OK;
43167 return rc;
43171 ** This function may only be called when a read-transaction is open on
43172 ** the pager. It returns the total number of pages in the database.
43174 ** However, if the file is between 1 and <page-size> bytes in size, then
43175 ** this is considered a 1 page file.
43177 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
43178 assert( pPager->eState>=PAGER_READER );
43179 assert( pPager->eState!=PAGER_WRITER_FINISHED );
43180 *pnPage = (int)pPager->dbSize;
43185 ** Try to obtain a lock of type locktype on the database file. If
43186 ** a similar or greater lock is already held, this function is a no-op
43187 ** (returning SQLITE_OK immediately).
43189 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
43190 ** the busy callback if the lock is currently not available. Repeat
43191 ** until the busy callback returns false or until the attempt to
43192 ** obtain the lock succeeds.
43194 ** Return SQLITE_OK on success and an error code if we cannot obtain
43195 ** the lock. If the lock is obtained successfully, set the Pager.state
43196 ** variable to locktype before returning.
43198 static int pager_wait_on_lock(Pager *pPager, int locktype){
43199 int rc; /* Return code */
43201 /* Check that this is either a no-op (because the requested lock is
43202 ** already held, or one of the transistions that the busy-handler
43203 ** may be invoked during, according to the comment above
43204 ** sqlite3PagerSetBusyhandler().
43206 assert( (pPager->eLock>=locktype)
43207 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
43208 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
43211 do {
43212 rc = pagerLockDb(pPager, locktype);
43213 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
43214 return rc;
43218 ** Function assertTruncateConstraint(pPager) checks that one of the
43219 ** following is true for all dirty pages currently in the page-cache:
43221 ** a) The page number is less than or equal to the size of the
43222 ** current database image, in pages, OR
43224 ** b) if the page content were written at this time, it would not
43225 ** be necessary to write the current content out to the sub-journal
43226 ** (as determined by function subjRequiresPage()).
43228 ** If the condition asserted by this function were not true, and the
43229 ** dirty page were to be discarded from the cache via the pagerStress()
43230 ** routine, pagerStress() would not write the current page content to
43231 ** the database file. If a savepoint transaction were rolled back after
43232 ** this happened, the correct behavior would be to restore the current
43233 ** content of the page. However, since this content is not present in either
43234 ** the database file or the portion of the rollback journal and
43235 ** sub-journal rolled back the content could not be restored and the
43236 ** database image would become corrupt. It is therefore fortunate that
43237 ** this circumstance cannot arise.
43239 #if defined(SQLITE_DEBUG)
43240 static void assertTruncateConstraintCb(PgHdr *pPg){
43241 assert( pPg->flags&PGHDR_DIRTY );
43242 assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
43244 static void assertTruncateConstraint(Pager *pPager){
43245 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
43247 #else
43248 # define assertTruncateConstraint(pPager)
43249 #endif
43252 ** Truncate the in-memory database file image to nPage pages. This
43253 ** function does not actually modify the database file on disk. It
43254 ** just sets the internal state of the pager object so that the
43255 ** truncation will be done when the current transaction is committed.
43257 ** This function is only called right before committing a transaction.
43258 ** Once this function has been called, the transaction must either be
43259 ** rolled back or committed. It is not safe to call this function and
43260 ** then continue writing to the database.
43262 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
43263 assert( pPager->dbSize>=nPage );
43264 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43265 pPager->dbSize = nPage;
43267 /* At one point the code here called assertTruncateConstraint() to
43268 ** ensure that all pages being truncated away by this operation are,
43269 ** if one or more savepoints are open, present in the savepoint
43270 ** journal so that they can be restored if the savepoint is rolled
43271 ** back. This is no longer necessary as this function is now only
43272 ** called right before committing a transaction. So although the
43273 ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
43274 ** they cannot be rolled back. So the assertTruncateConstraint() call
43275 ** is no longer correct. */
43280 ** This function is called before attempting a hot-journal rollback. It
43281 ** syncs the journal file to disk, then sets pPager->journalHdr to the
43282 ** size of the journal file so that the pager_playback() routine knows
43283 ** that the entire journal file has been synced.
43285 ** Syncing a hot-journal to disk before attempting to roll it back ensures
43286 ** that if a power-failure occurs during the rollback, the process that
43287 ** attempts rollback following system recovery sees the same journal
43288 ** content as this process.
43290 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
43291 ** an SQLite error code.
43293 static int pagerSyncHotJournal(Pager *pPager){
43294 int rc = SQLITE_OK;
43295 if( !pPager->noSync ){
43296 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
43298 if( rc==SQLITE_OK ){
43299 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
43301 return rc;
43305 ** Obtain a reference to a memory mapped page object for page number pgno.
43306 ** The new object will use the pointer pData, obtained from xFetch().
43307 ** If successful, set *ppPage to point to the new page reference
43308 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
43309 ** *ppPage to zero.
43311 ** Page references obtained by calling this function should be released
43312 ** by calling pagerReleaseMapPage().
43314 static int pagerAcquireMapPage(
43315 Pager *pPager, /* Pager object */
43316 Pgno pgno, /* Page number */
43317 void *pData, /* xFetch()'d data for this page */
43318 PgHdr **ppPage /* OUT: Acquired page object */
43320 PgHdr *p; /* Memory mapped page to return */
43322 if( pPager->pMmapFreelist ){
43323 *ppPage = p = pPager->pMmapFreelist;
43324 pPager->pMmapFreelist = p->pDirty;
43325 p->pDirty = 0;
43326 memset(p->pExtra, 0, pPager->nExtra);
43327 }else{
43328 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
43329 if( p==0 ){
43330 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
43331 return SQLITE_NOMEM;
43333 p->pExtra = (void *)&p[1];
43334 p->flags = PGHDR_MMAP;
43335 p->nRef = 1;
43336 p->pPager = pPager;
43339 assert( p->pExtra==(void *)&p[1] );
43340 assert( p->pPage==0 );
43341 assert( p->flags==PGHDR_MMAP );
43342 assert( p->pPager==pPager );
43343 assert( p->nRef==1 );
43345 p->pgno = pgno;
43346 p->pData = pData;
43347 pPager->nMmapOut++;
43349 return SQLITE_OK;
43353 ** Release a reference to page pPg. pPg must have been returned by an
43354 ** earlier call to pagerAcquireMapPage().
43356 static void pagerReleaseMapPage(PgHdr *pPg){
43357 Pager *pPager = pPg->pPager;
43358 pPager->nMmapOut--;
43359 pPg->pDirty = pPager->pMmapFreelist;
43360 pPager->pMmapFreelist = pPg;
43362 assert( pPager->fd->pMethods->iVersion>=3 );
43363 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
43367 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
43369 static void pagerFreeMapHdrs(Pager *pPager){
43370 PgHdr *p;
43371 PgHdr *pNext;
43372 for(p=pPager->pMmapFreelist; p; p=pNext){
43373 pNext = p->pDirty;
43374 sqlite3_free(p);
43380 ** Shutdown the page cache. Free all memory and close all files.
43382 ** If a transaction was in progress when this routine is called, that
43383 ** transaction is rolled back. All outstanding pages are invalidated
43384 ** and their memory is freed. Any attempt to use a page associated
43385 ** with this page cache after this function returns will likely
43386 ** result in a coredump.
43388 ** This function always succeeds. If a transaction is active an attempt
43389 ** is made to roll it back. If an error occurs during the rollback
43390 ** a hot journal may be left in the filesystem but no error is returned
43391 ** to the caller.
43393 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
43394 u8 *pTmp = (u8 *)pPager->pTmpSpace;
43396 assert( assert_pager_state(pPager) );
43397 disable_simulated_io_errors();
43398 sqlite3BeginBenignMalloc();
43399 pagerFreeMapHdrs(pPager);
43400 /* pPager->errCode = 0; */
43401 pPager->exclusiveMode = 0;
43402 #ifndef SQLITE_OMIT_WAL
43403 sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
43404 pPager->pWal = 0;
43405 #endif
43406 pager_reset(pPager);
43407 if( MEMDB ){
43408 pager_unlock(pPager);
43409 }else{
43410 /* If it is open, sync the journal file before calling UnlockAndRollback.
43411 ** If this is not done, then an unsynced portion of the open journal
43412 ** file may be played back into the database. If a power failure occurs
43413 ** while this is happening, the database could become corrupt.
43415 ** If an error occurs while trying to sync the journal, shift the pager
43416 ** into the ERROR state. This causes UnlockAndRollback to unlock the
43417 ** database and close the journal file without attempting to roll it
43418 ** back or finalize it. The next database user will have to do hot-journal
43419 ** rollback before accessing the database file.
43421 if( isOpen(pPager->jfd) ){
43422 pager_error(pPager, pagerSyncHotJournal(pPager));
43424 pagerUnlockAndRollback(pPager);
43426 sqlite3EndBenignMalloc();
43427 enable_simulated_io_errors();
43428 PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
43429 IOTRACE(("CLOSE %p\n", pPager))
43430 sqlite3OsClose(pPager->jfd);
43431 sqlite3OsClose(pPager->fd);
43432 sqlite3PageFree(pTmp);
43433 sqlite3PcacheClose(pPager->pPCache);
43435 #ifdef SQLITE_HAS_CODEC
43436 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43437 #endif
43439 assert( !pPager->aSavepoint && !pPager->pInJournal );
43440 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
43442 sqlite3_free(pPager);
43443 return SQLITE_OK;
43446 #if !defined(NDEBUG) || defined(SQLITE_TEST)
43448 ** Return the page number for page pPg.
43450 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
43451 return pPg->pgno;
43453 #endif
43456 ** Increment the reference count for page pPg.
43458 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
43459 sqlite3PcacheRef(pPg);
43463 ** Sync the journal. In other words, make sure all the pages that have
43464 ** been written to the journal have actually reached the surface of the
43465 ** disk and can be restored in the event of a hot-journal rollback.
43467 ** If the Pager.noSync flag is set, then this function is a no-op.
43468 ** Otherwise, the actions required depend on the journal-mode and the
43469 ** device characteristics of the file-system, as follows:
43471 ** * If the journal file is an in-memory journal file, no action need
43472 ** be taken.
43474 ** * Otherwise, if the device does not support the SAFE_APPEND property,
43475 ** then the nRec field of the most recently written journal header
43476 ** is updated to contain the number of journal records that have
43477 ** been written following it. If the pager is operating in full-sync
43478 ** mode, then the journal file is synced before this field is updated.
43480 ** * If the device does not support the SEQUENTIAL property, then
43481 ** journal file is synced.
43483 ** Or, in pseudo-code:
43485 ** if( NOT <in-memory journal> ){
43486 ** if( NOT SAFE_APPEND ){
43487 ** if( <full-sync mode> ) xSync(<journal file>);
43488 ** <update nRec field>
43489 ** }
43490 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
43491 ** }
43493 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
43494 ** page currently held in memory before returning SQLITE_OK. If an IO
43495 ** error is encountered, then the IO error code is returned to the caller.
43497 static int syncJournal(Pager *pPager, int newHdr){
43498 int rc; /* Return code */
43500 assert( pPager->eState==PAGER_WRITER_CACHEMOD
43501 || pPager->eState==PAGER_WRITER_DBMOD
43503 assert( assert_pager_state(pPager) );
43504 assert( !pagerUseWal(pPager) );
43506 rc = sqlite3PagerExclusiveLock(pPager);
43507 if( rc!=SQLITE_OK ) return rc;
43509 if( !pPager->noSync ){
43510 assert( !pPager->tempFile );
43511 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
43512 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43513 assert( isOpen(pPager->jfd) );
43515 if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43516 /* This block deals with an obscure problem. If the last connection
43517 ** that wrote to this database was operating in persistent-journal
43518 ** mode, then the journal file may at this point actually be larger
43519 ** than Pager.journalOff bytes. If the next thing in the journal
43520 ** file happens to be a journal-header (written as part of the
43521 ** previous connection's transaction), and a crash or power-failure
43522 ** occurs after nRec is updated but before this connection writes
43523 ** anything else to the journal file (or commits/rolls back its
43524 ** transaction), then SQLite may become confused when doing the
43525 ** hot-journal rollback following recovery. It may roll back all
43526 ** of this connections data, then proceed to rolling back the old,
43527 ** out-of-date data that follows it. Database corruption.
43529 ** To work around this, if the journal file does appear to contain
43530 ** a valid header following Pager.journalOff, then write a 0x00
43531 ** byte to the start of it to prevent it from being recognized.
43533 ** Variable iNextHdrOffset is set to the offset at which this
43534 ** problematic header will occur, if it exists. aMagic is used
43535 ** as a temporary buffer to inspect the first couple of bytes of
43536 ** the potential journal header.
43538 i64 iNextHdrOffset;
43539 u8 aMagic[8];
43540 u8 zHeader[sizeof(aJournalMagic)+4];
43542 memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
43543 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
43545 iNextHdrOffset = journalHdrOffset(pPager);
43546 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
43547 if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
43548 static const u8 zerobyte = 0;
43549 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
43551 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43552 return rc;
43555 /* Write the nRec value into the journal file header. If in
43556 ** full-synchronous mode, sync the journal first. This ensures that
43557 ** all data has really hit the disk before nRec is updated to mark
43558 ** it as a candidate for rollback.
43560 ** This is not required if the persistent media supports the
43561 ** SAFE_APPEND property. Because in this case it is not possible
43562 ** for garbage data to be appended to the file, the nRec field
43563 ** is populated with 0xFFFFFFFF when the journal header is written
43564 ** and never needs to be updated.
43566 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
43567 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43568 IOTRACE(("JSYNC %p\n", pPager))
43569 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
43570 if( rc!=SQLITE_OK ) return rc;
43572 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
43573 rc = sqlite3OsWrite(
43574 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
43576 if( rc!=SQLITE_OK ) return rc;
43578 if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
43579 PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
43580 IOTRACE(("JSYNC %p\n", pPager))
43581 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
43582 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
43584 if( rc!=SQLITE_OK ) return rc;
43587 pPager->journalHdr = pPager->journalOff;
43588 if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
43589 pPager->nRec = 0;
43590 rc = writeJournalHdr(pPager);
43591 if( rc!=SQLITE_OK ) return rc;
43593 }else{
43594 pPager->journalHdr = pPager->journalOff;
43598 /* Unless the pager is in noSync mode, the journal file was just
43599 ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
43600 ** all pages.
43602 sqlite3PcacheClearSyncFlags(pPager->pPCache);
43603 pPager->eState = PAGER_WRITER_DBMOD;
43604 assert( assert_pager_state(pPager) );
43605 return SQLITE_OK;
43609 ** The argument is the first in a linked list of dirty pages connected
43610 ** by the PgHdr.pDirty pointer. This function writes each one of the
43611 ** in-memory pages in the list to the database file. The argument may
43612 ** be NULL, representing an empty list. In this case this function is
43613 ** a no-op.
43615 ** The pager must hold at least a RESERVED lock when this function
43616 ** is called. Before writing anything to the database file, this lock
43617 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
43618 ** SQLITE_BUSY is returned and no data is written to the database file.
43620 ** If the pager is a temp-file pager and the actual file-system file
43621 ** is not yet open, it is created and opened before any data is
43622 ** written out.
43624 ** Once the lock has been upgraded and, if necessary, the file opened,
43625 ** the pages are written out to the database file in list order. Writing
43626 ** a page is skipped if it meets either of the following criteria:
43628 ** * The page number is greater than Pager.dbSize, or
43629 ** * The PGHDR_DONT_WRITE flag is set on the page.
43631 ** If writing out a page causes the database file to grow, Pager.dbFileSize
43632 ** is updated accordingly. If page 1 is written out, then the value cached
43633 ** in Pager.dbFileVers[] is updated to match the new value stored in
43634 ** the database file.
43636 ** If everything is successful, SQLITE_OK is returned. If an IO error
43637 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
43638 ** be obtained, SQLITE_BUSY is returned.
43640 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
43641 int rc = SQLITE_OK; /* Return code */
43643 /* This function is only called for rollback pagers in WRITER_DBMOD state. */
43644 assert( !pagerUseWal(pPager) );
43645 assert( pPager->eState==PAGER_WRITER_DBMOD );
43646 assert( pPager->eLock==EXCLUSIVE_LOCK );
43648 /* If the file is a temp-file has not yet been opened, open it now. It
43649 ** is not possible for rc to be other than SQLITE_OK if this branch
43650 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
43652 if( !isOpen(pPager->fd) ){
43653 assert( pPager->tempFile && rc==SQLITE_OK );
43654 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
43657 /* Before the first write, give the VFS a hint of what the final
43658 ** file size will be.
43660 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
43661 if( rc==SQLITE_OK
43662 && pPager->dbHintSize<pPager->dbSize
43663 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
43665 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
43666 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
43667 pPager->dbHintSize = pPager->dbSize;
43670 while( rc==SQLITE_OK && pList ){
43671 Pgno pgno = pList->pgno;
43673 /* If there are dirty pages in the page cache with page numbers greater
43674 ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
43675 ** make the file smaller (presumably by auto-vacuum code). Do not write
43676 ** any such pages to the file.
43678 ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
43679 ** set (set by sqlite3PagerDontWrite()).
43681 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
43682 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
43683 char *pData; /* Data to write */
43685 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
43686 if( pList->pgno==1 ) pager_write_changecounter(pList);
43688 /* Encode the database */
43689 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
43691 /* Write out the page data. */
43692 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
43694 /* If page 1 was just written, update Pager.dbFileVers to match
43695 ** the value now stored in the database file. If writing this
43696 ** page caused the database file to grow, update dbFileSize.
43698 if( pgno==1 ){
43699 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
43701 if( pgno>pPager->dbFileSize ){
43702 pPager->dbFileSize = pgno;
43704 pPager->aStat[PAGER_STAT_WRITE]++;
43706 /* Update any backup objects copying the contents of this pager. */
43707 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
43709 PAGERTRACE(("STORE %d page %d hash(%08x)\n",
43710 PAGERID(pPager), pgno, pager_pagehash(pList)));
43711 IOTRACE(("PGOUT %p %d\n", pPager, pgno));
43712 PAGER_INCR(sqlite3_pager_writedb_count);
43713 }else{
43714 PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
43716 pager_set_pagehash(pList);
43717 pList = pList->pDirty;
43720 return rc;
43724 ** Ensure that the sub-journal file is open. If it is already open, this
43725 ** function is a no-op.
43727 ** SQLITE_OK is returned if everything goes according to plan. An
43728 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
43729 ** fails.
43731 static int openSubJournal(Pager *pPager){
43732 int rc = SQLITE_OK;
43733 if( !isOpen(pPager->sjfd) ){
43734 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
43735 sqlite3MemJournalOpen(pPager->sjfd);
43736 }else{
43737 rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
43740 return rc;
43744 ** Append a record of the current state of page pPg to the sub-journal.
43745 ** It is the callers responsibility to use subjRequiresPage() to check
43746 ** that it is really required before calling this function.
43748 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
43749 ** for all open savepoints before returning.
43751 ** This function returns SQLITE_OK if everything is successful, an IO
43752 ** error code if the attempt to write to the sub-journal fails, or
43753 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
43754 ** bitvec.
43756 static int subjournalPage(PgHdr *pPg){
43757 int rc = SQLITE_OK;
43758 Pager *pPager = pPg->pPager;
43759 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43761 /* Open the sub-journal, if it has not already been opened */
43762 assert( pPager->useJournal );
43763 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
43764 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
43765 assert( pagerUseWal(pPager)
43766 || pageInJournal(pPager, pPg)
43767 || pPg->pgno>pPager->dbOrigSize
43769 rc = openSubJournal(pPager);
43771 /* If the sub-journal was opened successfully (or was already open),
43772 ** write the journal record into the file. */
43773 if( rc==SQLITE_OK ){
43774 void *pData = pPg->pData;
43775 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
43776 char *pData2;
43778 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43779 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
43780 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
43781 if( rc==SQLITE_OK ){
43782 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
43786 if( rc==SQLITE_OK ){
43787 pPager->nSubRec++;
43788 assert( pPager->nSavepoint>0 );
43789 rc = addToSavepointBitvecs(pPager, pPg->pgno);
43791 return rc;
43795 ** This function is called by the pcache layer when it has reached some
43796 ** soft memory limit. The first argument is a pointer to a Pager object
43797 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
43798 ** database). The second argument is a reference to a page that is
43799 ** currently dirty but has no outstanding references. The page
43800 ** is always associated with the Pager object passed as the first
43801 ** argument.
43803 ** The job of this function is to make pPg clean by writing its contents
43804 ** out to the database file, if possible. This may involve syncing the
43805 ** journal file.
43807 ** If successful, sqlite3PcacheMakeClean() is called on the page and
43808 ** SQLITE_OK returned. If an IO error occurs while trying to make the
43809 ** page clean, the IO error code is returned. If the page cannot be
43810 ** made clean for some other reason, but no error occurs, then SQLITE_OK
43811 ** is returned by sqlite3PcacheMakeClean() is not called.
43813 static int pagerStress(void *p, PgHdr *pPg){
43814 Pager *pPager = (Pager *)p;
43815 int rc = SQLITE_OK;
43817 assert( pPg->pPager==pPager );
43818 assert( pPg->flags&PGHDR_DIRTY );
43820 /* The doNotSpill NOSYNC bit is set during times when doing a sync of
43821 ** journal (and adding a new header) is not allowed. This occurs
43822 ** during calls to sqlite3PagerWrite() while trying to journal multiple
43823 ** pages belonging to the same sector.
43825 ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
43826 ** regardless of whether or not a sync is required. This is set during
43827 ** a rollback or by user request, respectively.
43829 ** Spilling is also prohibited when in an error state since that could
43830 ** lead to database corruption. In the current implementaton it
43831 ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
43832 ** while in the error state, hence it is impossible for this routine to
43833 ** be called in the error state. Nevertheless, we include a NEVER()
43834 ** test for the error state as a safeguard against future changes.
43836 if( NEVER(pPager->errCode) ) return SQLITE_OK;
43837 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
43838 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
43839 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
43840 if( pPager->doNotSpill
43841 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
43842 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
43844 return SQLITE_OK;
43847 pPg->pDirty = 0;
43848 if( pagerUseWal(pPager) ){
43849 /* Write a single frame for this page to the log. */
43850 if( subjRequiresPage(pPg) ){
43851 rc = subjournalPage(pPg);
43853 if( rc==SQLITE_OK ){
43854 rc = pagerWalFrames(pPager, pPg, 0, 0);
43856 }else{
43858 /* Sync the journal file if required. */
43859 if( pPg->flags&PGHDR_NEED_SYNC
43860 || pPager->eState==PAGER_WRITER_CACHEMOD
43862 rc = syncJournal(pPager, 1);
43865 /* If the page number of this page is larger than the current size of
43866 ** the database image, it may need to be written to the sub-journal.
43867 ** This is because the call to pager_write_pagelist() below will not
43868 ** actually write data to the file in this case.
43870 ** Consider the following sequence of events:
43872 ** BEGIN;
43873 ** <journal page X>
43874 ** <modify page X>
43875 ** SAVEPOINT sp;
43876 ** <shrink database file to Y pages>
43877 ** pagerStress(page X)
43878 ** ROLLBACK TO sp;
43880 ** If (X>Y), then when pagerStress is called page X will not be written
43881 ** out to the database file, but will be dropped from the cache. Then,
43882 ** following the "ROLLBACK TO sp" statement, reading page X will read
43883 ** data from the database file. This will be the copy of page X as it
43884 ** was when the transaction started, not as it was when "SAVEPOINT sp"
43885 ** was executed.
43887 ** The solution is to write the current data for page X into the
43888 ** sub-journal file now (if it is not already there), so that it will
43889 ** be restored to its current value when the "ROLLBACK TO sp" is
43890 ** executed.
43892 if( NEVER(
43893 rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
43894 ) ){
43895 rc = subjournalPage(pPg);
43898 /* Write the contents of the page out to the database file. */
43899 if( rc==SQLITE_OK ){
43900 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
43901 rc = pager_write_pagelist(pPager, pPg);
43905 /* Mark the page as clean. */
43906 if( rc==SQLITE_OK ){
43907 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
43908 sqlite3PcacheMakeClean(pPg);
43911 return pager_error(pPager, rc);
43916 ** Allocate and initialize a new Pager object and put a pointer to it
43917 ** in *ppPager. The pager should eventually be freed by passing it
43918 ** to sqlite3PagerClose().
43920 ** The zFilename argument is the path to the database file to open.
43921 ** If zFilename is NULL then a randomly-named temporary file is created
43922 ** and used as the file to be cached. Temporary files are be deleted
43923 ** automatically when they are closed. If zFilename is ":memory:" then
43924 ** all information is held in cache. It is never written to disk.
43925 ** This can be used to implement an in-memory database.
43927 ** The nExtra parameter specifies the number of bytes of space allocated
43928 ** along with each page reference. This space is available to the user
43929 ** via the sqlite3PagerGetExtra() API.
43931 ** The flags argument is used to specify properties that affect the
43932 ** operation of the pager. It should be passed some bitwise combination
43933 ** of the PAGER_* flags.
43935 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
43936 ** of the xOpen() method of the supplied VFS when opening files.
43938 ** If the pager object is allocated and the specified file opened
43939 ** successfully, SQLITE_OK is returned and *ppPager set to point to
43940 ** the new pager object. If an error occurs, *ppPager is set to NULL
43941 ** and error code returned. This function may return SQLITE_NOMEM
43942 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
43943 ** various SQLITE_IO_XXX errors.
43945 SQLITE_PRIVATE int sqlite3PagerOpen(
43946 sqlite3_vfs *pVfs, /* The virtual file system to use */
43947 Pager **ppPager, /* OUT: Return the Pager structure here */
43948 const char *zFilename, /* Name of the database file to open */
43949 int nExtra, /* Extra bytes append to each in-memory page */
43950 int flags, /* flags controlling this file */
43951 int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
43952 void (*xReinit)(DbPage*) /* Function to reinitialize pages */
43954 u8 *pPtr;
43955 Pager *pPager = 0; /* Pager object to allocate and return */
43956 int rc = SQLITE_OK; /* Return code */
43957 int tempFile = 0; /* True for temp files (incl. in-memory files) */
43958 int memDb = 0; /* True if this is an in-memory file */
43959 int readOnly = 0; /* True if this is a read-only file */
43960 int journalFileSize; /* Bytes to allocate for each journal fd */
43961 char *zPathname = 0; /* Full path to database file */
43962 int nPathname = 0; /* Number of bytes in zPathname */
43963 int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
43964 int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
43965 u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
43966 const char *zUri = 0; /* URI args to copy */
43967 int nUri = 0; /* Number of bytes of URI args at *zUri */
43969 /* Figure out how much space is required for each journal file-handle
43970 ** (there are two of them, the main journal and the sub-journal). This
43971 ** is the maximum space required for an in-memory journal file handle
43972 ** and a regular journal file-handle. Note that a "regular journal-handle"
43973 ** may be a wrapper capable of caching the first portion of the journal
43974 ** file in memory to implement the atomic-write optimization (see
43975 ** source file journal.c).
43977 if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
43978 journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
43979 }else{
43980 journalFileSize = ROUND8(sqlite3MemJournalSize());
43983 /* Set the output variable to NULL in case an error occurs. */
43984 *ppPager = 0;
43986 #ifndef SQLITE_OMIT_MEMORYDB
43987 if( flags & PAGER_MEMORY ){
43988 memDb = 1;
43989 if( zFilename && zFilename[0] ){
43990 zPathname = sqlite3DbStrDup(0, zFilename);
43991 if( zPathname==0 ) return SQLITE_NOMEM;
43992 nPathname = sqlite3Strlen30(zPathname);
43993 zFilename = 0;
43996 #endif
43998 /* Compute and store the full pathname in an allocated buffer pointed
43999 ** to by zPathname, length nPathname. Or, if this is a temporary file,
44000 ** leave both nPathname and zPathname set to 0.
44002 if( zFilename && zFilename[0] ){
44003 const char *z;
44004 nPathname = pVfs->mxPathname+1;
44005 zPathname = sqlite3DbMallocRaw(0, nPathname*2);
44006 if( zPathname==0 ){
44007 return SQLITE_NOMEM;
44009 zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
44010 rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
44011 nPathname = sqlite3Strlen30(zPathname);
44012 z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
44013 while( *z ){
44014 z += sqlite3Strlen30(z)+1;
44015 z += sqlite3Strlen30(z)+1;
44017 nUri = (int)(&z[1] - zUri);
44018 assert( nUri>=0 );
44019 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
44020 /* This branch is taken when the journal path required by
44021 ** the database being opened will be more than pVfs->mxPathname
44022 ** bytes in length. This means the database cannot be opened,
44023 ** as it will not be possible to open the journal file or even
44024 ** check for a hot-journal before reading.
44026 rc = SQLITE_CANTOPEN_BKPT;
44028 if( rc!=SQLITE_OK ){
44029 sqlite3DbFree(0, zPathname);
44030 return rc;
44034 /* Allocate memory for the Pager structure, PCache object, the
44035 ** three file descriptors, the database file name and the journal
44036 ** file name. The layout in memory is as follows:
44038 ** Pager object (sizeof(Pager) bytes)
44039 ** PCache object (sqlite3PcacheSize() bytes)
44040 ** Database file handle (pVfs->szOsFile bytes)
44041 ** Sub-journal file handle (journalFileSize bytes)
44042 ** Main journal file handle (journalFileSize bytes)
44043 ** Database file name (nPathname+1 bytes)
44044 ** Journal file name (nPathname+8+1 bytes)
44046 pPtr = (u8 *)sqlite3MallocZero(
44047 ROUND8(sizeof(*pPager)) + /* Pager structure */
44048 ROUND8(pcacheSize) + /* PCache object */
44049 ROUND8(pVfs->szOsFile) + /* The main db file */
44050 journalFileSize * 2 + /* The two journal files */
44051 nPathname + 1 + nUri + /* zFilename */
44052 nPathname + 8 + 2 /* zJournal */
44053 #ifndef SQLITE_OMIT_WAL
44054 + nPathname + 4 + 2 /* zWal */
44055 #endif
44057 assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
44058 if( !pPtr ){
44059 sqlite3DbFree(0, zPathname);
44060 return SQLITE_NOMEM;
44062 pPager = (Pager*)(pPtr);
44063 pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
44064 pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
44065 pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
44066 pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
44067 pPager->zFilename = (char*)(pPtr += journalFileSize);
44068 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
44070 /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
44071 if( zPathname ){
44072 assert( nPathname>0 );
44073 pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
44074 memcpy(pPager->zFilename, zPathname, nPathname);
44075 if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
44076 memcpy(pPager->zJournal, zPathname, nPathname);
44077 memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
44078 sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
44079 #ifndef SQLITE_OMIT_WAL
44080 pPager->zWal = &pPager->zJournal[nPathname+8+1];
44081 memcpy(pPager->zWal, zPathname, nPathname);
44082 memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
44083 sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
44084 #endif
44085 sqlite3DbFree(0, zPathname);
44087 pPager->pVfs = pVfs;
44088 pPager->vfsFlags = vfsFlags;
44090 /* Open the pager file.
44092 if( zFilename && zFilename[0] ){
44093 int fout = 0; /* VFS flags returned by xOpen() */
44094 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
44095 assert( !memDb );
44096 readOnly = (fout&SQLITE_OPEN_READONLY);
44098 /* If the file was successfully opened for read/write access,
44099 ** choose a default page size in case we have to create the
44100 ** database file. The default page size is the maximum of:
44102 ** + SQLITE_DEFAULT_PAGE_SIZE,
44103 ** + The value returned by sqlite3OsSectorSize()
44104 ** + The largest page size that can be written atomically.
44106 if( rc==SQLITE_OK && !readOnly ){
44107 setSectorSize(pPager);
44108 assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
44109 if( szPageDflt<pPager->sectorSize ){
44110 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
44111 szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
44112 }else{
44113 szPageDflt = (u32)pPager->sectorSize;
44116 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44118 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
44119 int ii;
44120 assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
44121 assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
44122 assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
44123 for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
44124 if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
44125 szPageDflt = ii;
44129 #endif
44131 }else{
44132 /* If a temporary file is requested, it is not opened immediately.
44133 ** In this case we accept the default page size and delay actually
44134 ** opening the file until the first call to OsWrite().
44136 ** This branch is also run for an in-memory database. An in-memory
44137 ** database is the same as a temp-file that is never written out to
44138 ** disk and uses an in-memory rollback journal.
44140 tempFile = 1;
44141 pPager->eState = PAGER_READER;
44142 pPager->eLock = EXCLUSIVE_LOCK;
44143 readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
44146 /* The following call to PagerSetPagesize() serves to set the value of
44147 ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
44149 if( rc==SQLITE_OK ){
44150 assert( pPager->memDb==0 );
44151 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
44152 testcase( rc!=SQLITE_OK );
44155 /* If an error occurred in either of the blocks above, free the
44156 ** Pager structure and close the file.
44158 if( rc!=SQLITE_OK ){
44159 assert( !pPager->pTmpSpace );
44160 sqlite3OsClose(pPager->fd);
44161 sqlite3_free(pPager);
44162 return rc;
44165 /* Initialize the PCache object. */
44166 assert( nExtra<1000 );
44167 nExtra = ROUND8(nExtra);
44168 sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
44169 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
44171 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
44172 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
44174 pPager->useJournal = (u8)useJournal;
44175 /* pPager->stmtOpen = 0; */
44176 /* pPager->stmtInUse = 0; */
44177 /* pPager->nRef = 0; */
44178 /* pPager->stmtSize = 0; */
44179 /* pPager->stmtJSize = 0; */
44180 /* pPager->nPage = 0; */
44181 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
44182 /* pPager->state = PAGER_UNLOCK; */
44183 #if 0
44184 assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
44185 #endif
44186 /* pPager->errMask = 0; */
44187 pPager->tempFile = (u8)tempFile;
44188 assert( tempFile==PAGER_LOCKINGMODE_NORMAL
44189 || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
44190 assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
44191 pPager->exclusiveMode = (u8)tempFile;
44192 pPager->changeCountDone = pPager->tempFile;
44193 pPager->memDb = (u8)memDb;
44194 pPager->readOnly = (u8)readOnly;
44195 assert( useJournal || pPager->tempFile );
44196 pPager->noSync = pPager->tempFile;
44197 if( pPager->noSync ){
44198 assert( pPager->fullSync==0 );
44199 assert( pPager->syncFlags==0 );
44200 assert( pPager->walSyncFlags==0 );
44201 assert( pPager->ckptSyncFlags==0 );
44202 }else{
44203 pPager->fullSync = 1;
44204 pPager->syncFlags = SQLITE_SYNC_NORMAL;
44205 pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
44206 pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
44208 /* pPager->pFirst = 0; */
44209 /* pPager->pFirstSynced = 0; */
44210 /* pPager->pLast = 0; */
44211 pPager->nExtra = (u16)nExtra;
44212 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
44213 assert( isOpen(pPager->fd) || tempFile );
44214 setSectorSize(pPager);
44215 if( !useJournal ){
44216 pPager->journalMode = PAGER_JOURNALMODE_OFF;
44217 }else if( memDb ){
44218 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
44220 /* pPager->xBusyHandler = 0; */
44221 /* pPager->pBusyHandlerArg = 0; */
44222 pPager->xReiniter = xReinit;
44223 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
44224 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
44226 *ppPager = pPager;
44227 return SQLITE_OK;
44231 /* Verify that the database file has not be deleted or renamed out from
44232 ** under the pager. Return SQLITE_OK if the database is still were it ought
44233 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
44234 ** code from sqlite3OsAccess()) if the database has gone missing.
44236 static int databaseIsUnmoved(Pager *pPager){
44237 int bHasMoved = 0;
44238 int rc;
44240 if( pPager->tempFile ) return SQLITE_OK;
44241 if( pPager->dbSize==0 ) return SQLITE_OK;
44242 assert( pPager->zFilename && pPager->zFilename[0] );
44243 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
44244 if( rc==SQLITE_NOTFOUND ){
44245 /* If the HAS_MOVED file-control is unimplemented, assume that the file
44246 ** has not been moved. That is the historical behavior of SQLite: prior to
44247 ** version 3.8.3, it never checked */
44248 rc = SQLITE_OK;
44249 }else if( rc==SQLITE_OK && bHasMoved ){
44250 rc = SQLITE_READONLY_DBMOVED;
44252 return rc;
44257 ** This function is called after transitioning from PAGER_UNLOCK to
44258 ** PAGER_SHARED state. It tests if there is a hot journal present in
44259 ** the file-system for the given pager. A hot journal is one that
44260 ** needs to be played back. According to this function, a hot-journal
44261 ** file exists if the following criteria are met:
44263 ** * The journal file exists in the file system, and
44264 ** * No process holds a RESERVED or greater lock on the database file, and
44265 ** * The database file itself is greater than 0 bytes in size, and
44266 ** * The first byte of the journal file exists and is not 0x00.
44268 ** If the current size of the database file is 0 but a journal file
44269 ** exists, that is probably an old journal left over from a prior
44270 ** database with the same name. In this case the journal file is
44271 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
44272 ** is returned.
44274 ** This routine does not check if there is a master journal filename
44275 ** at the end of the file. If there is, and that master journal file
44276 ** does not exist, then the journal file is not really hot. In this
44277 ** case this routine will return a false-positive. The pager_playback()
44278 ** routine will discover that the journal file is not really hot and
44279 ** will not roll it back.
44281 ** If a hot-journal file is found to exist, *pExists is set to 1 and
44282 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
44283 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
44284 ** to determine whether or not a hot-journal file exists, the IO error
44285 ** code is returned and the value of *pExists is undefined.
44287 static int hasHotJournal(Pager *pPager, int *pExists){
44288 sqlite3_vfs * const pVfs = pPager->pVfs;
44289 int rc = SQLITE_OK; /* Return code */
44290 int exists = 1; /* True if a journal file is present */
44291 int jrnlOpen = !!isOpen(pPager->jfd);
44293 assert( pPager->useJournal );
44294 assert( isOpen(pPager->fd) );
44295 assert( pPager->eState==PAGER_OPEN );
44297 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
44298 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
44301 *pExists = 0;
44302 if( !jrnlOpen ){
44303 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
44305 if( rc==SQLITE_OK && exists ){
44306 int locked = 0; /* True if some process holds a RESERVED lock */
44308 /* Race condition here: Another process might have been holding the
44309 ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
44310 ** call above, but then delete the journal and drop the lock before
44311 ** we get to the following sqlite3OsCheckReservedLock() call. If that
44312 ** is the case, this routine might think there is a hot journal when
44313 ** in fact there is none. This results in a false-positive which will
44314 ** be dealt with by the playback routine. Ticket #3883.
44316 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
44317 if( rc==SQLITE_OK && !locked ){
44318 Pgno nPage; /* Number of pages in database file */
44320 /* Check the size of the database file. If it consists of 0 pages,
44321 ** then delete the journal file. See the header comment above for
44322 ** the reasoning here. Delete the obsolete journal file under
44323 ** a RESERVED lock to avoid race conditions and to avoid violating
44324 ** [H33020].
44326 rc = pagerPagecount(pPager, &nPage);
44327 if( rc==SQLITE_OK ){
44328 if( nPage==0 ){
44329 sqlite3BeginBenignMalloc();
44330 if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
44331 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
44332 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
44334 sqlite3EndBenignMalloc();
44335 }else{
44336 /* The journal file exists and no other connection has a reserved
44337 ** or greater lock on the database file. Now check that there is
44338 ** at least one non-zero bytes at the start of the journal file.
44339 ** If there is, then we consider this journal to be hot. If not,
44340 ** it can be ignored.
44342 if( !jrnlOpen ){
44343 int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
44344 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
44346 if( rc==SQLITE_OK ){
44347 u8 first = 0;
44348 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
44349 if( rc==SQLITE_IOERR_SHORT_READ ){
44350 rc = SQLITE_OK;
44352 if( !jrnlOpen ){
44353 sqlite3OsClose(pPager->jfd);
44355 *pExists = (first!=0);
44356 }else if( rc==SQLITE_CANTOPEN ){
44357 /* If we cannot open the rollback journal file in order to see if
44358 ** its has a zero header, that might be due to an I/O error, or
44359 ** it might be due to the race condition described above and in
44360 ** ticket #3883. Either way, assume that the journal is hot.
44361 ** This might be a false positive. But if it is, then the
44362 ** automatic journal playback and recovery mechanism will deal
44363 ** with it under an EXCLUSIVE lock where we do not need to
44364 ** worry so much with race conditions.
44366 *pExists = 1;
44367 rc = SQLITE_OK;
44374 return rc;
44378 ** This function is called to obtain a shared lock on the database file.
44379 ** It is illegal to call sqlite3PagerAcquire() until after this function
44380 ** has been successfully called. If a shared-lock is already held when
44381 ** this function is called, it is a no-op.
44383 ** The following operations are also performed by this function.
44385 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
44386 ** on the database file), then an attempt is made to obtain a
44387 ** SHARED lock on the database file. Immediately after obtaining
44388 ** the SHARED lock, the file-system is checked for a hot-journal,
44389 ** which is played back if present. Following any hot-journal
44390 ** rollback, the contents of the cache are validated by checking
44391 ** the 'change-counter' field of the database file header and
44392 ** discarded if they are found to be invalid.
44394 ** 2) If the pager is running in exclusive-mode, and there are currently
44395 ** no outstanding references to any pages, and is in the error state,
44396 ** then an attempt is made to clear the error state by discarding
44397 ** the contents of the page cache and rolling back any open journal
44398 ** file.
44400 ** If everything is successful, SQLITE_OK is returned. If an IO error
44401 ** occurs while locking the database, checking for a hot-journal file or
44402 ** rolling back a journal file, the IO error code is returned.
44404 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
44405 int rc = SQLITE_OK; /* Return code */
44407 /* This routine is only called from b-tree and only when there are no
44408 ** outstanding pages. This implies that the pager state should either
44409 ** be OPEN or READER. READER is only possible if the pager is or was in
44410 ** exclusive access mode.
44412 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
44413 assert( assert_pager_state(pPager) );
44414 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44415 if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
44417 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
44418 int bHotJournal = 1; /* True if there exists a hot journal-file */
44420 assert( !MEMDB );
44422 rc = pager_wait_on_lock(pPager, SHARED_LOCK);
44423 if( rc!=SQLITE_OK ){
44424 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
44425 goto failed;
44428 /* If a journal file exists, and there is no RESERVED lock on the
44429 ** database file, then it either needs to be played back or deleted.
44431 if( pPager->eLock<=SHARED_LOCK ){
44432 rc = hasHotJournal(pPager, &bHotJournal);
44434 if( rc!=SQLITE_OK ){
44435 goto failed;
44437 if( bHotJournal ){
44438 if( pPager->readOnly ){
44439 rc = SQLITE_READONLY_ROLLBACK;
44440 goto failed;
44443 /* Get an EXCLUSIVE lock on the database file. At this point it is
44444 ** important that a RESERVED lock is not obtained on the way to the
44445 ** EXCLUSIVE lock. If it were, another process might open the
44446 ** database file, detect the RESERVED lock, and conclude that the
44447 ** database is safe to read while this process is still rolling the
44448 ** hot-journal back.
44450 ** Because the intermediate RESERVED lock is not requested, any
44451 ** other process attempting to access the database file will get to
44452 ** this point in the code and fail to obtain its own EXCLUSIVE lock
44453 ** on the database file.
44455 ** Unless the pager is in locking_mode=exclusive mode, the lock is
44456 ** downgraded to SHARED_LOCK before this function returns.
44458 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44459 if( rc!=SQLITE_OK ){
44460 goto failed;
44463 /* If it is not already open and the file exists on disk, open the
44464 ** journal for read/write access. Write access is required because
44465 ** in exclusive-access mode the file descriptor will be kept open
44466 ** and possibly used for a transaction later on. Also, write-access
44467 ** is usually required to finalize the journal in journal_mode=persist
44468 ** mode (and also for journal_mode=truncate on some systems).
44470 ** If the journal does not exist, it usually means that some
44471 ** other connection managed to get in and roll it back before
44472 ** this connection obtained the exclusive lock above. Or, it
44473 ** may mean that the pager was in the error-state when this
44474 ** function was called and the journal file does not exist.
44476 if( !isOpen(pPager->jfd) ){
44477 sqlite3_vfs * const pVfs = pPager->pVfs;
44478 int bExists; /* True if journal file exists */
44479 rc = sqlite3OsAccess(
44480 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
44481 if( rc==SQLITE_OK && bExists ){
44482 int fout = 0;
44483 int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
44484 assert( !pPager->tempFile );
44485 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
44486 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44487 if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
44488 rc = SQLITE_CANTOPEN_BKPT;
44489 sqlite3OsClose(pPager->jfd);
44494 /* Playback and delete the journal. Drop the database write
44495 ** lock and reacquire the read lock. Purge the cache before
44496 ** playing back the hot-journal so that we don't end up with
44497 ** an inconsistent cache. Sync the hot journal before playing
44498 ** it back since the process that crashed and left the hot journal
44499 ** probably did not sync it and we are required to always sync
44500 ** the journal before playing it back.
44502 if( isOpen(pPager->jfd) ){
44503 assert( rc==SQLITE_OK );
44504 rc = pagerSyncHotJournal(pPager);
44505 if( rc==SQLITE_OK ){
44506 rc = pager_playback(pPager, 1);
44507 pPager->eState = PAGER_OPEN;
44509 }else if( !pPager->exclusiveMode ){
44510 pagerUnlockDb(pPager, SHARED_LOCK);
44513 if( rc!=SQLITE_OK ){
44514 /* This branch is taken if an error occurs while trying to open
44515 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
44516 ** pager_unlock() routine will be called before returning to unlock
44517 ** the file. If the unlock attempt fails, then Pager.eLock must be
44518 ** set to UNKNOWN_LOCK (see the comment above the #define for
44519 ** UNKNOWN_LOCK above for an explanation).
44521 ** In order to get pager_unlock() to do this, set Pager.eState to
44522 ** PAGER_ERROR now. This is not actually counted as a transition
44523 ** to ERROR state in the state diagram at the top of this file,
44524 ** since we know that the same call to pager_unlock() will very
44525 ** shortly transition the pager object to the OPEN state. Calling
44526 ** assert_pager_state() would fail now, as it should not be possible
44527 ** to be in ERROR state when there are zero outstanding page
44528 ** references.
44530 pager_error(pPager, rc);
44531 goto failed;
44534 assert( pPager->eState==PAGER_OPEN );
44535 assert( (pPager->eLock==SHARED_LOCK)
44536 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
44540 if( !pPager->tempFile && (
44541 pPager->pBackup
44542 || sqlite3PcachePagecount(pPager->pPCache)>0
44543 || USEFETCH(pPager)
44545 /* The shared-lock has just been acquired on the database file
44546 ** and there are already pages in the cache (from a previous
44547 ** read or write transaction). Check to see if the database
44548 ** has been modified. If the database has changed, flush the
44549 ** cache.
44551 ** Database changes is detected by looking at 15 bytes beginning
44552 ** at offset 24 into the file. The first 4 of these 16 bytes are
44553 ** a 32-bit counter that is incremented with each change. The
44554 ** other bytes change randomly with each file change when
44555 ** a codec is in use.
44557 ** There is a vanishingly small chance that a change will not be
44558 ** detected. The chance of an undetected change is so small that
44559 ** it can be neglected.
44561 Pgno nPage = 0;
44562 char dbFileVers[sizeof(pPager->dbFileVers)];
44564 rc = pagerPagecount(pPager, &nPage);
44565 if( rc ) goto failed;
44567 if( nPage>0 ){
44568 IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
44569 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
44570 if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
44571 goto failed;
44573 }else{
44574 memset(dbFileVers, 0, sizeof(dbFileVers));
44577 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
44578 pager_reset(pPager);
44580 /* Unmap the database file. It is possible that external processes
44581 ** may have truncated the database file and then extended it back
44582 ** to its original size while this process was not holding a lock.
44583 ** In this case there may exist a Pager.pMap mapping that appears
44584 ** to be the right size but is not actually valid. Avoid this
44585 ** possibility by unmapping the db here. */
44586 if( USEFETCH(pPager) ){
44587 sqlite3OsUnfetch(pPager->fd, 0, 0);
44592 /* If there is a WAL file in the file-system, open this database in WAL
44593 ** mode. Otherwise, the following function call is a no-op.
44595 rc = pagerOpenWalIfPresent(pPager);
44596 #ifndef SQLITE_OMIT_WAL
44597 assert( pPager->pWal==0 || rc==SQLITE_OK );
44598 #endif
44601 if( pagerUseWal(pPager) ){
44602 assert( rc==SQLITE_OK );
44603 rc = pagerBeginReadTransaction(pPager);
44606 if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
44607 rc = pagerPagecount(pPager, &pPager->dbSize);
44610 failed:
44611 if( rc!=SQLITE_OK ){
44612 assert( !MEMDB );
44613 pager_unlock(pPager);
44614 assert( pPager->eState==PAGER_OPEN );
44615 }else{
44616 pPager->eState = PAGER_READER;
44618 return rc;
44622 ** If the reference count has reached zero, rollback any active
44623 ** transaction and unlock the pager.
44625 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
44626 ** the rollback journal, the unlock is not performed and there is
44627 ** nothing to rollback, so this routine is a no-op.
44629 static void pagerUnlockIfUnused(Pager *pPager){
44630 if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
44631 pagerUnlockAndRollback(pPager);
44636 ** Acquire a reference to page number pgno in pager pPager (a page
44637 ** reference has type DbPage*). If the requested reference is
44638 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
44640 ** If the requested page is already in the cache, it is returned.
44641 ** Otherwise, a new page object is allocated and populated with data
44642 ** read from the database file. In some cases, the pcache module may
44643 ** choose not to allocate a new page object and may reuse an existing
44644 ** object with no outstanding references.
44646 ** The extra data appended to a page is always initialized to zeros the
44647 ** first time a page is loaded into memory. If the page requested is
44648 ** already in the cache when this function is called, then the extra
44649 ** data is left as it was when the page object was last used.
44651 ** If the database image is smaller than the requested page or if a
44652 ** non-zero value is passed as the noContent parameter and the
44653 ** requested page is not already stored in the cache, then no
44654 ** actual disk read occurs. In this case the memory image of the
44655 ** page is initialized to all zeros.
44657 ** If noContent is true, it means that we do not care about the contents
44658 ** of the page. This occurs in two scenarios:
44660 ** a) When reading a free-list leaf page from the database, and
44662 ** b) When a savepoint is being rolled back and we need to load
44663 ** a new page into the cache to be filled with the data read
44664 ** from the savepoint journal.
44666 ** If noContent is true, then the data returned is zeroed instead of
44667 ** being read from the database. Additionally, the bits corresponding
44668 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
44669 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
44670 ** savepoints are set. This means if the page is made writable at any
44671 ** point in the future, using a call to sqlite3PagerWrite(), its contents
44672 ** will not be journaled. This saves IO.
44674 ** The acquisition might fail for several reasons. In all cases,
44675 ** an appropriate error code is returned and *ppPage is set to NULL.
44677 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
44678 ** to find a page in the in-memory cache first. If the page is not already
44679 ** in memory, this routine goes to disk to read it in whereas Lookup()
44680 ** just returns 0. This routine acquires a read-lock the first time it
44681 ** has to go to disk, and could also playback an old journal if necessary.
44682 ** Since Lookup() never goes to disk, it never has to deal with locks
44683 ** or journal files.
44685 SQLITE_PRIVATE int sqlite3PagerAcquire(
44686 Pager *pPager, /* The pager open on the database file */
44687 Pgno pgno, /* Page number to fetch */
44688 DbPage **ppPage, /* Write a pointer to the page here */
44689 int flags /* PAGER_GET_XXX flags */
44691 int rc = SQLITE_OK;
44692 PgHdr *pPg = 0;
44693 u32 iFrame = 0; /* Frame to read from WAL file */
44694 const int noContent = (flags & PAGER_GET_NOCONTENT);
44696 /* It is acceptable to use a read-only (mmap) page for any page except
44697 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
44698 ** flag was specified by the caller. And so long as the db is not a
44699 ** temporary or in-memory database. */
44700 const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
44701 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
44702 #ifdef SQLITE_HAS_CODEC
44703 && pPager->xCodec==0
44704 #endif
44707 assert( pPager->eState>=PAGER_READER );
44708 assert( assert_pager_state(pPager) );
44709 assert( noContent==0 || bMmapOk==0 );
44711 if( pgno==0 ){
44712 return SQLITE_CORRUPT_BKPT;
44715 /* If the pager is in the error state, return an error immediately.
44716 ** Otherwise, request the page from the PCache layer. */
44717 if( pPager->errCode!=SQLITE_OK ){
44718 rc = pPager->errCode;
44719 }else{
44721 if( bMmapOk && pagerUseWal(pPager) ){
44722 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
44723 if( rc!=SQLITE_OK ) goto pager_acquire_err;
44726 if( bMmapOk && iFrame==0 ){
44727 void *pData = 0;
44729 rc = sqlite3OsFetch(pPager->fd,
44730 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
44733 if( rc==SQLITE_OK && pData ){
44734 if( pPager->eState>PAGER_READER ){
44735 (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
44737 if( pPg==0 ){
44738 rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
44739 }else{
44740 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
44742 if( pPg ){
44743 assert( rc==SQLITE_OK );
44744 *ppPage = pPg;
44745 return SQLITE_OK;
44748 if( rc!=SQLITE_OK ){
44749 goto pager_acquire_err;
44753 rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
44756 if( rc!=SQLITE_OK ){
44757 /* Either the call to sqlite3PcacheFetch() returned an error or the
44758 ** pager was already in the error-state when this function was called.
44759 ** Set pPg to 0 and jump to the exception handler. */
44760 pPg = 0;
44761 goto pager_acquire_err;
44763 assert( (*ppPage)->pgno==pgno );
44764 assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
44766 if( (*ppPage)->pPager && !noContent ){
44767 /* In this case the pcache already contains an initialized copy of
44768 ** the page. Return without further ado. */
44769 assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
44770 pPager->aStat[PAGER_STAT_HIT]++;
44771 return SQLITE_OK;
44773 }else{
44774 /* The pager cache has created a new page. Its content needs to
44775 ** be initialized. */
44777 pPg = *ppPage;
44778 pPg->pPager = pPager;
44780 /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
44781 ** number greater than this, or the unused locking-page, is requested. */
44782 if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
44783 rc = SQLITE_CORRUPT_BKPT;
44784 goto pager_acquire_err;
44787 if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
44788 if( pgno>pPager->mxPgno ){
44789 rc = SQLITE_FULL;
44790 goto pager_acquire_err;
44792 if( noContent ){
44793 /* Failure to set the bits in the InJournal bit-vectors is benign.
44794 ** It merely means that we might do some extra work to journal a
44795 ** page that does not need to be journaled. Nevertheless, be sure
44796 ** to test the case where a malloc error occurs while trying to set
44797 ** a bit in a bit vector.
44799 sqlite3BeginBenignMalloc();
44800 if( pgno<=pPager->dbOrigSize ){
44801 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
44802 testcase( rc==SQLITE_NOMEM );
44804 TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
44805 testcase( rc==SQLITE_NOMEM );
44806 sqlite3EndBenignMalloc();
44808 memset(pPg->pData, 0, pPager->pageSize);
44809 IOTRACE(("ZERO %p %d\n", pPager, pgno));
44810 }else{
44811 if( pagerUseWal(pPager) && bMmapOk==0 ){
44812 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
44813 if( rc!=SQLITE_OK ) goto pager_acquire_err;
44815 assert( pPg->pPager==pPager );
44816 pPager->aStat[PAGER_STAT_MISS]++;
44817 rc = readDbPage(pPg, iFrame);
44818 if( rc!=SQLITE_OK ){
44819 goto pager_acquire_err;
44822 pager_set_pagehash(pPg);
44825 return SQLITE_OK;
44827 pager_acquire_err:
44828 assert( rc!=SQLITE_OK );
44829 if( pPg ){
44830 sqlite3PcacheDrop(pPg);
44832 pagerUnlockIfUnused(pPager);
44834 *ppPage = 0;
44835 return rc;
44839 ** Acquire a page if it is already in the in-memory cache. Do
44840 ** not read the page from disk. Return a pointer to the page,
44841 ** or 0 if the page is not in cache.
44843 ** See also sqlite3PagerGet(). The difference between this routine
44844 ** and sqlite3PagerGet() is that _get() will go to the disk and read
44845 ** in the page if the page is not already in cache. This routine
44846 ** returns NULL if the page is not in cache or if a disk I/O error
44847 ** has ever happened.
44849 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
44850 PgHdr *pPg = 0;
44851 assert( pPager!=0 );
44852 assert( pgno!=0 );
44853 assert( pPager->pPCache!=0 );
44854 assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
44855 sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
44856 return pPg;
44860 ** Release a page reference.
44862 ** If the number of references to the page drop to zero, then the
44863 ** page is added to the LRU list. When all references to all pages
44864 ** are released, a rollback occurs and the lock on the database is
44865 ** removed.
44867 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
44868 Pager *pPager;
44869 assert( pPg!=0 );
44870 pPager = pPg->pPager;
44871 if( pPg->flags & PGHDR_MMAP ){
44872 pagerReleaseMapPage(pPg);
44873 }else{
44874 sqlite3PcacheRelease(pPg);
44876 pagerUnlockIfUnused(pPager);
44878 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
44879 if( pPg ) sqlite3PagerUnrefNotNull(pPg);
44883 ** This function is called at the start of every write transaction.
44884 ** There must already be a RESERVED or EXCLUSIVE lock on the database
44885 ** file when this routine is called.
44887 ** Open the journal file for pager pPager and write a journal header
44888 ** to the start of it. If there are active savepoints, open the sub-journal
44889 ** as well. This function is only used when the journal file is being
44890 ** opened to write a rollback log for a transaction. It is not used
44891 ** when opening a hot journal file to roll it back.
44893 ** If the journal file is already open (as it may be in exclusive mode),
44894 ** then this function just writes a journal header to the start of the
44895 ** already open file.
44897 ** Whether or not the journal file is opened by this function, the
44898 ** Pager.pInJournal bitvec structure is allocated.
44900 ** Return SQLITE_OK if everything is successful. Otherwise, return
44901 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
44902 ** an IO error code if opening or writing the journal file fails.
44904 static int pager_open_journal(Pager *pPager){
44905 int rc = SQLITE_OK; /* Return code */
44906 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
44908 assert( pPager->eState==PAGER_WRITER_LOCKED );
44909 assert( assert_pager_state(pPager) );
44910 assert( pPager->pInJournal==0 );
44912 /* If already in the error state, this function is a no-op. But on
44913 ** the other hand, this routine is never called if we are already in
44914 ** an error state. */
44915 if( NEVER(pPager->errCode) ) return pPager->errCode;
44917 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
44918 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
44919 if( pPager->pInJournal==0 ){
44920 return SQLITE_NOMEM;
44923 /* Open the journal file if it is not already open. */
44924 if( !isOpen(pPager->jfd) ){
44925 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
44926 sqlite3MemJournalOpen(pPager->jfd);
44927 }else{
44928 const int flags = /* VFS flags to open journal file */
44929 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
44930 (pPager->tempFile ?
44931 (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
44932 (SQLITE_OPEN_MAIN_JOURNAL)
44935 /* Verify that the database still has the same name as it did when
44936 ** it was originally opened. */
44937 rc = databaseIsUnmoved(pPager);
44938 if( rc==SQLITE_OK ){
44939 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44940 rc = sqlite3JournalOpen(
44941 pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
44943 #else
44944 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
44945 #endif
44948 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
44952 /* Write the first journal header to the journal file and open
44953 ** the sub-journal if necessary.
44955 if( rc==SQLITE_OK ){
44956 /* TODO: Check if all of these are really required. */
44957 pPager->nRec = 0;
44958 pPager->journalOff = 0;
44959 pPager->setMaster = 0;
44960 pPager->journalHdr = 0;
44961 rc = writeJournalHdr(pPager);
44965 if( rc!=SQLITE_OK ){
44966 sqlite3BitvecDestroy(pPager->pInJournal);
44967 pPager->pInJournal = 0;
44968 }else{
44969 assert( pPager->eState==PAGER_WRITER_LOCKED );
44970 pPager->eState = PAGER_WRITER_CACHEMOD;
44973 return rc;
44977 ** Begin a write-transaction on the specified pager object. If a
44978 ** write-transaction has already been opened, this function is a no-op.
44980 ** If the exFlag argument is false, then acquire at least a RESERVED
44981 ** lock on the database file. If exFlag is true, then acquire at least
44982 ** an EXCLUSIVE lock. If such a lock is already held, no locking
44983 ** functions need be called.
44985 ** If the subjInMemory argument is non-zero, then any sub-journal opened
44986 ** within this transaction will be opened as an in-memory file. This
44987 ** has no effect if the sub-journal is already opened (as it may be when
44988 ** running in exclusive mode) or if the transaction does not require a
44989 ** sub-journal. If the subjInMemory argument is zero, then any required
44990 ** sub-journal is implemented in-memory if pPager is an in-memory database,
44991 ** or using a temporary file otherwise.
44993 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
44994 int rc = SQLITE_OK;
44996 if( pPager->errCode ) return pPager->errCode;
44997 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
44998 pPager->subjInMemory = (u8)subjInMemory;
45000 if( ALWAYS(pPager->eState==PAGER_READER) ){
45001 assert( pPager->pInJournal==0 );
45003 if( pagerUseWal(pPager) ){
45004 /* If the pager is configured to use locking_mode=exclusive, and an
45005 ** exclusive lock on the database is not already held, obtain it now.
45007 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
45008 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45009 if( rc!=SQLITE_OK ){
45010 return rc;
45012 sqlite3WalExclusiveMode(pPager->pWal, 1);
45015 /* Grab the write lock on the log file. If successful, upgrade to
45016 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
45017 ** The busy-handler is not invoked if another connection already
45018 ** holds the write-lock. If possible, the upper layer will call it.
45020 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
45021 }else{
45022 /* Obtain a RESERVED lock on the database file. If the exFlag parameter
45023 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
45024 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
45025 ** lock, but not when obtaining the RESERVED lock.
45027 rc = pagerLockDb(pPager, RESERVED_LOCK);
45028 if( rc==SQLITE_OK && exFlag ){
45029 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45033 if( rc==SQLITE_OK ){
45034 /* Change to WRITER_LOCKED state.
45036 ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
45037 ** when it has an open transaction, but never to DBMOD or FINISHED.
45038 ** This is because in those states the code to roll back savepoint
45039 ** transactions may copy data from the sub-journal into the database
45040 ** file as well as into the page cache. Which would be incorrect in
45041 ** WAL mode.
45043 pPager->eState = PAGER_WRITER_LOCKED;
45044 pPager->dbHintSize = pPager->dbSize;
45045 pPager->dbFileSize = pPager->dbSize;
45046 pPager->dbOrigSize = pPager->dbSize;
45047 pPager->journalOff = 0;
45050 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
45051 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
45052 assert( assert_pager_state(pPager) );
45055 PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
45056 return rc;
45060 ** Mark a single data page as writeable. The page is written into the
45061 ** main journal or sub-journal as required. If the page is written into
45062 ** one of the journals, the corresponding bit is set in the
45063 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
45064 ** of any open savepoints as appropriate.
45066 static int pager_write(PgHdr *pPg){
45067 Pager *pPager = pPg->pPager;
45068 int rc = SQLITE_OK;
45069 int inJournal;
45071 /* This routine is not called unless a write-transaction has already
45072 ** been started. The journal file may or may not be open at this point.
45073 ** It is never called in the ERROR state.
45075 assert( pPager->eState==PAGER_WRITER_LOCKED
45076 || pPager->eState==PAGER_WRITER_CACHEMOD
45077 || pPager->eState==PAGER_WRITER_DBMOD
45079 assert( assert_pager_state(pPager) );
45080 assert( pPager->errCode==0 );
45081 assert( pPager->readOnly==0 );
45083 CHECK_PAGE(pPg);
45085 /* The journal file needs to be opened. Higher level routines have already
45086 ** obtained the necessary locks to begin the write-transaction, but the
45087 ** rollback journal might not yet be open. Open it now if this is the case.
45089 ** This is done before calling sqlite3PcacheMakeDirty() on the page.
45090 ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
45091 ** an error might occur and the pager would end up in WRITER_LOCKED state
45092 ** with pages marked as dirty in the cache.
45094 if( pPager->eState==PAGER_WRITER_LOCKED ){
45095 rc = pager_open_journal(pPager);
45096 if( rc!=SQLITE_OK ) return rc;
45098 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
45099 assert( assert_pager_state(pPager) );
45101 /* Mark the page as dirty. If the page has already been written
45102 ** to the journal then we can return right away.
45104 sqlite3PcacheMakeDirty(pPg);
45105 inJournal = pageInJournal(pPager, pPg);
45106 if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
45107 assert( !pagerUseWal(pPager) );
45108 }else{
45110 /* The transaction journal now exists and we have a RESERVED or an
45111 ** EXCLUSIVE lock on the main database file. Write the current page to
45112 ** the transaction journal if it is not there already.
45114 if( !inJournal && !pagerUseWal(pPager) ){
45115 assert( pagerUseWal(pPager)==0 );
45116 if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
45117 u32 cksum;
45118 char *pData2;
45119 i64 iOff = pPager->journalOff;
45121 /* We should never write to the journal file the page that
45122 ** contains the database locks. The following assert verifies
45123 ** that we do not. */
45124 assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
45126 assert( pPager->journalHdr<=pPager->journalOff );
45127 CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45128 cksum = pager_cksum(pPager, (u8*)pData2);
45130 /* Even if an IO or diskfull error occurs while journalling the
45131 ** page in the block above, set the need-sync flag for the page.
45132 ** Otherwise, when the transaction is rolled back, the logic in
45133 ** playback_one_page() will think that the page needs to be restored
45134 ** in the database file. And if an IO error occurs while doing so,
45135 ** then corruption may follow.
45137 pPg->flags |= PGHDR_NEED_SYNC;
45139 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
45140 if( rc!=SQLITE_OK ) return rc;
45141 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
45142 if( rc!=SQLITE_OK ) return rc;
45143 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
45144 if( rc!=SQLITE_OK ) return rc;
45146 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
45147 pPager->journalOff, pPager->pageSize));
45148 PAGER_INCR(sqlite3_pager_writej_count);
45149 PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
45150 PAGERID(pPager), pPg->pgno,
45151 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
45153 pPager->journalOff += 8 + pPager->pageSize;
45154 pPager->nRec++;
45155 assert( pPager->pInJournal!=0 );
45156 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
45157 testcase( rc==SQLITE_NOMEM );
45158 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
45159 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
45160 if( rc!=SQLITE_OK ){
45161 assert( rc==SQLITE_NOMEM );
45162 return rc;
45164 }else{
45165 if( pPager->eState!=PAGER_WRITER_DBMOD ){
45166 pPg->flags |= PGHDR_NEED_SYNC;
45168 PAGERTRACE(("APPEND %d page %d needSync=%d\n",
45169 PAGERID(pPager), pPg->pgno,
45170 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
45174 /* If the statement journal is open and the page is not in it,
45175 ** then write the current page to the statement journal. Note that
45176 ** the statement journal format differs from the standard journal format
45177 ** in that it omits the checksums and the header.
45179 if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
45180 rc = subjournalPage(pPg);
45184 /* Update the database size and return.
45186 if( pPager->dbSize<pPg->pgno ){
45187 pPager->dbSize = pPg->pgno;
45189 return rc;
45193 ** Mark a data page as writeable. This routine must be called before
45194 ** making changes to a page. The caller must check the return value
45195 ** of this function and be careful not to change any page data unless
45196 ** this routine returns SQLITE_OK.
45198 ** The difference between this function and pager_write() is that this
45199 ** function also deals with the special case where 2 or more pages
45200 ** fit on a single disk sector. In this case all co-resident pages
45201 ** must have been written to the journal file before returning.
45203 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
45204 ** as appropriate. Otherwise, SQLITE_OK.
45206 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
45207 int rc = SQLITE_OK;
45209 PgHdr *pPg = pDbPage;
45210 Pager *pPager = pPg->pPager;
45212 assert( (pPg->flags & PGHDR_MMAP)==0 );
45213 assert( pPager->eState>=PAGER_WRITER_LOCKED );
45214 assert( pPager->eState!=PAGER_ERROR );
45215 assert( assert_pager_state(pPager) );
45217 if( pPager->sectorSize > (u32)pPager->pageSize ){
45218 Pgno nPageCount; /* Total number of pages in database file */
45219 Pgno pg1; /* First page of the sector pPg is located on. */
45220 int nPage = 0; /* Number of pages starting at pg1 to journal */
45221 int ii; /* Loop counter */
45222 int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
45223 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
45225 /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
45226 ** a journal header to be written between the pages journaled by
45227 ** this function.
45229 assert( !MEMDB );
45230 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
45231 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
45233 /* This trick assumes that both the page-size and sector-size are
45234 ** an integer power of 2. It sets variable pg1 to the identifier
45235 ** of the first page of the sector pPg is located on.
45237 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
45239 nPageCount = pPager->dbSize;
45240 if( pPg->pgno>nPageCount ){
45241 nPage = (pPg->pgno - pg1)+1;
45242 }else if( (pg1+nPagePerSector-1)>nPageCount ){
45243 nPage = nPageCount+1-pg1;
45244 }else{
45245 nPage = nPagePerSector;
45247 assert(nPage>0);
45248 assert(pg1<=pPg->pgno);
45249 assert((pg1+nPage)>pPg->pgno);
45251 for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
45252 Pgno pg = pg1+ii;
45253 PgHdr *pPage;
45254 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
45255 if( pg!=PAGER_MJ_PGNO(pPager) ){
45256 rc = sqlite3PagerGet(pPager, pg, &pPage);
45257 if( rc==SQLITE_OK ){
45258 rc = pager_write(pPage);
45259 if( pPage->flags&PGHDR_NEED_SYNC ){
45260 needSync = 1;
45262 sqlite3PagerUnrefNotNull(pPage);
45265 }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
45266 if( pPage->flags&PGHDR_NEED_SYNC ){
45267 needSync = 1;
45269 sqlite3PagerUnrefNotNull(pPage);
45273 /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
45274 ** starting at pg1, then it needs to be set for all of them. Because
45275 ** writing to any of these nPage pages may damage the others, the
45276 ** journal file must contain sync()ed copies of all of them
45277 ** before any of them can be written out to the database file.
45279 if( rc==SQLITE_OK && needSync ){
45280 assert( !MEMDB );
45281 for(ii=0; ii<nPage; ii++){
45282 PgHdr *pPage = pager_lookup(pPager, pg1+ii);
45283 if( pPage ){
45284 pPage->flags |= PGHDR_NEED_SYNC;
45285 sqlite3PagerUnrefNotNull(pPage);
45290 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
45291 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
45292 }else{
45293 rc = pager_write(pDbPage);
45295 return rc;
45299 ** Return TRUE if the page given in the argument was previously passed
45300 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
45301 ** to change the content of the page.
45303 #ifndef NDEBUG
45304 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
45305 return pPg->flags&PGHDR_DIRTY;
45307 #endif
45310 ** A call to this routine tells the pager that it is not necessary to
45311 ** write the information on page pPg back to the disk, even though
45312 ** that page might be marked as dirty. This happens, for example, when
45313 ** the page has been added as a leaf of the freelist and so its
45314 ** content no longer matters.
45316 ** The overlying software layer calls this routine when all of the data
45317 ** on the given page is unused. The pager marks the page as clean so
45318 ** that it does not get written to disk.
45320 ** Tests show that this optimization can quadruple the speed of large
45321 ** DELETE operations.
45323 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
45324 Pager *pPager = pPg->pPager;
45325 if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
45326 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
45327 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
45328 pPg->flags |= PGHDR_DONT_WRITE;
45329 pager_set_pagehash(pPg);
45334 ** This routine is called to increment the value of the database file
45335 ** change-counter, stored as a 4-byte big-endian integer starting at
45336 ** byte offset 24 of the pager file. The secondary change counter at
45337 ** 92 is also updated, as is the SQLite version number at offset 96.
45339 ** But this only happens if the pPager->changeCountDone flag is false.
45340 ** To avoid excess churning of page 1, the update only happens once.
45341 ** See also the pager_write_changecounter() routine that does an
45342 ** unconditional update of the change counters.
45344 ** If the isDirectMode flag is zero, then this is done by calling
45345 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
45346 ** page data. In this case the file will be updated when the current
45347 ** transaction is committed.
45349 ** The isDirectMode flag may only be non-zero if the library was compiled
45350 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
45351 ** if isDirect is non-zero, then the database file is updated directly
45352 ** by writing an updated version of page 1 using a call to the
45353 ** sqlite3OsWrite() function.
45355 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
45356 int rc = SQLITE_OK;
45358 assert( pPager->eState==PAGER_WRITER_CACHEMOD
45359 || pPager->eState==PAGER_WRITER_DBMOD
45361 assert( assert_pager_state(pPager) );
45363 /* Declare and initialize constant integer 'isDirect'. If the
45364 ** atomic-write optimization is enabled in this build, then isDirect
45365 ** is initialized to the value passed as the isDirectMode parameter
45366 ** to this function. Otherwise, it is always set to zero.
45368 ** The idea is that if the atomic-write optimization is not
45369 ** enabled at compile time, the compiler can omit the tests of
45370 ** 'isDirect' below, as well as the block enclosed in the
45371 ** "if( isDirect )" condition.
45373 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
45374 # define DIRECT_MODE 0
45375 assert( isDirectMode==0 );
45376 UNUSED_PARAMETER(isDirectMode);
45377 #else
45378 # define DIRECT_MODE isDirectMode
45379 #endif
45381 if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
45382 PgHdr *pPgHdr; /* Reference to page 1 */
45384 assert( !pPager->tempFile && isOpen(pPager->fd) );
45386 /* Open page 1 of the file for writing. */
45387 rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
45388 assert( pPgHdr==0 || rc==SQLITE_OK );
45390 /* If page one was fetched successfully, and this function is not
45391 ** operating in direct-mode, make page 1 writable. When not in
45392 ** direct mode, page 1 is always held in cache and hence the PagerGet()
45393 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
45395 if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
45396 rc = sqlite3PagerWrite(pPgHdr);
45399 if( rc==SQLITE_OK ){
45400 /* Actually do the update of the change counter */
45401 pager_write_changecounter(pPgHdr);
45403 /* If running in direct mode, write the contents of page 1 to the file. */
45404 if( DIRECT_MODE ){
45405 const void *zBuf;
45406 assert( pPager->dbFileSize>0 );
45407 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
45408 if( rc==SQLITE_OK ){
45409 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
45410 pPager->aStat[PAGER_STAT_WRITE]++;
45412 if( rc==SQLITE_OK ){
45413 /* Update the pager's copy of the change-counter. Otherwise, the
45414 ** next time a read transaction is opened the cache will be
45415 ** flushed (as the change-counter values will not match). */
45416 const void *pCopy = (const void *)&((const char *)zBuf)[24];
45417 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
45418 pPager->changeCountDone = 1;
45420 }else{
45421 pPager->changeCountDone = 1;
45425 /* Release the page reference. */
45426 sqlite3PagerUnref(pPgHdr);
45428 return rc;
45432 ** Sync the database file to disk. This is a no-op for in-memory databases
45433 ** or pages with the Pager.noSync flag set.
45435 ** If successful, or if called on a pager for which it is a no-op, this
45436 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
45438 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
45439 int rc = SQLITE_OK;
45441 if( isOpen(pPager->fd) ){
45442 void *pArg = (void*)zMaster;
45443 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
45444 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
45446 if( rc==SQLITE_OK && !pPager->noSync ){
45447 assert( !MEMDB );
45448 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
45450 return rc;
45454 ** This function may only be called while a write-transaction is active in
45455 ** rollback. If the connection is in WAL mode, this call is a no-op.
45456 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
45457 ** the database file, an attempt is made to obtain one.
45459 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
45460 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
45461 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
45462 ** returned.
45464 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
45465 int rc = SQLITE_OK;
45466 assert( pPager->eState==PAGER_WRITER_CACHEMOD
45467 || pPager->eState==PAGER_WRITER_DBMOD
45468 || pPager->eState==PAGER_WRITER_LOCKED
45470 assert( assert_pager_state(pPager) );
45471 if( 0==pagerUseWal(pPager) ){
45472 rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
45474 return rc;
45478 ** Sync the database file for the pager pPager. zMaster points to the name
45479 ** of a master journal file that should be written into the individual
45480 ** journal file. zMaster may be NULL, which is interpreted as no master
45481 ** journal (a single database transaction).
45483 ** This routine ensures that:
45485 ** * The database file change-counter is updated,
45486 ** * the journal is synced (unless the atomic-write optimization is used),
45487 ** * all dirty pages are written to the database file,
45488 ** * the database file is truncated (if required), and
45489 ** * the database file synced.
45491 ** The only thing that remains to commit the transaction is to finalize
45492 ** (delete, truncate or zero the first part of) the journal file (or
45493 ** delete the master journal file if specified).
45495 ** Note that if zMaster==NULL, this does not overwrite a previous value
45496 ** passed to an sqlite3PagerCommitPhaseOne() call.
45498 ** If the final parameter - noSync - is true, then the database file itself
45499 ** is not synced. The caller must call sqlite3PagerSync() directly to
45500 ** sync the database file before calling CommitPhaseTwo() to delete the
45501 ** journal file in this case.
45503 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
45504 Pager *pPager, /* Pager object */
45505 const char *zMaster, /* If not NULL, the master journal name */
45506 int noSync /* True to omit the xSync on the db file */
45508 int rc = SQLITE_OK; /* Return code */
45510 assert( pPager->eState==PAGER_WRITER_LOCKED
45511 || pPager->eState==PAGER_WRITER_CACHEMOD
45512 || pPager->eState==PAGER_WRITER_DBMOD
45513 || pPager->eState==PAGER_ERROR
45515 assert( assert_pager_state(pPager) );
45517 /* If a prior error occurred, report that error again. */
45518 if( NEVER(pPager->errCode) ) return pPager->errCode;
45520 PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
45521 pPager->zFilename, zMaster, pPager->dbSize));
45523 /* If no database changes have been made, return early. */
45524 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
45526 if( MEMDB ){
45527 /* If this is an in-memory db, or no pages have been written to, or this
45528 ** function has already been called, it is mostly a no-op. However, any
45529 ** backup in progress needs to be restarted.
45531 sqlite3BackupRestart(pPager->pBackup);
45532 }else{
45533 if( pagerUseWal(pPager) ){
45534 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
45535 PgHdr *pPageOne = 0;
45536 if( pList==0 ){
45537 /* Must have at least one page for the WAL commit flag.
45538 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
45539 rc = sqlite3PagerGet(pPager, 1, &pPageOne);
45540 pList = pPageOne;
45541 pList->pDirty = 0;
45543 assert( rc==SQLITE_OK );
45544 if( ALWAYS(pList) ){
45545 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
45547 sqlite3PagerUnref(pPageOne);
45548 if( rc==SQLITE_OK ){
45549 sqlite3PcacheCleanAll(pPager->pPCache);
45551 }else{
45552 /* The following block updates the change-counter. Exactly how it
45553 ** does this depends on whether or not the atomic-update optimization
45554 ** was enabled at compile time, and if this transaction meets the
45555 ** runtime criteria to use the operation:
45557 ** * The file-system supports the atomic-write property for
45558 ** blocks of size page-size, and
45559 ** * This commit is not part of a multi-file transaction, and
45560 ** * Exactly one page has been modified and store in the journal file.
45562 ** If the optimization was not enabled at compile time, then the
45563 ** pager_incr_changecounter() function is called to update the change
45564 ** counter in 'indirect-mode'. If the optimization is compiled in but
45565 ** is not applicable to this transaction, call sqlite3JournalCreate()
45566 ** to make sure the journal file has actually been created, then call
45567 ** pager_incr_changecounter() to update the change-counter in indirect
45568 ** mode.
45570 ** Otherwise, if the optimization is both enabled and applicable,
45571 ** then call pager_incr_changecounter() to update the change-counter
45572 ** in 'direct' mode. In this case the journal file will never be
45573 ** created for this transaction.
45575 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
45576 PgHdr *pPg;
45577 assert( isOpen(pPager->jfd)
45578 || pPager->journalMode==PAGER_JOURNALMODE_OFF
45579 || pPager->journalMode==PAGER_JOURNALMODE_WAL
45581 if( !zMaster && isOpen(pPager->jfd)
45582 && pPager->journalOff==jrnlBufferSize(pPager)
45583 && pPager->dbSize>=pPager->dbOrigSize
45584 && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
45586 /* Update the db file change counter via the direct-write method. The
45587 ** following call will modify the in-memory representation of page 1
45588 ** to include the updated change counter and then write page 1
45589 ** directly to the database file. Because of the atomic-write
45590 ** property of the host file-system, this is safe.
45592 rc = pager_incr_changecounter(pPager, 1);
45593 }else{
45594 rc = sqlite3JournalCreate(pPager->jfd);
45595 if( rc==SQLITE_OK ){
45596 rc = pager_incr_changecounter(pPager, 0);
45599 #else
45600 rc = pager_incr_changecounter(pPager, 0);
45601 #endif
45602 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45604 /* Write the master journal name into the journal file. If a master
45605 ** journal file name has already been written to the journal file,
45606 ** or if zMaster is NULL (no master journal), then this call is a no-op.
45608 rc = writeMasterJournal(pPager, zMaster);
45609 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45611 /* Sync the journal file and write all dirty pages to the database.
45612 ** If the atomic-update optimization is being used, this sync will not
45613 ** create the journal file or perform any real IO.
45615 ** Because the change-counter page was just modified, unless the
45616 ** atomic-update optimization is used it is almost certain that the
45617 ** journal requires a sync here. However, in locking_mode=exclusive
45618 ** on a system under memory pressure it is just possible that this is
45619 ** not the case. In this case it is likely enough that the redundant
45620 ** xSync() call will be changed to a no-op by the OS anyhow.
45622 rc = syncJournal(pPager, 0);
45623 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45625 rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
45626 if( rc!=SQLITE_OK ){
45627 assert( rc!=SQLITE_IOERR_BLOCKED );
45628 goto commit_phase_one_exit;
45630 sqlite3PcacheCleanAll(pPager->pPCache);
45632 /* If the file on disk is smaller than the database image, use
45633 ** pager_truncate to grow the file here. This can happen if the database
45634 ** image was extended as part of the current transaction and then the
45635 ** last page in the db image moved to the free-list. In this case the
45636 ** last page is never written out to disk, leaving the database file
45637 ** undersized. Fix this now if it is the case. */
45638 if( pPager->dbSize>pPager->dbFileSize ){
45639 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
45640 assert( pPager->eState==PAGER_WRITER_DBMOD );
45641 rc = pager_truncate(pPager, nNew);
45642 if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
45645 /* Finally, sync the database file. */
45646 if( !noSync ){
45647 rc = sqlite3PagerSync(pPager, zMaster);
45649 IOTRACE(("DBSYNC %p\n", pPager))
45653 commit_phase_one_exit:
45654 if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
45655 pPager->eState = PAGER_WRITER_FINISHED;
45657 return rc;
45662 ** When this function is called, the database file has been completely
45663 ** updated to reflect the changes made by the current transaction and
45664 ** synced to disk. The journal file still exists in the file-system
45665 ** though, and if a failure occurs at this point it will eventually
45666 ** be used as a hot-journal and the current transaction rolled back.
45668 ** This function finalizes the journal file, either by deleting,
45669 ** truncating or partially zeroing it, so that it cannot be used
45670 ** for hot-journal rollback. Once this is done the transaction is
45671 ** irrevocably committed.
45673 ** If an error occurs, an IO error code is returned and the pager
45674 ** moves into the error state. Otherwise, SQLITE_OK is returned.
45676 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
45677 int rc = SQLITE_OK; /* Return code */
45679 /* This routine should not be called if a prior error has occurred.
45680 ** But if (due to a coding error elsewhere in the system) it does get
45681 ** called, just return the same error code without doing anything. */
45682 if( NEVER(pPager->errCode) ) return pPager->errCode;
45684 assert( pPager->eState==PAGER_WRITER_LOCKED
45685 || pPager->eState==PAGER_WRITER_FINISHED
45686 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
45688 assert( assert_pager_state(pPager) );
45690 /* An optimization. If the database was not actually modified during
45691 ** this transaction, the pager is running in exclusive-mode and is
45692 ** using persistent journals, then this function is a no-op.
45694 ** The start of the journal file currently contains a single journal
45695 ** header with the nRec field set to 0. If such a journal is used as
45696 ** a hot-journal during hot-journal rollback, 0 changes will be made
45697 ** to the database file. So there is no need to zero the journal
45698 ** header. Since the pager is in exclusive mode, there is no need
45699 ** to drop any locks either.
45701 if( pPager->eState==PAGER_WRITER_LOCKED
45702 && pPager->exclusiveMode
45703 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
45705 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
45706 pPager->eState = PAGER_READER;
45707 return SQLITE_OK;
45710 PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
45711 rc = pager_end_transaction(pPager, pPager->setMaster, 1);
45712 return pager_error(pPager, rc);
45716 ** If a write transaction is open, then all changes made within the
45717 ** transaction are reverted and the current write-transaction is closed.
45718 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
45719 ** state if an error occurs.
45721 ** If the pager is already in PAGER_ERROR state when this function is called,
45722 ** it returns Pager.errCode immediately. No work is performed in this case.
45724 ** Otherwise, in rollback mode, this function performs two functions:
45726 ** 1) It rolls back the journal file, restoring all database file and
45727 ** in-memory cache pages to the state they were in when the transaction
45728 ** was opened, and
45730 ** 2) It finalizes the journal file, so that it is not used for hot
45731 ** rollback at any point in the future.
45733 ** Finalization of the journal file (task 2) is only performed if the
45734 ** rollback is successful.
45736 ** In WAL mode, all cache-entries containing data modified within the
45737 ** current transaction are either expelled from the cache or reverted to
45738 ** their pre-transaction state by re-reading data from the database or
45739 ** WAL files. The WAL transaction is then closed.
45741 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
45742 int rc = SQLITE_OK; /* Return code */
45743 PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
45745 /* PagerRollback() is a no-op if called in READER or OPEN state. If
45746 ** the pager is already in the ERROR state, the rollback is not
45747 ** attempted here. Instead, the error code is returned to the caller.
45749 assert( assert_pager_state(pPager) );
45750 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
45751 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
45753 if( pagerUseWal(pPager) ){
45754 int rc2;
45755 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
45756 rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
45757 if( rc==SQLITE_OK ) rc = rc2;
45758 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
45759 int eState = pPager->eState;
45760 rc = pager_end_transaction(pPager, 0, 0);
45761 if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
45762 /* This can happen using journal_mode=off. Move the pager to the error
45763 ** state to indicate that the contents of the cache may not be trusted.
45764 ** Any active readers will get SQLITE_ABORT.
45766 pPager->errCode = SQLITE_ABORT;
45767 pPager->eState = PAGER_ERROR;
45768 return rc;
45770 }else{
45771 rc = pager_playback(pPager, 0);
45774 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
45775 assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
45776 || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
45777 || rc==SQLITE_CANTOPEN
45780 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
45781 ** cache. So call pager_error() on the way out to make any error persistent.
45783 return pager_error(pPager, rc);
45787 ** Return TRUE if the database file is opened read-only. Return FALSE
45788 ** if the database is (in theory) writable.
45790 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
45791 return pPager->readOnly;
45795 ** Return the number of references to the pager.
45797 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
45798 return sqlite3PcacheRefCount(pPager->pPCache);
45802 ** Return the approximate number of bytes of memory currently
45803 ** used by the pager and its associated cache.
45805 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
45806 int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
45807 + 5*sizeof(void*);
45808 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
45809 + sqlite3MallocSize(pPager)
45810 + pPager->pageSize;
45814 ** Return the number of references to the specified page.
45816 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
45817 return sqlite3PcachePageRefcount(pPage);
45820 #ifdef SQLITE_TEST
45822 ** This routine is used for testing and analysis only.
45824 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
45825 static int a[11];
45826 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
45827 a[1] = sqlite3PcachePagecount(pPager->pPCache);
45828 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
45829 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
45830 a[4] = pPager->eState;
45831 a[5] = pPager->errCode;
45832 a[6] = pPager->aStat[PAGER_STAT_HIT];
45833 a[7] = pPager->aStat[PAGER_STAT_MISS];
45834 a[8] = 0; /* Used to be pPager->nOvfl */
45835 a[9] = pPager->nRead;
45836 a[10] = pPager->aStat[PAGER_STAT_WRITE];
45837 return a;
45839 #endif
45842 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
45843 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
45844 ** current cache hit or miss count, according to the value of eStat. If the
45845 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
45846 ** returning.
45848 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
45850 assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
45851 || eStat==SQLITE_DBSTATUS_CACHE_MISS
45852 || eStat==SQLITE_DBSTATUS_CACHE_WRITE
45855 assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
45856 assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
45857 assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
45859 *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
45860 if( reset ){
45861 pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
45866 ** Return true if this is an in-memory pager.
45868 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
45869 return MEMDB;
45873 ** Check that there are at least nSavepoint savepoints open. If there are
45874 ** currently less than nSavepoints open, then open one or more savepoints
45875 ** to make up the difference. If the number of savepoints is already
45876 ** equal to nSavepoint, then this function is a no-op.
45878 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
45879 ** occurs while opening the sub-journal file, then an IO error code is
45880 ** returned. Otherwise, SQLITE_OK.
45882 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
45883 int rc = SQLITE_OK; /* Return code */
45884 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
45886 assert( pPager->eState>=PAGER_WRITER_LOCKED );
45887 assert( assert_pager_state(pPager) );
45889 if( nSavepoint>nCurrent && pPager->useJournal ){
45890 int ii; /* Iterator variable */
45891 PagerSavepoint *aNew; /* New Pager.aSavepoint array */
45893 /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
45894 ** if the allocation fails. Otherwise, zero the new portion in case a
45895 ** malloc failure occurs while populating it in the for(...) loop below.
45897 aNew = (PagerSavepoint *)sqlite3Realloc(
45898 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
45900 if( !aNew ){
45901 return SQLITE_NOMEM;
45903 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
45904 pPager->aSavepoint = aNew;
45906 /* Populate the PagerSavepoint structures just allocated. */
45907 for(ii=nCurrent; ii<nSavepoint; ii++){
45908 aNew[ii].nOrig = pPager->dbSize;
45909 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
45910 aNew[ii].iOffset = pPager->journalOff;
45911 }else{
45912 aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
45914 aNew[ii].iSubRec = pPager->nSubRec;
45915 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
45916 if( !aNew[ii].pInSavepoint ){
45917 return SQLITE_NOMEM;
45919 if( pagerUseWal(pPager) ){
45920 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
45922 pPager->nSavepoint = ii+1;
45924 assert( pPager->nSavepoint==nSavepoint );
45925 assertTruncateConstraint(pPager);
45928 return rc;
45932 ** This function is called to rollback or release (commit) a savepoint.
45933 ** The savepoint to release or rollback need not be the most recently
45934 ** created savepoint.
45936 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
45937 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
45938 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
45939 ** that have occurred since the specified savepoint was created.
45941 ** The savepoint to rollback or release is identified by parameter
45942 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
45943 ** (the first created). A value of (Pager.nSavepoint-1) means operate
45944 ** on the most recently created savepoint. If iSavepoint is greater than
45945 ** (Pager.nSavepoint-1), then this function is a no-op.
45947 ** If a negative value is passed to this function, then the current
45948 ** transaction is rolled back. This is different to calling
45949 ** sqlite3PagerRollback() because this function does not terminate
45950 ** the transaction or unlock the database, it just restores the
45951 ** contents of the database to its original state.
45953 ** In any case, all savepoints with an index greater than iSavepoint
45954 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
45955 ** then savepoint iSavepoint is also destroyed.
45957 ** This function may return SQLITE_NOMEM if a memory allocation fails,
45958 ** or an IO error code if an IO error occurs while rolling back a
45959 ** savepoint. If no errors occur, SQLITE_OK is returned.
45961 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
45962 int rc = pPager->errCode; /* Return code */
45964 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
45965 assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
45967 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
45968 int ii; /* Iterator variable */
45969 int nNew; /* Number of remaining savepoints after this op. */
45971 /* Figure out how many savepoints will still be active after this
45972 ** operation. Store this value in nNew. Then free resources associated
45973 ** with any savepoints that are destroyed by this operation.
45975 nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
45976 for(ii=nNew; ii<pPager->nSavepoint; ii++){
45977 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
45979 pPager->nSavepoint = nNew;
45981 /* If this is a release of the outermost savepoint, truncate
45982 ** the sub-journal to zero bytes in size. */
45983 if( op==SAVEPOINT_RELEASE ){
45984 if( nNew==0 && isOpen(pPager->sjfd) ){
45985 /* Only truncate if it is an in-memory sub-journal. */
45986 if( sqlite3IsMemJournal(pPager->sjfd) ){
45987 rc = sqlite3OsTruncate(pPager->sjfd, 0);
45988 assert( rc==SQLITE_OK );
45990 pPager->nSubRec = 0;
45993 /* Else this is a rollback operation, playback the specified savepoint.
45994 ** If this is a temp-file, it is possible that the journal file has
45995 ** not yet been opened. In this case there have been no changes to
45996 ** the database file, so the playback operation can be skipped.
45998 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
45999 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
46000 rc = pagerPlaybackSavepoint(pPager, pSavepoint);
46001 assert(rc!=SQLITE_DONE);
46005 return rc;
46009 ** Return the full pathname of the database file.
46011 ** Except, if the pager is in-memory only, then return an empty string if
46012 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
46013 ** used to report the filename to the user, for compatibility with legacy
46014 ** behavior. But when the Btree needs to know the filename for matching to
46015 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
46016 ** participate in shared-cache.
46018 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
46019 return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
46023 ** Return the VFS structure for the pager.
46025 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
46026 return pPager->pVfs;
46030 ** Return the file handle for the database file associated
46031 ** with the pager. This might return NULL if the file has
46032 ** not yet been opened.
46034 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
46035 return pPager->fd;
46039 ** Return the full pathname of the journal file.
46041 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
46042 return pPager->zJournal;
46046 ** Return true if fsync() calls are disabled for this pager. Return FALSE
46047 ** if fsync()s are executed normally.
46049 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
46050 return pPager->noSync;
46053 #ifdef SQLITE_HAS_CODEC
46055 ** Set or retrieve the codec for this pager
46057 SQLITE_PRIVATE void sqlite3PagerSetCodec(
46058 Pager *pPager,
46059 void *(*xCodec)(void*,void*,Pgno,int),
46060 void (*xCodecSizeChng)(void*,int,int),
46061 void (*xCodecFree)(void*),
46062 void *pCodec
46064 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
46065 pPager->xCodec = pPager->memDb ? 0 : xCodec;
46066 pPager->xCodecSizeChng = xCodecSizeChng;
46067 pPager->xCodecFree = xCodecFree;
46068 pPager->pCodec = pCodec;
46069 pagerReportSize(pPager);
46071 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
46072 return pPager->pCodec;
46076 ** This function is called by the wal module when writing page content
46077 ** into the log file.
46079 ** This function returns a pointer to a buffer containing the encrypted
46080 ** page content. If a malloc fails, this function may return NULL.
46082 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
46083 void *aData = 0;
46084 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
46085 return aData;
46089 ** Return the current pager state
46091 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
46092 return pPager->eState;
46094 #endif /* SQLITE_HAS_CODEC */
46096 #ifndef SQLITE_OMIT_AUTOVACUUM
46098 ** Move the page pPg to location pgno in the file.
46100 ** There must be no references to the page previously located at
46101 ** pgno (which we call pPgOld) though that page is allowed to be
46102 ** in cache. If the page previously located at pgno is not already
46103 ** in the rollback journal, it is not put there by by this routine.
46105 ** References to the page pPg remain valid. Updating any
46106 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
46107 ** allocated along with the page) is the responsibility of the caller.
46109 ** A transaction must be active when this routine is called. It used to be
46110 ** required that a statement transaction was not active, but this restriction
46111 ** has been removed (CREATE INDEX needs to move a page when a statement
46112 ** transaction is active).
46114 ** If the fourth argument, isCommit, is non-zero, then this page is being
46115 ** moved as part of a database reorganization just before the transaction
46116 ** is being committed. In this case, it is guaranteed that the database page
46117 ** pPg refers to will not be written to again within this transaction.
46119 ** This function may return SQLITE_NOMEM or an IO error code if an error
46120 ** occurs. Otherwise, it returns SQLITE_OK.
46122 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
46123 PgHdr *pPgOld; /* The page being overwritten. */
46124 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
46125 int rc; /* Return code */
46126 Pgno origPgno; /* The original page number */
46128 assert( pPg->nRef>0 );
46129 assert( pPager->eState==PAGER_WRITER_CACHEMOD
46130 || pPager->eState==PAGER_WRITER_DBMOD
46132 assert( assert_pager_state(pPager) );
46134 /* In order to be able to rollback, an in-memory database must journal
46135 ** the page we are moving from.
46137 if( MEMDB ){
46138 rc = sqlite3PagerWrite(pPg);
46139 if( rc ) return rc;
46142 /* If the page being moved is dirty and has not been saved by the latest
46143 ** savepoint, then save the current contents of the page into the
46144 ** sub-journal now. This is required to handle the following scenario:
46146 ** BEGIN;
46147 ** <journal page X, then modify it in memory>
46148 ** SAVEPOINT one;
46149 ** <Move page X to location Y>
46150 ** ROLLBACK TO one;
46152 ** If page X were not written to the sub-journal here, it would not
46153 ** be possible to restore its contents when the "ROLLBACK TO one"
46154 ** statement were is processed.
46156 ** subjournalPage() may need to allocate space to store pPg->pgno into
46157 ** one or more savepoint bitvecs. This is the reason this function
46158 ** may return SQLITE_NOMEM.
46160 if( pPg->flags&PGHDR_DIRTY
46161 && subjRequiresPage(pPg)
46162 && SQLITE_OK!=(rc = subjournalPage(pPg))
46164 return rc;
46167 PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
46168 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
46169 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
46171 /* If the journal needs to be sync()ed before page pPg->pgno can
46172 ** be written to, store pPg->pgno in local variable needSyncPgno.
46174 ** If the isCommit flag is set, there is no need to remember that
46175 ** the journal needs to be sync()ed before database page pPg->pgno
46176 ** can be written to. The caller has already promised not to write to it.
46178 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
46179 needSyncPgno = pPg->pgno;
46180 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
46181 pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
46182 assert( pPg->flags&PGHDR_DIRTY );
46185 /* If the cache contains a page with page-number pgno, remove it
46186 ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
46187 ** page pgno before the 'move' operation, it needs to be retained
46188 ** for the page moved there.
46190 pPg->flags &= ~PGHDR_NEED_SYNC;
46191 pPgOld = pager_lookup(pPager, pgno);
46192 assert( !pPgOld || pPgOld->nRef==1 );
46193 if( pPgOld ){
46194 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
46195 if( MEMDB ){
46196 /* Do not discard pages from an in-memory database since we might
46197 ** need to rollback later. Just move the page out of the way. */
46198 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
46199 }else{
46200 sqlite3PcacheDrop(pPgOld);
46204 origPgno = pPg->pgno;
46205 sqlite3PcacheMove(pPg, pgno);
46206 sqlite3PcacheMakeDirty(pPg);
46208 /* For an in-memory database, make sure the original page continues
46209 ** to exist, in case the transaction needs to roll back. Use pPgOld
46210 ** as the original page since it has already been allocated.
46212 if( MEMDB ){
46213 assert( pPgOld );
46214 sqlite3PcacheMove(pPgOld, origPgno);
46215 sqlite3PagerUnrefNotNull(pPgOld);
46218 if( needSyncPgno ){
46219 /* If needSyncPgno is non-zero, then the journal file needs to be
46220 ** sync()ed before any data is written to database file page needSyncPgno.
46221 ** Currently, no such page exists in the page-cache and the
46222 ** "is journaled" bitvec flag has been set. This needs to be remedied by
46223 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
46224 ** flag.
46226 ** If the attempt to load the page into the page-cache fails, (due
46227 ** to a malloc() or IO failure), clear the bit in the pInJournal[]
46228 ** array. Otherwise, if the page is loaded and written again in
46229 ** this transaction, it may be written to the database file before
46230 ** it is synced into the journal file. This way, it may end up in
46231 ** the journal file twice, but that is not a problem.
46233 PgHdr *pPgHdr;
46234 rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
46235 if( rc!=SQLITE_OK ){
46236 if( needSyncPgno<=pPager->dbOrigSize ){
46237 assert( pPager->pTmpSpace!=0 );
46238 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
46240 return rc;
46242 pPgHdr->flags |= PGHDR_NEED_SYNC;
46243 sqlite3PcacheMakeDirty(pPgHdr);
46244 sqlite3PagerUnrefNotNull(pPgHdr);
46247 return SQLITE_OK;
46249 #endif
46252 ** Return a pointer to the data for the specified page.
46254 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
46255 assert( pPg->nRef>0 || pPg->pPager->memDb );
46256 return pPg->pData;
46260 ** Return a pointer to the Pager.nExtra bytes of "extra" space
46261 ** allocated along with the specified page.
46263 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
46264 return pPg->pExtra;
46268 ** Get/set the locking-mode for this pager. Parameter eMode must be one
46269 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
46270 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
46271 ** the locking-mode is set to the value specified.
46273 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
46274 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
46275 ** locking-mode.
46277 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
46278 assert( eMode==PAGER_LOCKINGMODE_QUERY
46279 || eMode==PAGER_LOCKINGMODE_NORMAL
46280 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
46281 assert( PAGER_LOCKINGMODE_QUERY<0 );
46282 assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
46283 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
46284 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
46285 pPager->exclusiveMode = (u8)eMode;
46287 return (int)pPager->exclusiveMode;
46291 ** Set the journal-mode for this pager. Parameter eMode must be one of:
46293 ** PAGER_JOURNALMODE_DELETE
46294 ** PAGER_JOURNALMODE_TRUNCATE
46295 ** PAGER_JOURNALMODE_PERSIST
46296 ** PAGER_JOURNALMODE_OFF
46297 ** PAGER_JOURNALMODE_MEMORY
46298 ** PAGER_JOURNALMODE_WAL
46300 ** The journalmode is set to the value specified if the change is allowed.
46301 ** The change may be disallowed for the following reasons:
46303 ** * An in-memory database can only have its journal_mode set to _OFF
46304 ** or _MEMORY.
46306 ** * Temporary databases cannot have _WAL journalmode.
46308 ** The returned indicate the current (possibly updated) journal-mode.
46310 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
46311 u8 eOld = pPager->journalMode; /* Prior journalmode */
46313 #ifdef SQLITE_DEBUG
46314 /* The print_pager_state() routine is intended to be used by the debugger
46315 ** only. We invoke it once here to suppress a compiler warning. */
46316 print_pager_state(pPager);
46317 #endif
46320 /* The eMode parameter is always valid */
46321 assert( eMode==PAGER_JOURNALMODE_DELETE
46322 || eMode==PAGER_JOURNALMODE_TRUNCATE
46323 || eMode==PAGER_JOURNALMODE_PERSIST
46324 || eMode==PAGER_JOURNALMODE_OFF
46325 || eMode==PAGER_JOURNALMODE_WAL
46326 || eMode==PAGER_JOURNALMODE_MEMORY );
46328 /* This routine is only called from the OP_JournalMode opcode, and
46329 ** the logic there will never allow a temporary file to be changed
46330 ** to WAL mode.
46332 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
46334 /* Do allow the journalmode of an in-memory database to be set to
46335 ** anything other than MEMORY or OFF
46337 if( MEMDB ){
46338 assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
46339 if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
46340 eMode = eOld;
46344 if( eMode!=eOld ){
46346 /* Change the journal mode. */
46347 assert( pPager->eState!=PAGER_ERROR );
46348 pPager->journalMode = (u8)eMode;
46350 /* When transistioning from TRUNCATE or PERSIST to any other journal
46351 ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
46352 ** delete the journal file.
46354 assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
46355 assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
46356 assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
46357 assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
46358 assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
46359 assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
46361 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
46362 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
46364 /* In this case we would like to delete the journal file. If it is
46365 ** not possible, then that is not a problem. Deleting the journal file
46366 ** here is an optimization only.
46368 ** Before deleting the journal file, obtain a RESERVED lock on the
46369 ** database file. This ensures that the journal file is not deleted
46370 ** while it is in use by some other client.
46372 sqlite3OsClose(pPager->jfd);
46373 if( pPager->eLock>=RESERVED_LOCK ){
46374 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
46375 }else{
46376 int rc = SQLITE_OK;
46377 int state = pPager->eState;
46378 assert( state==PAGER_OPEN || state==PAGER_READER );
46379 if( state==PAGER_OPEN ){
46380 rc = sqlite3PagerSharedLock(pPager);
46382 if( pPager->eState==PAGER_READER ){
46383 assert( rc==SQLITE_OK );
46384 rc = pagerLockDb(pPager, RESERVED_LOCK);
46386 if( rc==SQLITE_OK ){
46387 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
46389 if( rc==SQLITE_OK && state==PAGER_READER ){
46390 pagerUnlockDb(pPager, SHARED_LOCK);
46391 }else if( state==PAGER_OPEN ){
46392 pager_unlock(pPager);
46394 assert( state==pPager->eState );
46399 /* Return the new journal mode */
46400 return (int)pPager->journalMode;
46404 ** Return the current journal mode.
46406 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
46407 return (int)pPager->journalMode;
46411 ** Return TRUE if the pager is in a state where it is OK to change the
46412 ** journalmode. Journalmode changes can only happen when the database
46413 ** is unmodified.
46415 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
46416 assert( assert_pager_state(pPager) );
46417 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
46418 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
46419 return 1;
46423 ** Get/set the size-limit used for persistent journal files.
46425 ** Setting the size limit to -1 means no limit is enforced.
46426 ** An attempt to set a limit smaller than -1 is a no-op.
46428 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
46429 if( iLimit>=-1 ){
46430 pPager->journalSizeLimit = iLimit;
46431 sqlite3WalLimit(pPager->pWal, iLimit);
46433 return pPager->journalSizeLimit;
46437 ** Return a pointer to the pPager->pBackup variable. The backup module
46438 ** in backup.c maintains the content of this variable. This module
46439 ** uses it opaquely as an argument to sqlite3BackupRestart() and
46440 ** sqlite3BackupUpdate() only.
46442 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
46443 return &pPager->pBackup;
46446 #ifndef SQLITE_OMIT_VACUUM
46448 ** Unless this is an in-memory or temporary database, clear the pager cache.
46450 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
46451 if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
46453 #endif
46455 #ifndef SQLITE_OMIT_WAL
46457 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
46458 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
46459 ** or wal_blocking_checkpoint() API functions.
46461 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
46463 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
46464 int rc = SQLITE_OK;
46465 if( pPager->pWal ){
46466 rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
46467 pPager->xBusyHandler, pPager->pBusyHandlerArg,
46468 pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
46469 pnLog, pnCkpt
46472 return rc;
46475 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
46476 return sqlite3WalCallback(pPager->pWal);
46480 ** Return true if the underlying VFS for the given pager supports the
46481 ** primitives necessary for write-ahead logging.
46483 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
46484 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
46485 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
46489 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
46490 ** is obtained instead, immediately release it.
46492 static int pagerExclusiveLock(Pager *pPager){
46493 int rc; /* Return code */
46495 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46496 rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46497 if( rc!=SQLITE_OK ){
46498 /* If the attempt to grab the exclusive lock failed, release the
46499 ** pending lock that may have been obtained instead. */
46500 pagerUnlockDb(pPager, SHARED_LOCK);
46503 return rc;
46507 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
46508 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
46509 ** lock on the database file and use heap-memory to store the wal-index
46510 ** in. Otherwise, use the normal shared-memory.
46512 static int pagerOpenWal(Pager *pPager){
46513 int rc = SQLITE_OK;
46515 assert( pPager->pWal==0 && pPager->tempFile==0 );
46516 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
46518 /* If the pager is already in exclusive-mode, the WAL module will use
46519 ** heap-memory for the wal-index instead of the VFS shared-memory
46520 ** implementation. Take the exclusive lock now, before opening the WAL
46521 ** file, to make sure this is safe.
46523 if( pPager->exclusiveMode ){
46524 rc = pagerExclusiveLock(pPager);
46527 /* Open the connection to the log file. If this operation fails,
46528 ** (e.g. due to malloc() failure), return an error code.
46530 if( rc==SQLITE_OK ){
46531 rc = sqlite3WalOpen(pPager->pVfs,
46532 pPager->fd, pPager->zWal, pPager->exclusiveMode,
46533 pPager->journalSizeLimit, &pPager->pWal
46536 pagerFixMaplimit(pPager);
46538 return rc;
46543 ** The caller must be holding a SHARED lock on the database file to call
46544 ** this function.
46546 ** If the pager passed as the first argument is open on a real database
46547 ** file (not a temp file or an in-memory database), and the WAL file
46548 ** is not already open, make an attempt to open it now. If successful,
46549 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
46550 ** not support the xShmXXX() methods, return an error code. *pbOpen is
46551 ** not modified in either case.
46553 ** If the pager is open on a temp-file (or in-memory database), or if
46554 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
46555 ** without doing anything.
46557 SQLITE_PRIVATE int sqlite3PagerOpenWal(
46558 Pager *pPager, /* Pager object */
46559 int *pbOpen /* OUT: Set to true if call is a no-op */
46561 int rc = SQLITE_OK; /* Return code */
46563 assert( assert_pager_state(pPager) );
46564 assert( pPager->eState==PAGER_OPEN || pbOpen );
46565 assert( pPager->eState==PAGER_READER || !pbOpen );
46566 assert( pbOpen==0 || *pbOpen==0 );
46567 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
46569 if( !pPager->tempFile && !pPager->pWal ){
46570 if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
46572 /* Close any rollback journal previously open */
46573 sqlite3OsClose(pPager->jfd);
46575 rc = pagerOpenWal(pPager);
46576 if( rc==SQLITE_OK ){
46577 pPager->journalMode = PAGER_JOURNALMODE_WAL;
46578 pPager->eState = PAGER_OPEN;
46580 }else{
46581 *pbOpen = 1;
46584 return rc;
46588 ** This function is called to close the connection to the log file prior
46589 ** to switching from WAL to rollback mode.
46591 ** Before closing the log file, this function attempts to take an
46592 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
46593 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
46594 ** If successful, the EXCLUSIVE lock is not released before returning.
46596 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
46597 int rc = SQLITE_OK;
46599 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
46601 /* If the log file is not already open, but does exist in the file-system,
46602 ** it may need to be checkpointed before the connection can switch to
46603 ** rollback mode. Open it now so this can happen.
46605 if( !pPager->pWal ){
46606 int logexists = 0;
46607 rc = pagerLockDb(pPager, SHARED_LOCK);
46608 if( rc==SQLITE_OK ){
46609 rc = sqlite3OsAccess(
46610 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
46613 if( rc==SQLITE_OK && logexists ){
46614 rc = pagerOpenWal(pPager);
46618 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
46619 ** the database file, the log and log-summary files will be deleted.
46621 if( rc==SQLITE_OK && pPager->pWal ){
46622 rc = pagerExclusiveLock(pPager);
46623 if( rc==SQLITE_OK ){
46624 rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
46625 pPager->pageSize, (u8*)pPager->pTmpSpace);
46626 pPager->pWal = 0;
46627 pagerFixMaplimit(pPager);
46630 return rc;
46633 #endif /* !SQLITE_OMIT_WAL */
46635 #ifdef SQLITE_ENABLE_ZIPVFS
46637 ** A read-lock must be held on the pager when this function is called. If
46638 ** the pager is in WAL mode and the WAL file currently contains one or more
46639 ** frames, return the size in bytes of the page images stored within the
46640 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
46641 ** is empty, return 0.
46643 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
46644 assert( pPager->eState==PAGER_READER );
46645 return sqlite3WalFramesize(pPager->pWal);
46647 #endif
46649 #endif /* SQLITE_OMIT_DISKIO */
46651 /************** End of pager.c ***********************************************/
46652 /************** Begin file wal.c *********************************************/
46654 ** 2010 February 1
46656 ** The author disclaims copyright to this source code. In place of
46657 ** a legal notice, here is a blessing:
46659 ** May you do good and not evil.
46660 ** May you find forgiveness for yourself and forgive others.
46661 ** May you share freely, never taking more than you give.
46663 *************************************************************************
46665 ** This file contains the implementation of a write-ahead log (WAL) used in
46666 ** "journal_mode=WAL" mode.
46668 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
46670 ** A WAL file consists of a header followed by zero or more "frames".
46671 ** Each frame records the revised content of a single page from the
46672 ** database file. All changes to the database are recorded by writing
46673 ** frames into the WAL. Transactions commit when a frame is written that
46674 ** contains a commit marker. A single WAL can and usually does record
46675 ** multiple transactions. Periodically, the content of the WAL is
46676 ** transferred back into the database file in an operation called a
46677 ** "checkpoint".
46679 ** A single WAL file can be used multiple times. In other words, the
46680 ** WAL can fill up with frames and then be checkpointed and then new
46681 ** frames can overwrite the old ones. A WAL always grows from beginning
46682 ** toward the end. Checksums and counters attached to each frame are
46683 ** used to determine which frames within the WAL are valid and which
46684 ** are leftovers from prior checkpoints.
46686 ** The WAL header is 32 bytes in size and consists of the following eight
46687 ** big-endian 32-bit unsigned integer values:
46689 ** 0: Magic number. 0x377f0682 or 0x377f0683
46690 ** 4: File format version. Currently 3007000
46691 ** 8: Database page size. Example: 1024
46692 ** 12: Checkpoint sequence number
46693 ** 16: Salt-1, random integer incremented with each checkpoint
46694 ** 20: Salt-2, a different random integer changing with each ckpt
46695 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
46696 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
46698 ** Immediately following the wal-header are zero or more frames. Each
46699 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
46700 ** of page data. The frame-header is six big-endian 32-bit unsigned
46701 ** integer values, as follows:
46703 ** 0: Page number.
46704 ** 4: For commit records, the size of the database image in pages
46705 ** after the commit. For all other records, zero.
46706 ** 8: Salt-1 (copied from the header)
46707 ** 12: Salt-2 (copied from the header)
46708 ** 16: Checksum-1.
46709 ** 20: Checksum-2.
46711 ** A frame is considered valid if and only if the following conditions are
46712 ** true:
46714 ** (1) The salt-1 and salt-2 values in the frame-header match
46715 ** salt values in the wal-header
46717 ** (2) The checksum values in the final 8 bytes of the frame-header
46718 ** exactly match the checksum computed consecutively on the
46719 ** WAL header and the first 8 bytes and the content of all frames
46720 ** up to and including the current frame.
46722 ** The checksum is computed using 32-bit big-endian integers if the
46723 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
46724 ** is computed using little-endian if the magic number is 0x377f0682.
46725 ** The checksum values are always stored in the frame header in a
46726 ** big-endian format regardless of which byte order is used to compute
46727 ** the checksum. The checksum is computed by interpreting the input as
46728 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
46729 ** algorithm used for the checksum is as follows:
46731 ** for i from 0 to n-1 step 2:
46732 ** s0 += x[i] + s1;
46733 ** s1 += x[i+1] + s0;
46734 ** endfor
46736 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
46737 ** in reverse order (the largest fibonacci weight occurs on the first element
46738 ** of the sequence being summed.) The s1 value spans all 32-bit
46739 ** terms of the sequence whereas s0 omits the final term.
46741 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
46742 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
46743 ** The VFS.xSync operations serve as write barriers - all writes launched
46744 ** before the xSync must complete before any write that launches after the
46745 ** xSync begins.
46747 ** After each checkpoint, the salt-1 value is incremented and the salt-2
46748 ** value is randomized. This prevents old and new frames in the WAL from
46749 ** being considered valid at the same time and being checkpointing together
46750 ** following a crash.
46752 ** READER ALGORITHM
46754 ** To read a page from the database (call it page number P), a reader
46755 ** first checks the WAL to see if it contains page P. If so, then the
46756 ** last valid instance of page P that is a followed by a commit frame
46757 ** or is a commit frame itself becomes the value read. If the WAL
46758 ** contains no copies of page P that are valid and which are a commit
46759 ** frame or are followed by a commit frame, then page P is read from
46760 ** the database file.
46762 ** To start a read transaction, the reader records the index of the last
46763 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
46764 ** for all subsequent read operations. New transactions can be appended
46765 ** to the WAL, but as long as the reader uses its original mxFrame value
46766 ** and ignores the newly appended content, it will see a consistent snapshot
46767 ** of the database from a single point in time. This technique allows
46768 ** multiple concurrent readers to view different versions of the database
46769 ** content simultaneously.
46771 ** The reader algorithm in the previous paragraphs works correctly, but
46772 ** because frames for page P can appear anywhere within the WAL, the
46773 ** reader has to scan the entire WAL looking for page P frames. If the
46774 ** WAL is large (multiple megabytes is typical) that scan can be slow,
46775 ** and read performance suffers. To overcome this problem, a separate
46776 ** data structure called the wal-index is maintained to expedite the
46777 ** search for frames of a particular page.
46779 ** WAL-INDEX FORMAT
46781 ** Conceptually, the wal-index is shared memory, though VFS implementations
46782 ** might choose to implement the wal-index using a mmapped file. Because
46783 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
46784 ** on a network filesystem. All users of the database must be able to
46785 ** share memory.
46787 ** The wal-index is transient. After a crash, the wal-index can (and should
46788 ** be) reconstructed from the original WAL file. In fact, the VFS is required
46789 ** to either truncate or zero the header of the wal-index when the last
46790 ** connection to it closes. Because the wal-index is transient, it can
46791 ** use an architecture-specific format; it does not have to be cross-platform.
46792 ** Hence, unlike the database and WAL file formats which store all values
46793 ** as big endian, the wal-index can store multi-byte values in the native
46794 ** byte order of the host computer.
46796 ** The purpose of the wal-index is to answer this question quickly: Given
46797 ** a page number P and a maximum frame index M, return the index of the
46798 ** last frame in the wal before frame M for page P in the WAL, or return
46799 ** NULL if there are no frames for page P in the WAL prior to M.
46801 ** The wal-index consists of a header region, followed by an one or
46802 ** more index blocks.
46804 ** The wal-index header contains the total number of frames within the WAL
46805 ** in the mxFrame field.
46807 ** Each index block except for the first contains information on
46808 ** HASHTABLE_NPAGE frames. The first index block contains information on
46809 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
46810 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
46811 ** first index block are the same size as all other index blocks in the
46812 ** wal-index.
46814 ** Each index block contains two sections, a page-mapping that contains the
46815 ** database page number associated with each wal frame, and a hash-table
46816 ** that allows readers to query an index block for a specific page number.
46817 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
46818 ** for the first index block) 32-bit page numbers. The first entry in the
46819 ** first index-block contains the database page number corresponding to the
46820 ** first frame in the WAL file. The first entry in the second index block
46821 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
46822 ** the log, and so on.
46824 ** The last index block in a wal-index usually contains less than the full
46825 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
46826 ** depending on the contents of the WAL file. This does not change the
46827 ** allocated size of the page-mapping array - the page-mapping array merely
46828 ** contains unused entries.
46830 ** Even without using the hash table, the last frame for page P
46831 ** can be found by scanning the page-mapping sections of each index block
46832 ** starting with the last index block and moving toward the first, and
46833 ** within each index block, starting at the end and moving toward the
46834 ** beginning. The first entry that equals P corresponds to the frame
46835 ** holding the content for that page.
46837 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
46838 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
46839 ** hash table for each page number in the mapping section, so the hash
46840 ** table is never more than half full. The expected number of collisions
46841 ** prior to finding a match is 1. Each entry of the hash table is an
46842 ** 1-based index of an entry in the mapping section of the same
46843 ** index block. Let K be the 1-based index of the largest entry in
46844 ** the mapping section. (For index blocks other than the last, K will
46845 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
46846 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
46847 ** contain a value of 0.
46849 ** To look for page P in the hash table, first compute a hash iKey on
46850 ** P as follows:
46852 ** iKey = (P * 383) % HASHTABLE_NSLOT
46854 ** Then start scanning entries of the hash table, starting with iKey
46855 ** (wrapping around to the beginning when the end of the hash table is
46856 ** reached) until an unused hash slot is found. Let the first unused slot
46857 ** be at index iUnused. (iUnused might be less than iKey if there was
46858 ** wrap-around.) Because the hash table is never more than half full,
46859 ** the search is guaranteed to eventually hit an unused entry. Let
46860 ** iMax be the value between iKey and iUnused, closest to iUnused,
46861 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
46862 ** no hash slot such that aHash[i]==p) then page P is not in the
46863 ** current index block. Otherwise the iMax-th mapping entry of the
46864 ** current index block corresponds to the last entry that references
46865 ** page P.
46867 ** A hash search begins with the last index block and moves toward the
46868 ** first index block, looking for entries corresponding to page P. On
46869 ** average, only two or three slots in each index block need to be
46870 ** examined in order to either find the last entry for page P, or to
46871 ** establish that no such entry exists in the block. Each index block
46872 ** holds over 4000 entries. So two or three index blocks are sufficient
46873 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
46874 ** comparisons (on average) suffice to either locate a frame in the
46875 ** WAL or to establish that the frame does not exist in the WAL. This
46876 ** is much faster than scanning the entire 10MB WAL.
46878 ** Note that entries are added in order of increasing K. Hence, one
46879 ** reader might be using some value K0 and a second reader that started
46880 ** at a later time (after additional transactions were added to the WAL
46881 ** and to the wal-index) might be using a different value K1, where K1>K0.
46882 ** Both readers can use the same hash table and mapping section to get
46883 ** the correct result. There may be entries in the hash table with
46884 ** K>K0 but to the first reader, those entries will appear to be unused
46885 ** slots in the hash table and so the first reader will get an answer as
46886 ** if no values greater than K0 had ever been inserted into the hash table
46887 ** in the first place - which is what reader one wants. Meanwhile, the
46888 ** second reader using K1 will see additional values that were inserted
46889 ** later, which is exactly what reader two wants.
46891 ** When a rollback occurs, the value of K is decreased. Hash table entries
46892 ** that correspond to frames greater than the new K value are removed
46893 ** from the hash table at this point.
46895 #ifndef SQLITE_OMIT_WAL
46899 ** Trace output macros
46901 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46902 SQLITE_PRIVATE int sqlite3WalTrace = 0;
46903 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
46904 #else
46905 # define WALTRACE(X)
46906 #endif
46909 ** The maximum (and only) versions of the wal and wal-index formats
46910 ** that may be interpreted by this version of SQLite.
46912 ** If a client begins recovering a WAL file and finds that (a) the checksum
46913 ** values in the wal-header are correct and (b) the version field is not
46914 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
46916 ** Similarly, if a client successfully reads a wal-index header (i.e. the
46917 ** checksum test is successful) and finds that the version field is not
46918 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
46919 ** returns SQLITE_CANTOPEN.
46921 #define WAL_MAX_VERSION 3007000
46922 #define WALINDEX_MAX_VERSION 3007000
46925 ** Indices of various locking bytes. WAL_NREADER is the number
46926 ** of available reader locks and should be at least 3.
46928 #define WAL_WRITE_LOCK 0
46929 #define WAL_ALL_BUT_WRITE 1
46930 #define WAL_CKPT_LOCK 1
46931 #define WAL_RECOVER_LOCK 2
46932 #define WAL_READ_LOCK(I) (3+(I))
46933 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
46936 /* Object declarations */
46937 typedef struct WalIndexHdr WalIndexHdr;
46938 typedef struct WalIterator WalIterator;
46939 typedef struct WalCkptInfo WalCkptInfo;
46943 ** The following object holds a copy of the wal-index header content.
46945 ** The actual header in the wal-index consists of two copies of this
46946 ** object.
46948 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
46949 ** Or it can be 1 to represent a 65536-byte page. The latter case was
46950 ** added in 3.7.1 when support for 64K pages was added.
46952 struct WalIndexHdr {
46953 u32 iVersion; /* Wal-index version */
46954 u32 unused; /* Unused (padding) field */
46955 u32 iChange; /* Counter incremented each transaction */
46956 u8 isInit; /* 1 when initialized */
46957 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
46958 u16 szPage; /* Database page size in bytes. 1==64K */
46959 u32 mxFrame; /* Index of last valid frame in the WAL */
46960 u32 nPage; /* Size of database in pages */
46961 u32 aFrameCksum[2]; /* Checksum of last frame in log */
46962 u32 aSalt[2]; /* Two salt values copied from WAL header */
46963 u32 aCksum[2]; /* Checksum over all prior fields */
46967 ** A copy of the following object occurs in the wal-index immediately
46968 ** following the second copy of the WalIndexHdr. This object stores
46969 ** information used by checkpoint.
46971 ** nBackfill is the number of frames in the WAL that have been written
46972 ** back into the database. (We call the act of moving content from WAL to
46973 ** database "backfilling".) The nBackfill number is never greater than
46974 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
46975 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
46976 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
46977 ** mxFrame back to zero when the WAL is reset.
46979 ** There is one entry in aReadMark[] for each reader lock. If a reader
46980 ** holds read-lock K, then the value in aReadMark[K] is no greater than
46981 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
46982 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
46983 ** a special case; its value is never used and it exists as a place-holder
46984 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
46985 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
46986 ** directly from the database.
46988 ** The value of aReadMark[K] may only be changed by a thread that
46989 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
46990 ** aReadMark[K] cannot changed while there is a reader is using that mark
46991 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
46993 ** The checkpointer may only transfer frames from WAL to database where
46994 ** the frame numbers are less than or equal to every aReadMark[] that is
46995 ** in use (that is, every aReadMark[j] for which there is a corresponding
46996 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
46997 ** largest value and will increase an unused aReadMark[] to mxFrame if there
46998 ** is not already an aReadMark[] equal to mxFrame. The exception to the
46999 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
47000 ** in the WAL has been backfilled into the database) then new readers
47001 ** will choose aReadMark[0] which has value 0 and hence such reader will
47002 ** get all their all content directly from the database file and ignore
47003 ** the WAL.
47005 ** Writers normally append new frames to the end of the WAL. However,
47006 ** if nBackfill equals mxFrame (meaning that all WAL content has been
47007 ** written back into the database) and if no readers are using the WAL
47008 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
47009 ** the writer will first "reset" the WAL back to the beginning and start
47010 ** writing new content beginning at frame 1.
47012 ** We assume that 32-bit loads are atomic and so no locks are needed in
47013 ** order to read from any aReadMark[] entries.
47015 struct WalCkptInfo {
47016 u32 nBackfill; /* Number of WAL frames backfilled into DB */
47017 u32 aReadMark[WAL_NREADER]; /* Reader marks */
47019 #define READMARK_NOT_USED 0xffffffff
47022 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
47023 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
47024 ** only support mandatory file-locks, we do not read or write data
47025 ** from the region of the file on which locks are applied.
47027 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
47028 #define WALINDEX_LOCK_RESERVED 16
47029 #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
47031 /* Size of header before each frame in wal */
47032 #define WAL_FRAME_HDRSIZE 24
47034 /* Size of write ahead log header, including checksum. */
47035 /* #define WAL_HDRSIZE 24 */
47036 #define WAL_HDRSIZE 32
47038 /* WAL magic value. Either this value, or the same value with the least
47039 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
47040 ** big-endian format in the first 4 bytes of a WAL file.
47042 ** If the LSB is set, then the checksums for each frame within the WAL
47043 ** file are calculated by treating all data as an array of 32-bit
47044 ** big-endian words. Otherwise, they are calculated by interpreting
47045 ** all data as 32-bit little-endian words.
47047 #define WAL_MAGIC 0x377f0682
47050 ** Return the offset of frame iFrame in the write-ahead log file,
47051 ** assuming a database page size of szPage bytes. The offset returned
47052 ** is to the start of the write-ahead log frame-header.
47054 #define walFrameOffset(iFrame, szPage) ( \
47055 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
47059 ** An open write-ahead log file is represented by an instance of the
47060 ** following object.
47062 struct Wal {
47063 sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
47064 sqlite3_file *pDbFd; /* File handle for the database file */
47065 sqlite3_file *pWalFd; /* File handle for WAL file */
47066 u32 iCallback; /* Value to pass to log callback (or 0) */
47067 i64 mxWalSize; /* Truncate WAL to this size upon reset */
47068 int nWiData; /* Size of array apWiData */
47069 int szFirstBlock; /* Size of first block written to WAL file */
47070 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
47071 u32 szPage; /* Database page size */
47072 i16 readLock; /* Which read lock is being held. -1 for none */
47073 u8 syncFlags; /* Flags to use to sync header writes */
47074 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
47075 u8 writeLock; /* True if in a write transaction */
47076 u8 ckptLock; /* True if holding a checkpoint lock */
47077 u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
47078 u8 truncateOnCommit; /* True to truncate WAL file on commit */
47079 u8 syncHeader; /* Fsync the WAL header if true */
47080 u8 padToSectorBoundary; /* Pad transactions out to the next sector */
47081 WalIndexHdr hdr; /* Wal-index header for current transaction */
47082 const char *zWalName; /* Name of WAL file */
47083 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
47084 #ifdef SQLITE_DEBUG
47085 u8 lockError; /* True if a locking error has occurred */
47086 #endif
47090 ** Candidate values for Wal.exclusiveMode.
47092 #define WAL_NORMAL_MODE 0
47093 #define WAL_EXCLUSIVE_MODE 1
47094 #define WAL_HEAPMEMORY_MODE 2
47097 ** Possible values for WAL.readOnly
47099 #define WAL_RDWR 0 /* Normal read/write connection */
47100 #define WAL_RDONLY 1 /* The WAL file is readonly */
47101 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
47104 ** Each page of the wal-index mapping contains a hash-table made up of
47105 ** an array of HASHTABLE_NSLOT elements of the following type.
47107 typedef u16 ht_slot;
47110 ** This structure is used to implement an iterator that loops through
47111 ** all frames in the WAL in database page order. Where two or more frames
47112 ** correspond to the same database page, the iterator visits only the
47113 ** frame most recently written to the WAL (in other words, the frame with
47114 ** the largest index).
47116 ** The internals of this structure are only accessed by:
47118 ** walIteratorInit() - Create a new iterator,
47119 ** walIteratorNext() - Step an iterator,
47120 ** walIteratorFree() - Free an iterator.
47122 ** This functionality is used by the checkpoint code (see walCheckpoint()).
47124 struct WalIterator {
47125 int iPrior; /* Last result returned from the iterator */
47126 int nSegment; /* Number of entries in aSegment[] */
47127 struct WalSegment {
47128 int iNext; /* Next slot in aIndex[] not yet returned */
47129 ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
47130 u32 *aPgno; /* Array of page numbers. */
47131 int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
47132 int iZero; /* Frame number associated with aPgno[0] */
47133 } aSegment[1]; /* One for every 32KB page in the wal-index */
47137 ** Define the parameters of the hash tables in the wal-index file. There
47138 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
47139 ** wal-index.
47141 ** Changing any of these constants will alter the wal-index format and
47142 ** create incompatibilities.
47144 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
47145 #define HASHTABLE_HASH_1 383 /* Should be prime */
47146 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
47149 ** The block of page numbers associated with the first hash-table in a
47150 ** wal-index is smaller than usual. This is so that there is a complete
47151 ** hash-table on each aligned 32KB page of the wal-index.
47153 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
47155 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
47156 #define WALINDEX_PGSZ ( \
47157 sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
47161 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
47162 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
47163 ** numbered from zero.
47165 ** If this call is successful, *ppPage is set to point to the wal-index
47166 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
47167 ** then an SQLite error code is returned and *ppPage is set to 0.
47169 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
47170 int rc = SQLITE_OK;
47172 /* Enlarge the pWal->apWiData[] array if required */
47173 if( pWal->nWiData<=iPage ){
47174 int nByte = sizeof(u32*)*(iPage+1);
47175 volatile u32 **apNew;
47176 apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
47177 if( !apNew ){
47178 *ppPage = 0;
47179 return SQLITE_NOMEM;
47181 memset((void*)&apNew[pWal->nWiData], 0,
47182 sizeof(u32*)*(iPage+1-pWal->nWiData));
47183 pWal->apWiData = apNew;
47184 pWal->nWiData = iPage+1;
47187 /* Request a pointer to the required page from the VFS */
47188 if( pWal->apWiData[iPage]==0 ){
47189 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47190 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
47191 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
47192 }else{
47193 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
47194 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
47196 if( rc==SQLITE_READONLY ){
47197 pWal->readOnly |= WAL_SHM_RDONLY;
47198 rc = SQLITE_OK;
47203 *ppPage = pWal->apWiData[iPage];
47204 assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
47205 return rc;
47209 ** Return a pointer to the WalCkptInfo structure in the wal-index.
47211 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
47212 assert( pWal->nWiData>0 && pWal->apWiData[0] );
47213 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
47217 ** Return a pointer to the WalIndexHdr structure in the wal-index.
47219 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
47220 assert( pWal->nWiData>0 && pWal->apWiData[0] );
47221 return (volatile WalIndexHdr*)pWal->apWiData[0];
47225 ** The argument to this macro must be of type u32. On a little-endian
47226 ** architecture, it returns the u32 value that results from interpreting
47227 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
47228 ** returns the value that would be produced by intepreting the 4 bytes
47229 ** of the input value as a little-endian integer.
47231 #define BYTESWAP32(x) ( \
47232 (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
47233 + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
47237 ** Generate or extend an 8 byte checksum based on the data in
47238 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
47239 ** initial values of 0 and 0 if aIn==NULL).
47241 ** The checksum is written back into aOut[] before returning.
47243 ** nByte must be a positive multiple of 8.
47245 static void walChecksumBytes(
47246 int nativeCksum, /* True for native byte-order, false for non-native */
47247 u8 *a, /* Content to be checksummed */
47248 int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
47249 const u32 *aIn, /* Initial checksum value input */
47250 u32 *aOut /* OUT: Final checksum value output */
47252 u32 s1, s2;
47253 u32 *aData = (u32 *)a;
47254 u32 *aEnd = (u32 *)&a[nByte];
47256 if( aIn ){
47257 s1 = aIn[0];
47258 s2 = aIn[1];
47259 }else{
47260 s1 = s2 = 0;
47263 assert( nByte>=8 );
47264 assert( (nByte&0x00000007)==0 );
47266 if( nativeCksum ){
47267 do {
47268 s1 += *aData++ + s2;
47269 s2 += *aData++ + s1;
47270 }while( aData<aEnd );
47271 }else{
47272 do {
47273 s1 += BYTESWAP32(aData[0]) + s2;
47274 s2 += BYTESWAP32(aData[1]) + s1;
47275 aData += 2;
47276 }while( aData<aEnd );
47279 aOut[0] = s1;
47280 aOut[1] = s2;
47283 static void walShmBarrier(Wal *pWal){
47284 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
47285 sqlite3OsShmBarrier(pWal->pDbFd);
47290 ** Write the header information in pWal->hdr into the wal-index.
47292 ** The checksum on pWal->hdr is updated before it is written.
47294 static void walIndexWriteHdr(Wal *pWal){
47295 volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
47296 const int nCksum = offsetof(WalIndexHdr, aCksum);
47298 assert( pWal->writeLock );
47299 pWal->hdr.isInit = 1;
47300 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
47301 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
47302 memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
47303 walShmBarrier(pWal);
47304 memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
47308 ** This function encodes a single frame header and writes it to a buffer
47309 ** supplied by the caller. A frame-header is made up of a series of
47310 ** 4-byte big-endian integers, as follows:
47312 ** 0: Page number.
47313 ** 4: For commit records, the size of the database image in pages
47314 ** after the commit. For all other records, zero.
47315 ** 8: Salt-1 (copied from the wal-header)
47316 ** 12: Salt-2 (copied from the wal-header)
47317 ** 16: Checksum-1.
47318 ** 20: Checksum-2.
47320 static void walEncodeFrame(
47321 Wal *pWal, /* The write-ahead log */
47322 u32 iPage, /* Database page number for frame */
47323 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
47324 u8 *aData, /* Pointer to page data */
47325 u8 *aFrame /* OUT: Write encoded frame here */
47327 int nativeCksum; /* True for native byte-order checksums */
47328 u32 *aCksum = pWal->hdr.aFrameCksum;
47329 assert( WAL_FRAME_HDRSIZE==24 );
47330 sqlite3Put4byte(&aFrame[0], iPage);
47331 sqlite3Put4byte(&aFrame[4], nTruncate);
47332 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
47334 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
47335 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
47336 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
47338 sqlite3Put4byte(&aFrame[16], aCksum[0]);
47339 sqlite3Put4byte(&aFrame[20], aCksum[1]);
47343 ** Check to see if the frame with header in aFrame[] and content
47344 ** in aData[] is valid. If it is a valid frame, fill *piPage and
47345 ** *pnTruncate and return true. Return if the frame is not valid.
47347 static int walDecodeFrame(
47348 Wal *pWal, /* The write-ahead log */
47349 u32 *piPage, /* OUT: Database page number for frame */
47350 u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
47351 u8 *aData, /* Pointer to page data (for checksum) */
47352 u8 *aFrame /* Frame data */
47354 int nativeCksum; /* True for native byte-order checksums */
47355 u32 *aCksum = pWal->hdr.aFrameCksum;
47356 u32 pgno; /* Page number of the frame */
47357 assert( WAL_FRAME_HDRSIZE==24 );
47359 /* A frame is only valid if the salt values in the frame-header
47360 ** match the salt values in the wal-header.
47362 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
47363 return 0;
47366 /* A frame is only valid if the page number is creater than zero.
47368 pgno = sqlite3Get4byte(&aFrame[0]);
47369 if( pgno==0 ){
47370 return 0;
47373 /* A frame is only valid if a checksum of the WAL header,
47374 ** all prior frams, the first 16 bytes of this frame-header,
47375 ** and the frame-data matches the checksum in the last 8
47376 ** bytes of this frame-header.
47378 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
47379 walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
47380 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
47381 if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
47382 || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
47384 /* Checksum failed. */
47385 return 0;
47388 /* If we reach this point, the frame is valid. Return the page number
47389 ** and the new database size.
47391 *piPage = pgno;
47392 *pnTruncate = sqlite3Get4byte(&aFrame[4]);
47393 return 1;
47397 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
47399 ** Names of locks. This routine is used to provide debugging output and is not
47400 ** a part of an ordinary build.
47402 static const char *walLockName(int lockIdx){
47403 if( lockIdx==WAL_WRITE_LOCK ){
47404 return "WRITE-LOCK";
47405 }else if( lockIdx==WAL_CKPT_LOCK ){
47406 return "CKPT-LOCK";
47407 }else if( lockIdx==WAL_RECOVER_LOCK ){
47408 return "RECOVER-LOCK";
47409 }else{
47410 static char zName[15];
47411 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
47412 lockIdx-WAL_READ_LOCK(0));
47413 return zName;
47416 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
47420 ** Set or release locks on the WAL. Locks are either shared or exclusive.
47421 ** A lock cannot be moved directly between shared and exclusive - it must go
47422 ** through the unlocked state first.
47424 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
47426 static int walLockShared(Wal *pWal, int lockIdx){
47427 int rc;
47428 if( pWal->exclusiveMode ) return SQLITE_OK;
47429 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
47430 SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
47431 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
47432 walLockName(lockIdx), rc ? "failed" : "ok"));
47433 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
47434 return rc;
47436 static void walUnlockShared(Wal *pWal, int lockIdx){
47437 if( pWal->exclusiveMode ) return;
47438 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
47439 SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
47440 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
47442 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
47443 int rc;
47444 if( pWal->exclusiveMode ) return SQLITE_OK;
47445 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
47446 SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
47447 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
47448 walLockName(lockIdx), n, rc ? "failed" : "ok"));
47449 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
47450 return rc;
47452 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
47453 if( pWal->exclusiveMode ) return;
47454 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
47455 SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
47456 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
47457 walLockName(lockIdx), n));
47461 ** Compute a hash on a page number. The resulting hash value must land
47462 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
47463 ** the hash to the next value in the event of a collision.
47465 static int walHash(u32 iPage){
47466 assert( iPage>0 );
47467 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
47468 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
47470 static int walNextHash(int iPriorHash){
47471 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
47475 ** Return pointers to the hash table and page number array stored on
47476 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
47477 ** numbered starting from 0.
47479 ** Set output variable *paHash to point to the start of the hash table
47480 ** in the wal-index file. Set *piZero to one less than the frame
47481 ** number of the first frame indexed by this hash table. If a
47482 ** slot in the hash table is set to N, it refers to frame number
47483 ** (*piZero+N) in the log.
47485 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
47486 ** first frame indexed by the hash table, frame (*piZero+1).
47488 static int walHashGet(
47489 Wal *pWal, /* WAL handle */
47490 int iHash, /* Find the iHash'th table */
47491 volatile ht_slot **paHash, /* OUT: Pointer to hash index */
47492 volatile u32 **paPgno, /* OUT: Pointer to page number array */
47493 u32 *piZero /* OUT: Frame associated with *paPgno[0] */
47495 int rc; /* Return code */
47496 volatile u32 *aPgno;
47498 rc = walIndexPage(pWal, iHash, &aPgno);
47499 assert( rc==SQLITE_OK || iHash>0 );
47501 if( rc==SQLITE_OK ){
47502 u32 iZero;
47503 volatile ht_slot *aHash;
47505 aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
47506 if( iHash==0 ){
47507 aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
47508 iZero = 0;
47509 }else{
47510 iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
47513 *paPgno = &aPgno[-1];
47514 *paHash = aHash;
47515 *piZero = iZero;
47517 return rc;
47521 ** Return the number of the wal-index page that contains the hash-table
47522 ** and page-number array that contain entries corresponding to WAL frame
47523 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
47524 ** are numbered starting from 0.
47526 static int walFramePage(u32 iFrame){
47527 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
47528 assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
47529 && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
47530 && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
47531 && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
47532 && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
47534 return iHash;
47538 ** Return the page number associated with frame iFrame in this WAL.
47540 static u32 walFramePgno(Wal *pWal, u32 iFrame){
47541 int iHash = walFramePage(iFrame);
47542 if( iHash==0 ){
47543 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
47545 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
47549 ** Remove entries from the hash table that point to WAL slots greater
47550 ** than pWal->hdr.mxFrame.
47552 ** This function is called whenever pWal->hdr.mxFrame is decreased due
47553 ** to a rollback or savepoint.
47555 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
47556 ** updated. Any later hash tables will be automatically cleared when
47557 ** pWal->hdr.mxFrame advances to the point where those hash tables are
47558 ** actually needed.
47560 static void walCleanupHash(Wal *pWal){
47561 volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
47562 volatile u32 *aPgno = 0; /* Page number array for hash table */
47563 u32 iZero = 0; /* frame == (aHash[x]+iZero) */
47564 int iLimit = 0; /* Zero values greater than this */
47565 int nByte; /* Number of bytes to zero in aPgno[] */
47566 int i; /* Used to iterate through aHash[] */
47568 assert( pWal->writeLock );
47569 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
47570 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
47571 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
47573 if( pWal->hdr.mxFrame==0 ) return;
47575 /* Obtain pointers to the hash-table and page-number array containing
47576 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
47577 ** that the page said hash-table and array reside on is already mapped.
47579 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
47580 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
47581 walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
47583 /* Zero all hash-table entries that correspond to frame numbers greater
47584 ** than pWal->hdr.mxFrame.
47586 iLimit = pWal->hdr.mxFrame - iZero;
47587 assert( iLimit>0 );
47588 for(i=0; i<HASHTABLE_NSLOT; i++){
47589 if( aHash[i]>iLimit ){
47590 aHash[i] = 0;
47594 /* Zero the entries in the aPgno array that correspond to frames with
47595 ** frame numbers greater than pWal->hdr.mxFrame.
47597 nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
47598 memset((void *)&aPgno[iLimit+1], 0, nByte);
47600 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47601 /* Verify that the every entry in the mapping region is still reachable
47602 ** via the hash table even after the cleanup.
47604 if( iLimit ){
47605 int i; /* Loop counter */
47606 int iKey; /* Hash key */
47607 for(i=1; i<=iLimit; i++){
47608 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47609 if( aHash[iKey]==i ) break;
47611 assert( aHash[iKey]==i );
47614 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
47619 ** Set an entry in the wal-index that will map database page number
47620 ** pPage into WAL frame iFrame.
47622 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
47623 int rc; /* Return code */
47624 u32 iZero = 0; /* One less than frame number of aPgno[1] */
47625 volatile u32 *aPgno = 0; /* Page number array */
47626 volatile ht_slot *aHash = 0; /* Hash table */
47628 rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
47630 /* Assuming the wal-index file was successfully mapped, populate the
47631 ** page number array and hash table entry.
47633 if( rc==SQLITE_OK ){
47634 int iKey; /* Hash table key */
47635 int idx; /* Value to write to hash-table slot */
47636 int nCollide; /* Number of hash collisions */
47638 idx = iFrame - iZero;
47639 assert( idx <= HASHTABLE_NSLOT/2 + 1 );
47641 /* If this is the first entry to be added to this hash-table, zero the
47642 ** entire hash table and aPgno[] array before proceding.
47644 if( idx==1 ){
47645 int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
47646 memset((void*)&aPgno[1], 0, nByte);
47649 /* If the entry in aPgno[] is already set, then the previous writer
47650 ** must have exited unexpectedly in the middle of a transaction (after
47651 ** writing one or more dirty pages to the WAL to free up memory).
47652 ** Remove the remnants of that writers uncommitted transaction from
47653 ** the hash-table before writing any new entries.
47655 if( aPgno[idx] ){
47656 walCleanupHash(pWal);
47657 assert( !aPgno[idx] );
47660 /* Write the aPgno[] array entry and the hash-table slot. */
47661 nCollide = idx;
47662 for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
47663 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
47665 aPgno[idx] = iPage;
47666 aHash[iKey] = (ht_slot)idx;
47668 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47669 /* Verify that the number of entries in the hash table exactly equals
47670 ** the number of entries in the mapping region.
47673 int i; /* Loop counter */
47674 int nEntry = 0; /* Number of entries in the hash table */
47675 for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
47676 assert( nEntry==idx );
47679 /* Verify that the every entry in the mapping region is reachable
47680 ** via the hash table. This turns out to be a really, really expensive
47681 ** thing to check, so only do this occasionally - not on every
47682 ** iteration.
47684 if( (idx&0x3ff)==0 ){
47685 int i; /* Loop counter */
47686 for(i=1; i<=idx; i++){
47687 for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
47688 if( aHash[iKey]==i ) break;
47690 assert( aHash[iKey]==i );
47693 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
47697 return rc;
47702 ** Recover the wal-index by reading the write-ahead log file.
47704 ** This routine first tries to establish an exclusive lock on the
47705 ** wal-index to prevent other threads/processes from doing anything
47706 ** with the WAL or wal-index while recovery is running. The
47707 ** WAL_RECOVER_LOCK is also held so that other threads will know
47708 ** that this thread is running recovery. If unable to establish
47709 ** the necessary locks, this routine returns SQLITE_BUSY.
47711 static int walIndexRecover(Wal *pWal){
47712 int rc; /* Return Code */
47713 i64 nSize; /* Size of log file */
47714 u32 aFrameCksum[2] = {0, 0};
47715 int iLock; /* Lock offset to lock for checkpoint */
47716 int nLock; /* Number of locks to hold */
47718 /* Obtain an exclusive lock on all byte in the locking range not already
47719 ** locked by the caller. The caller is guaranteed to have locked the
47720 ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
47721 ** If successful, the same bytes that are locked here are unlocked before
47722 ** this function returns.
47724 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
47725 assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
47726 assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
47727 assert( pWal->writeLock );
47728 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
47729 nLock = SQLITE_SHM_NLOCK - iLock;
47730 rc = walLockExclusive(pWal, iLock, nLock);
47731 if( rc ){
47732 return rc;
47734 WALTRACE(("WAL%p: recovery begin...\n", pWal));
47736 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47738 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
47739 if( rc!=SQLITE_OK ){
47740 goto recovery_error;
47743 if( nSize>WAL_HDRSIZE ){
47744 u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
47745 u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
47746 int szFrame; /* Number of bytes in buffer aFrame[] */
47747 u8 *aData; /* Pointer to data part of aFrame buffer */
47748 int iFrame; /* Index of last frame read */
47749 i64 iOffset; /* Next offset to read from log file */
47750 int szPage; /* Page size according to the log */
47751 u32 magic; /* Magic value read from WAL header */
47752 u32 version; /* Magic value read from WAL header */
47753 int isValid; /* True if this frame is valid */
47755 /* Read in the WAL header. */
47756 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
47757 if( rc!=SQLITE_OK ){
47758 goto recovery_error;
47761 /* If the database page size is not a power of two, or is greater than
47762 ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
47763 ** data. Similarly, if the 'magic' value is invalid, ignore the whole
47764 ** WAL file.
47766 magic = sqlite3Get4byte(&aBuf[0]);
47767 szPage = sqlite3Get4byte(&aBuf[8]);
47768 if( (magic&0xFFFFFFFE)!=WAL_MAGIC
47769 || szPage&(szPage-1)
47770 || szPage>SQLITE_MAX_PAGE_SIZE
47771 || szPage<512
47773 goto finished;
47775 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
47776 pWal->szPage = szPage;
47777 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
47778 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
47780 /* Verify that the WAL header checksum is correct */
47781 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
47782 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
47784 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
47785 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
47787 goto finished;
47790 /* Verify that the version number on the WAL format is one that
47791 ** are able to understand */
47792 version = sqlite3Get4byte(&aBuf[4]);
47793 if( version!=WAL_MAX_VERSION ){
47794 rc = SQLITE_CANTOPEN_BKPT;
47795 goto finished;
47798 /* Malloc a buffer to read frames into. */
47799 szFrame = szPage + WAL_FRAME_HDRSIZE;
47800 aFrame = (u8 *)sqlite3_malloc(szFrame);
47801 if( !aFrame ){
47802 rc = SQLITE_NOMEM;
47803 goto recovery_error;
47805 aData = &aFrame[WAL_FRAME_HDRSIZE];
47807 /* Read all frames from the log file. */
47808 iFrame = 0;
47809 for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
47810 u32 pgno; /* Database page number for frame */
47811 u32 nTruncate; /* dbsize field from frame header */
47813 /* Read and decode the next log frame. */
47814 iFrame++;
47815 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
47816 if( rc!=SQLITE_OK ) break;
47817 isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
47818 if( !isValid ) break;
47819 rc = walIndexAppend(pWal, iFrame, pgno);
47820 if( rc!=SQLITE_OK ) break;
47822 /* If nTruncate is non-zero, this is a commit record. */
47823 if( nTruncate ){
47824 pWal->hdr.mxFrame = iFrame;
47825 pWal->hdr.nPage = nTruncate;
47826 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47827 testcase( szPage<=32768 );
47828 testcase( szPage>=65536 );
47829 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
47830 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
47834 sqlite3_free(aFrame);
47837 finished:
47838 if( rc==SQLITE_OK ){
47839 volatile WalCkptInfo *pInfo;
47840 int i;
47841 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
47842 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
47843 walIndexWriteHdr(pWal);
47845 /* Reset the checkpoint-header. This is safe because this thread is
47846 ** currently holding locks that exclude all other readers, writers and
47847 ** checkpointers.
47849 pInfo = walCkptInfo(pWal);
47850 pInfo->nBackfill = 0;
47851 pInfo->aReadMark[0] = 0;
47852 for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47853 if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
47855 /* If more than one frame was recovered from the log file, report an
47856 ** event via sqlite3_log(). This is to help with identifying performance
47857 ** problems caused by applications routinely shutting down without
47858 ** checkpointing the log file.
47860 if( pWal->hdr.nPage ){
47861 sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
47862 "recovered %d frames from WAL file %s",
47863 pWal->hdr.mxFrame, pWal->zWalName
47868 recovery_error:
47869 WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
47870 walUnlockExclusive(pWal, iLock, nLock);
47871 return rc;
47875 ** Close an open wal-index.
47877 static void walIndexClose(Wal *pWal, int isDelete){
47878 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
47879 int i;
47880 for(i=0; i<pWal->nWiData; i++){
47881 sqlite3_free((void *)pWal->apWiData[i]);
47882 pWal->apWiData[i] = 0;
47884 }else{
47885 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
47890 ** Open a connection to the WAL file zWalName. The database file must
47891 ** already be opened on connection pDbFd. The buffer that zWalName points
47892 ** to must remain valid for the lifetime of the returned Wal* handle.
47894 ** A SHARED lock should be held on the database file when this function
47895 ** is called. The purpose of this SHARED lock is to prevent any other
47896 ** client from unlinking the WAL or wal-index file. If another process
47897 ** were to do this just after this client opened one of these files, the
47898 ** system would be badly broken.
47900 ** If the log file is successfully opened, SQLITE_OK is returned and
47901 ** *ppWal is set to point to a new WAL handle. If an error occurs,
47902 ** an SQLite error code is returned and *ppWal is left unmodified.
47904 SQLITE_PRIVATE int sqlite3WalOpen(
47905 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
47906 sqlite3_file *pDbFd, /* The open database file */
47907 const char *zWalName, /* Name of the WAL file */
47908 int bNoShm, /* True to run in heap-memory mode */
47909 i64 mxWalSize, /* Truncate WAL to this size on reset */
47910 Wal **ppWal /* OUT: Allocated Wal handle */
47912 int rc; /* Return Code */
47913 Wal *pRet; /* Object to allocate and return */
47914 int flags; /* Flags passed to OsOpen() */
47916 assert( zWalName && zWalName[0] );
47917 assert( pDbFd );
47919 /* In the amalgamation, the os_unix.c and os_win.c source files come before
47920 ** this source file. Verify that the #defines of the locking byte offsets
47921 ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
47923 #ifdef WIN_SHM_BASE
47924 assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
47925 #endif
47926 #ifdef UNIX_SHM_BASE
47927 assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
47928 #endif
47931 /* Allocate an instance of struct Wal to return. */
47932 *ppWal = 0;
47933 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
47934 if( !pRet ){
47935 return SQLITE_NOMEM;
47938 pRet->pVfs = pVfs;
47939 pRet->pWalFd = (sqlite3_file *)&pRet[1];
47940 pRet->pDbFd = pDbFd;
47941 pRet->readLock = -1;
47942 pRet->mxWalSize = mxWalSize;
47943 pRet->zWalName = zWalName;
47944 pRet->syncHeader = 1;
47945 pRet->padToSectorBoundary = 1;
47946 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
47948 /* Open file handle on the write-ahead log file. */
47949 flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
47950 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
47951 if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
47952 pRet->readOnly = WAL_RDONLY;
47955 if( rc!=SQLITE_OK ){
47956 walIndexClose(pRet, 0);
47957 sqlite3OsClose(pRet->pWalFd);
47958 sqlite3_free(pRet);
47959 }else{
47960 int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
47961 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
47962 if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
47963 pRet->padToSectorBoundary = 0;
47965 *ppWal = pRet;
47966 WALTRACE(("WAL%d: opened\n", pRet));
47968 return rc;
47972 ** Change the size to which the WAL file is trucated on each reset.
47974 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
47975 if( pWal ) pWal->mxWalSize = iLimit;
47979 ** Find the smallest page number out of all pages held in the WAL that
47980 ** has not been returned by any prior invocation of this method on the
47981 ** same WalIterator object. Write into *piFrame the frame index where
47982 ** that page was last written into the WAL. Write into *piPage the page
47983 ** number.
47985 ** Return 0 on success. If there are no pages in the WAL with a page
47986 ** number larger than *piPage, then return 1.
47988 static int walIteratorNext(
47989 WalIterator *p, /* Iterator */
47990 u32 *piPage, /* OUT: The page number of the next page */
47991 u32 *piFrame /* OUT: Wal frame index of next page */
47993 u32 iMin; /* Result pgno must be greater than iMin */
47994 u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
47995 int i; /* For looping through segments */
47997 iMin = p->iPrior;
47998 assert( iMin<0xffffffff );
47999 for(i=p->nSegment-1; i>=0; i--){
48000 struct WalSegment *pSegment = &p->aSegment[i];
48001 while( pSegment->iNext<pSegment->nEntry ){
48002 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
48003 if( iPg>iMin ){
48004 if( iPg<iRet ){
48005 iRet = iPg;
48006 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
48008 break;
48010 pSegment->iNext++;
48014 *piPage = p->iPrior = iRet;
48015 return (iRet==0xFFFFFFFF);
48019 ** This function merges two sorted lists into a single sorted list.
48021 ** aLeft[] and aRight[] are arrays of indices. The sort key is
48022 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
48023 ** is guaranteed for all J<K:
48025 ** aContent[aLeft[J]] < aContent[aLeft[K]]
48026 ** aContent[aRight[J]] < aContent[aRight[K]]
48028 ** This routine overwrites aRight[] with a new (probably longer) sequence
48029 ** of indices such that the aRight[] contains every index that appears in
48030 ** either aLeft[] or the old aRight[] and such that the second condition
48031 ** above is still met.
48033 ** The aContent[aLeft[X]] values will be unique for all X. And the
48034 ** aContent[aRight[X]] values will be unique too. But there might be
48035 ** one or more combinations of X and Y such that
48037 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
48039 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
48041 static void walMerge(
48042 const u32 *aContent, /* Pages in wal - keys for the sort */
48043 ht_slot *aLeft, /* IN: Left hand input list */
48044 int nLeft, /* IN: Elements in array *paLeft */
48045 ht_slot **paRight, /* IN/OUT: Right hand input list */
48046 int *pnRight, /* IN/OUT: Elements in *paRight */
48047 ht_slot *aTmp /* Temporary buffer */
48049 int iLeft = 0; /* Current index in aLeft */
48050 int iRight = 0; /* Current index in aRight */
48051 int iOut = 0; /* Current index in output buffer */
48052 int nRight = *pnRight;
48053 ht_slot *aRight = *paRight;
48055 assert( nLeft>0 && nRight>0 );
48056 while( iRight<nRight || iLeft<nLeft ){
48057 ht_slot logpage;
48058 Pgno dbpage;
48060 if( (iLeft<nLeft)
48061 && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
48063 logpage = aLeft[iLeft++];
48064 }else{
48065 logpage = aRight[iRight++];
48067 dbpage = aContent[logpage];
48069 aTmp[iOut++] = logpage;
48070 if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
48072 assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
48073 assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
48076 *paRight = aLeft;
48077 *pnRight = iOut;
48078 memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
48082 ** Sort the elements in list aList using aContent[] as the sort key.
48083 ** Remove elements with duplicate keys, preferring to keep the
48084 ** larger aList[] values.
48086 ** The aList[] entries are indices into aContent[]. The values in
48087 ** aList[] are to be sorted so that for all J<K:
48089 ** aContent[aList[J]] < aContent[aList[K]]
48091 ** For any X and Y such that
48093 ** aContent[aList[X]] == aContent[aList[Y]]
48095 ** Keep the larger of the two values aList[X] and aList[Y] and discard
48096 ** the smaller.
48098 static void walMergesort(
48099 const u32 *aContent, /* Pages in wal */
48100 ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
48101 ht_slot *aList, /* IN/OUT: List to sort */
48102 int *pnList /* IN/OUT: Number of elements in aList[] */
48104 struct Sublist {
48105 int nList; /* Number of elements in aList */
48106 ht_slot *aList; /* Pointer to sub-list content */
48109 const int nList = *pnList; /* Size of input list */
48110 int nMerge = 0; /* Number of elements in list aMerge */
48111 ht_slot *aMerge = 0; /* List to be merged */
48112 int iList; /* Index into input list */
48113 int iSub = 0; /* Index into aSub array */
48114 struct Sublist aSub[13]; /* Array of sub-lists */
48116 memset(aSub, 0, sizeof(aSub));
48117 assert( nList<=HASHTABLE_NPAGE && nList>0 );
48118 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
48120 for(iList=0; iList<nList; iList++){
48121 nMerge = 1;
48122 aMerge = &aList[iList];
48123 for(iSub=0; iList & (1<<iSub); iSub++){
48124 struct Sublist *p = &aSub[iSub];
48125 assert( p->aList && p->nList<=(1<<iSub) );
48126 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
48127 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
48129 aSub[iSub].aList = aMerge;
48130 aSub[iSub].nList = nMerge;
48133 for(iSub++; iSub<ArraySize(aSub); iSub++){
48134 if( nList & (1<<iSub) ){
48135 struct Sublist *p = &aSub[iSub];
48136 assert( p->nList<=(1<<iSub) );
48137 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
48138 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
48141 assert( aMerge==aList );
48142 *pnList = nMerge;
48144 #ifdef SQLITE_DEBUG
48146 int i;
48147 for(i=1; i<*pnList; i++){
48148 assert( aContent[aList[i]] > aContent[aList[i-1]] );
48151 #endif
48155 ** Free an iterator allocated by walIteratorInit().
48157 static void walIteratorFree(WalIterator *p){
48158 sqlite3ScratchFree(p);
48162 ** Construct a WalInterator object that can be used to loop over all
48163 ** pages in the WAL in ascending order. The caller must hold the checkpoint
48164 ** lock.
48166 ** On success, make *pp point to the newly allocated WalInterator object
48167 ** return SQLITE_OK. Otherwise, return an error code. If this routine
48168 ** returns an error, the value of *pp is undefined.
48170 ** The calling routine should invoke walIteratorFree() to destroy the
48171 ** WalIterator object when it has finished with it.
48173 static int walIteratorInit(Wal *pWal, WalIterator **pp){
48174 WalIterator *p; /* Return value */
48175 int nSegment; /* Number of segments to merge */
48176 u32 iLast; /* Last frame in log */
48177 int nByte; /* Number of bytes to allocate */
48178 int i; /* Iterator variable */
48179 ht_slot *aTmp; /* Temp space used by merge-sort */
48180 int rc = SQLITE_OK; /* Return Code */
48182 /* This routine only runs while holding the checkpoint lock. And
48183 ** it only runs if there is actually content in the log (mxFrame>0).
48185 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
48186 iLast = pWal->hdr.mxFrame;
48188 /* Allocate space for the WalIterator object. */
48189 nSegment = walFramePage(iLast) + 1;
48190 nByte = sizeof(WalIterator)
48191 + (nSegment-1)*sizeof(struct WalSegment)
48192 + iLast*sizeof(ht_slot);
48193 p = (WalIterator *)sqlite3ScratchMalloc(nByte);
48194 if( !p ){
48195 return SQLITE_NOMEM;
48197 memset(p, 0, nByte);
48198 p->nSegment = nSegment;
48200 /* Allocate temporary space used by the merge-sort routine. This block
48201 ** of memory will be freed before this function returns.
48203 aTmp = (ht_slot *)sqlite3ScratchMalloc(
48204 sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
48206 if( !aTmp ){
48207 rc = SQLITE_NOMEM;
48210 for(i=0; rc==SQLITE_OK && i<nSegment; i++){
48211 volatile ht_slot *aHash;
48212 u32 iZero;
48213 volatile u32 *aPgno;
48215 rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
48216 if( rc==SQLITE_OK ){
48217 int j; /* Counter variable */
48218 int nEntry; /* Number of entries in this segment */
48219 ht_slot *aIndex; /* Sorted index for this segment */
48221 aPgno++;
48222 if( (i+1)==nSegment ){
48223 nEntry = (int)(iLast - iZero);
48224 }else{
48225 nEntry = (int)((u32*)aHash - (u32*)aPgno);
48227 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
48228 iZero++;
48230 for(j=0; j<nEntry; j++){
48231 aIndex[j] = (ht_slot)j;
48233 walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
48234 p->aSegment[i].iZero = iZero;
48235 p->aSegment[i].nEntry = nEntry;
48236 p->aSegment[i].aIndex = aIndex;
48237 p->aSegment[i].aPgno = (u32 *)aPgno;
48240 sqlite3ScratchFree(aTmp);
48242 if( rc!=SQLITE_OK ){
48243 walIteratorFree(p);
48245 *pp = p;
48246 return rc;
48250 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
48251 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
48252 ** busy-handler function. Invoke it and retry the lock until either the
48253 ** lock is successfully obtained or the busy-handler returns 0.
48255 static int walBusyLock(
48256 Wal *pWal, /* WAL connection */
48257 int (*xBusy)(void*), /* Function to call when busy */
48258 void *pBusyArg, /* Context argument for xBusyHandler */
48259 int lockIdx, /* Offset of first byte to lock */
48260 int n /* Number of bytes to lock */
48262 int rc;
48263 do {
48264 rc = walLockExclusive(pWal, lockIdx, n);
48265 }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
48266 return rc;
48270 ** The cache of the wal-index header must be valid to call this function.
48271 ** Return the page-size in bytes used by the database.
48273 static int walPagesize(Wal *pWal){
48274 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48278 ** Copy as much content as we can from the WAL back into the database file
48279 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
48281 ** The amount of information copies from WAL to database might be limited
48282 ** by active readers. This routine will never overwrite a database page
48283 ** that a concurrent reader might be using.
48285 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
48286 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
48287 ** checkpoints are always run by a background thread or background
48288 ** process, foreground threads will never block on a lengthy fsync call.
48290 ** Fsync is called on the WAL before writing content out of the WAL and
48291 ** into the database. This ensures that if the new content is persistent
48292 ** in the WAL and can be recovered following a power-loss or hard reset.
48294 ** Fsync is also called on the database file if (and only if) the entire
48295 ** WAL content is copied into the database file. This second fsync makes
48296 ** it safe to delete the WAL since the new content will persist in the
48297 ** database file.
48299 ** This routine uses and updates the nBackfill field of the wal-index header.
48300 ** This is the only routine tha will increase the value of nBackfill.
48301 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
48302 ** its value.)
48304 ** The caller must be holding sufficient locks to ensure that no other
48305 ** checkpoint is running (in any other thread or process) at the same
48306 ** time.
48308 static int walCheckpoint(
48309 Wal *pWal, /* Wal connection */
48310 int eMode, /* One of PASSIVE, FULL or RESTART */
48311 int (*xBusyCall)(void*), /* Function to call when busy */
48312 void *pBusyArg, /* Context argument for xBusyHandler */
48313 int sync_flags, /* Flags for OsSync() (or 0) */
48314 u8 *zBuf /* Temporary buffer to use */
48316 int rc; /* Return code */
48317 int szPage; /* Database page-size */
48318 WalIterator *pIter = 0; /* Wal iterator context */
48319 u32 iDbpage = 0; /* Next database page to write */
48320 u32 iFrame = 0; /* Wal frame containing data for iDbpage */
48321 u32 mxSafeFrame; /* Max frame that can be backfilled */
48322 u32 mxPage; /* Max database page to write */
48323 int i; /* Loop counter */
48324 volatile WalCkptInfo *pInfo; /* The checkpoint status information */
48325 int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
48327 szPage = walPagesize(pWal);
48328 testcase( szPage<=32768 );
48329 testcase( szPage>=65536 );
48330 pInfo = walCkptInfo(pWal);
48331 if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
48333 /* Allocate the iterator */
48334 rc = walIteratorInit(pWal, &pIter);
48335 if( rc!=SQLITE_OK ){
48336 return rc;
48338 assert( pIter );
48340 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
48342 /* Compute in mxSafeFrame the index of the last frame of the WAL that is
48343 ** safe to write into the database. Frames beyond mxSafeFrame might
48344 ** overwrite database pages that are in use by active readers and thus
48345 ** cannot be backfilled from the WAL.
48347 mxSafeFrame = pWal->hdr.mxFrame;
48348 mxPage = pWal->hdr.nPage;
48349 for(i=1; i<WAL_NREADER; i++){
48350 u32 y = pInfo->aReadMark[i];
48351 if( mxSafeFrame>y ){
48352 assert( y<=pWal->hdr.mxFrame );
48353 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
48354 if( rc==SQLITE_OK ){
48355 pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
48356 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48357 }else if( rc==SQLITE_BUSY ){
48358 mxSafeFrame = y;
48359 xBusy = 0;
48360 }else{
48361 goto walcheckpoint_out;
48366 if( pInfo->nBackfill<mxSafeFrame
48367 && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
48369 i64 nSize; /* Current size of database file */
48370 u32 nBackfill = pInfo->nBackfill;
48372 /* Sync the WAL to disk */
48373 if( sync_flags ){
48374 rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
48377 /* If the database may grow as a result of this checkpoint, hint
48378 ** about the eventual size of the db file to the VFS layer.
48380 if( rc==SQLITE_OK ){
48381 i64 nReq = ((i64)mxPage * szPage);
48382 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
48383 if( rc==SQLITE_OK && nSize<nReq ){
48384 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
48389 /* Iterate through the contents of the WAL, copying data to the db file. */
48390 while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
48391 i64 iOffset;
48392 assert( walFramePgno(pWal, iFrame)==iDbpage );
48393 if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
48394 iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
48395 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
48396 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
48397 if( rc!=SQLITE_OK ) break;
48398 iOffset = (iDbpage-1)*(i64)szPage;
48399 testcase( IS_BIG_INT(iOffset) );
48400 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
48401 if( rc!=SQLITE_OK ) break;
48404 /* If work was actually accomplished... */
48405 if( rc==SQLITE_OK ){
48406 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
48407 i64 szDb = pWal->hdr.nPage*(i64)szPage;
48408 testcase( IS_BIG_INT(szDb) );
48409 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
48410 if( rc==SQLITE_OK && sync_flags ){
48411 rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
48414 if( rc==SQLITE_OK ){
48415 pInfo->nBackfill = mxSafeFrame;
48419 /* Release the reader lock held while backfilling */
48420 walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
48423 if( rc==SQLITE_BUSY ){
48424 /* Reset the return code so as not to report a checkpoint failure
48425 ** just because there are active readers. */
48426 rc = SQLITE_OK;
48429 /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
48430 ** file has been copied into the database file, then block until all
48431 ** readers have finished using the wal file. This ensures that the next
48432 ** process to write to the database restarts the wal file.
48434 if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48435 assert( pWal->writeLock );
48436 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
48437 rc = SQLITE_BUSY;
48438 }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
48439 assert( mxSafeFrame==pWal->hdr.mxFrame );
48440 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
48441 if( rc==SQLITE_OK ){
48442 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48447 walcheckpoint_out:
48448 walIteratorFree(pIter);
48449 return rc;
48453 ** If the WAL file is currently larger than nMax bytes in size, truncate
48454 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
48456 static void walLimitSize(Wal *pWal, i64 nMax){
48457 i64 sz;
48458 int rx;
48459 sqlite3BeginBenignMalloc();
48460 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
48461 if( rx==SQLITE_OK && (sz > nMax ) ){
48462 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
48464 sqlite3EndBenignMalloc();
48465 if( rx ){
48466 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
48471 ** Close a connection to a log file.
48473 SQLITE_PRIVATE int sqlite3WalClose(
48474 Wal *pWal, /* Wal to close */
48475 int sync_flags, /* Flags to pass to OsSync() (or 0) */
48476 int nBuf,
48477 u8 *zBuf /* Buffer of at least nBuf bytes */
48479 int rc = SQLITE_OK;
48480 if( pWal ){
48481 int isDelete = 0; /* True to unlink wal and wal-index files */
48483 /* If an EXCLUSIVE lock can be obtained on the database file (using the
48484 ** ordinary, rollback-mode locking methods, this guarantees that the
48485 ** connection associated with this log file is the only connection to
48486 ** the database. In this case checkpoint the database and unlink both
48487 ** the wal and wal-index files.
48489 ** The EXCLUSIVE lock is not released before returning.
48491 rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
48492 if( rc==SQLITE_OK ){
48493 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
48494 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
48496 rc = sqlite3WalCheckpoint(
48497 pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
48499 if( rc==SQLITE_OK ){
48500 int bPersist = -1;
48501 sqlite3OsFileControlHint(
48502 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
48504 if( bPersist!=1 ){
48505 /* Try to delete the WAL file if the checkpoint completed and
48506 ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
48507 ** mode (!bPersist) */
48508 isDelete = 1;
48509 }else if( pWal->mxWalSize>=0 ){
48510 /* Try to truncate the WAL file to zero bytes if the checkpoint
48511 ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
48512 ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
48513 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
48514 ** to zero bytes as truncating to the journal_size_limit might
48515 ** leave a corrupt WAL file on disk. */
48516 walLimitSize(pWal, 0);
48521 walIndexClose(pWal, isDelete);
48522 sqlite3OsClose(pWal->pWalFd);
48523 if( isDelete ){
48524 sqlite3BeginBenignMalloc();
48525 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
48526 sqlite3EndBenignMalloc();
48528 WALTRACE(("WAL%p: closed\n", pWal));
48529 sqlite3_free((void *)pWal->apWiData);
48530 sqlite3_free(pWal);
48532 return rc;
48536 ** Try to read the wal-index header. Return 0 on success and 1 if
48537 ** there is a problem.
48539 ** The wal-index is in shared memory. Another thread or process might
48540 ** be writing the header at the same time this procedure is trying to
48541 ** read it, which might result in inconsistency. A dirty read is detected
48542 ** by verifying that both copies of the header are the same and also by
48543 ** a checksum on the header.
48545 ** If and only if the read is consistent and the header is different from
48546 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
48547 ** and *pChanged is set to 1.
48549 ** If the checksum cannot be verified return non-zero. If the header
48550 ** is read successfully and the checksum verified, return zero.
48552 static int walIndexTryHdr(Wal *pWal, int *pChanged){
48553 u32 aCksum[2]; /* Checksum on the header content */
48554 WalIndexHdr h1, h2; /* Two copies of the header content */
48555 WalIndexHdr volatile *aHdr; /* Header in shared memory */
48557 /* The first page of the wal-index must be mapped at this point. */
48558 assert( pWal->nWiData>0 && pWal->apWiData[0] );
48560 /* Read the header. This might happen concurrently with a write to the
48561 ** same area of shared memory on a different CPU in a SMP,
48562 ** meaning it is possible that an inconsistent snapshot is read
48563 ** from the file. If this happens, return non-zero.
48565 ** There are two copies of the header at the beginning of the wal-index.
48566 ** When reading, read [0] first then [1]. Writes are in the reverse order.
48567 ** Memory barriers are used to prevent the compiler or the hardware from
48568 ** reordering the reads and writes.
48570 aHdr = walIndexHdr(pWal);
48571 memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
48572 walShmBarrier(pWal);
48573 memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
48575 if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
48576 return 1; /* Dirty read */
48578 if( h1.isInit==0 ){
48579 return 1; /* Malformed header - probably all zeros */
48581 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
48582 if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
48583 return 1; /* Checksum does not match */
48586 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
48587 *pChanged = 1;
48588 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
48589 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
48590 testcase( pWal->szPage<=32768 );
48591 testcase( pWal->szPage>=65536 );
48594 /* The header was successfully read. Return zero. */
48595 return 0;
48599 ** Read the wal-index header from the wal-index and into pWal->hdr.
48600 ** If the wal-header appears to be corrupt, try to reconstruct the
48601 ** wal-index from the WAL before returning.
48603 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
48604 ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
48605 ** to 0.
48607 ** If the wal-index header is successfully read, return SQLITE_OK.
48608 ** Otherwise an SQLite error code.
48610 static int walIndexReadHdr(Wal *pWal, int *pChanged){
48611 int rc; /* Return code */
48612 int badHdr; /* True if a header read failed */
48613 volatile u32 *page0; /* Chunk of wal-index containing header */
48615 /* Ensure that page 0 of the wal-index (the page that contains the
48616 ** wal-index header) is mapped. Return early if an error occurs here.
48618 assert( pChanged );
48619 rc = walIndexPage(pWal, 0, &page0);
48620 if( rc!=SQLITE_OK ){
48621 return rc;
48623 assert( page0 || pWal->writeLock==0 );
48625 /* If the first page of the wal-index has been mapped, try to read the
48626 ** wal-index header immediately, without holding any lock. This usually
48627 ** works, but may fail if the wal-index header is corrupt or currently
48628 ** being modified by another thread or process.
48630 badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
48632 /* If the first attempt failed, it might have been due to a race
48633 ** with a writer. So get a WRITE lock and try again.
48635 assert( badHdr==0 || pWal->writeLock==0 );
48636 if( badHdr ){
48637 if( pWal->readOnly & WAL_SHM_RDONLY ){
48638 if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
48639 walUnlockShared(pWal, WAL_WRITE_LOCK);
48640 rc = SQLITE_READONLY_RECOVERY;
48642 }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
48643 pWal->writeLock = 1;
48644 if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
48645 badHdr = walIndexTryHdr(pWal, pChanged);
48646 if( badHdr ){
48647 /* If the wal-index header is still malformed even while holding
48648 ** a WRITE lock, it can only mean that the header is corrupted and
48649 ** needs to be reconstructed. So run recovery to do exactly that.
48651 rc = walIndexRecover(pWal);
48652 *pChanged = 1;
48655 pWal->writeLock = 0;
48656 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
48660 /* If the header is read successfully, check the version number to make
48661 ** sure the wal-index was not constructed with some future format that
48662 ** this version of SQLite cannot understand.
48664 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
48665 rc = SQLITE_CANTOPEN_BKPT;
48668 return rc;
48672 ** This is the value that walTryBeginRead returns when it needs to
48673 ** be retried.
48675 #define WAL_RETRY (-1)
48678 ** Attempt to start a read transaction. This might fail due to a race or
48679 ** other transient condition. When that happens, it returns WAL_RETRY to
48680 ** indicate to the caller that it is safe to retry immediately.
48682 ** On success return SQLITE_OK. On a permanent failure (such an
48683 ** I/O error or an SQLITE_BUSY because another process is running
48684 ** recovery) return a positive error code.
48686 ** The useWal parameter is true to force the use of the WAL and disable
48687 ** the case where the WAL is bypassed because it has been completely
48688 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
48689 ** to make a copy of the wal-index header into pWal->hdr. If the
48690 ** wal-index header has changed, *pChanged is set to 1 (as an indication
48691 ** to the caller that the local paget cache is obsolete and needs to be
48692 ** flushed.) When useWal==1, the wal-index header is assumed to already
48693 ** be loaded and the pChanged parameter is unused.
48695 ** The caller must set the cnt parameter to the number of prior calls to
48696 ** this routine during the current read attempt that returned WAL_RETRY.
48697 ** This routine will start taking more aggressive measures to clear the
48698 ** race conditions after multiple WAL_RETRY returns, and after an excessive
48699 ** number of errors will ultimately return SQLITE_PROTOCOL. The
48700 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
48701 ** and is not honoring the locking protocol. There is a vanishingly small
48702 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
48703 ** bad luck when there is lots of contention for the wal-index, but that
48704 ** possibility is so small that it can be safely neglected, we believe.
48706 ** On success, this routine obtains a read lock on
48707 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
48708 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
48709 ** that means the Wal does not hold any read lock. The reader must not
48710 ** access any database page that is modified by a WAL frame up to and
48711 ** including frame number aReadMark[pWal->readLock]. The reader will
48712 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
48713 ** Or if pWal->readLock==0, then the reader will ignore the WAL
48714 ** completely and get all content directly from the database file.
48715 ** If the useWal parameter is 1 then the WAL will never be ignored and
48716 ** this routine will always set pWal->readLock>0 on success.
48717 ** When the read transaction is completed, the caller must release the
48718 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
48720 ** This routine uses the nBackfill and aReadMark[] fields of the header
48721 ** to select a particular WAL_READ_LOCK() that strives to let the
48722 ** checkpoint process do as much work as possible. This routine might
48723 ** update values of the aReadMark[] array in the header, but if it does
48724 ** so it takes care to hold an exclusive lock on the corresponding
48725 ** WAL_READ_LOCK() while changing values.
48727 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
48728 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
48729 u32 mxReadMark; /* Largest aReadMark[] value */
48730 int mxI; /* Index of largest aReadMark[] value */
48731 int i; /* Loop counter */
48732 int rc = SQLITE_OK; /* Return code */
48734 assert( pWal->readLock<0 ); /* Not currently locked */
48736 /* Take steps to avoid spinning forever if there is a protocol error.
48738 ** Circumstances that cause a RETRY should only last for the briefest
48739 ** instances of time. No I/O or other system calls are done while the
48740 ** locks are held, so the locks should not be held for very long. But
48741 ** if we are unlucky, another process that is holding a lock might get
48742 ** paged out or take a page-fault that is time-consuming to resolve,
48743 ** during the few nanoseconds that it is holding the lock. In that case,
48744 ** it might take longer than normal for the lock to free.
48746 ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
48747 ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
48748 ** is more of a scheduler yield than an actual delay. But on the 10th
48749 ** an subsequent retries, the delays start becoming longer and longer,
48750 ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
48751 ** The total delay time before giving up is less than 1 second.
48753 if( cnt>5 ){
48754 int nDelay = 1; /* Pause time in microseconds */
48755 if( cnt>100 ){
48756 VVA_ONLY( pWal->lockError = 1; )
48757 return SQLITE_PROTOCOL;
48759 if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
48760 sqlite3OsSleep(pWal->pVfs, nDelay);
48763 if( !useWal ){
48764 rc = walIndexReadHdr(pWal, pChanged);
48765 if( rc==SQLITE_BUSY ){
48766 /* If there is not a recovery running in another thread or process
48767 ** then convert BUSY errors to WAL_RETRY. If recovery is known to
48768 ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
48769 ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
48770 ** would be technically correct. But the race is benign since with
48771 ** WAL_RETRY this routine will be called again and will probably be
48772 ** right on the second iteration.
48774 if( pWal->apWiData[0]==0 ){
48775 /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
48776 ** We assume this is a transient condition, so return WAL_RETRY. The
48777 ** xShmMap() implementation used by the default unix and win32 VFS
48778 ** modules may return SQLITE_BUSY due to a race condition in the
48779 ** code that determines whether or not the shared-memory region
48780 ** must be zeroed before the requested page is returned.
48782 rc = WAL_RETRY;
48783 }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
48784 walUnlockShared(pWal, WAL_RECOVER_LOCK);
48785 rc = WAL_RETRY;
48786 }else if( rc==SQLITE_BUSY ){
48787 rc = SQLITE_BUSY_RECOVERY;
48790 if( rc!=SQLITE_OK ){
48791 return rc;
48795 pInfo = walCkptInfo(pWal);
48796 if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
48797 /* The WAL has been completely backfilled (or it is empty).
48798 ** and can be safely ignored.
48800 rc = walLockShared(pWal, WAL_READ_LOCK(0));
48801 walShmBarrier(pWal);
48802 if( rc==SQLITE_OK ){
48803 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
48804 /* It is not safe to allow the reader to continue here if frames
48805 ** may have been appended to the log before READ_LOCK(0) was obtained.
48806 ** When holding READ_LOCK(0), the reader ignores the entire log file,
48807 ** which implies that the database file contains a trustworthy
48808 ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
48809 ** happening, this is usually correct.
48811 ** However, if frames have been appended to the log (or if the log
48812 ** is wrapped and written for that matter) before the READ_LOCK(0)
48813 ** is obtained, that is not necessarily true. A checkpointer may
48814 ** have started to backfill the appended frames but crashed before
48815 ** it finished. Leaving a corrupt image in the database file.
48817 walUnlockShared(pWal, WAL_READ_LOCK(0));
48818 return WAL_RETRY;
48820 pWal->readLock = 0;
48821 return SQLITE_OK;
48822 }else if( rc!=SQLITE_BUSY ){
48823 return rc;
48827 /* If we get this far, it means that the reader will want to use
48828 ** the WAL to get at content from recent commits. The job now is
48829 ** to select one of the aReadMark[] entries that is closest to
48830 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
48832 mxReadMark = 0;
48833 mxI = 0;
48834 for(i=1; i<WAL_NREADER; i++){
48835 u32 thisMark = pInfo->aReadMark[i];
48836 if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
48837 assert( thisMark!=READMARK_NOT_USED );
48838 mxReadMark = thisMark;
48839 mxI = i;
48842 /* There was once an "if" here. The extra "{" is to preserve indentation. */
48844 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
48845 && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
48847 for(i=1; i<WAL_NREADER; i++){
48848 rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
48849 if( rc==SQLITE_OK ){
48850 mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
48851 mxI = i;
48852 walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
48853 break;
48854 }else if( rc!=SQLITE_BUSY ){
48855 return rc;
48859 if( mxI==0 ){
48860 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
48861 return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
48864 rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
48865 if( rc ){
48866 return rc==SQLITE_BUSY ? WAL_RETRY : rc;
48868 /* Now that the read-lock has been obtained, check that neither the
48869 ** value in the aReadMark[] array or the contents of the wal-index
48870 ** header have changed.
48872 ** It is necessary to check that the wal-index header did not change
48873 ** between the time it was read and when the shared-lock was obtained
48874 ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
48875 ** that the log file may have been wrapped by a writer, or that frames
48876 ** that occur later in the log than pWal->hdr.mxFrame may have been
48877 ** copied into the database by a checkpointer. If either of these things
48878 ** happened, then reading the database with the current value of
48879 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
48880 ** instead.
48882 ** This does not guarantee that the copy of the wal-index header is up to
48883 ** date before proceeding. That would not be possible without somehow
48884 ** blocking writers. It only guarantees that a dangerous checkpoint or
48885 ** log-wrap (either of which would require an exclusive lock on
48886 ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
48888 walShmBarrier(pWal);
48889 if( pInfo->aReadMark[mxI]!=mxReadMark
48890 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
48892 walUnlockShared(pWal, WAL_READ_LOCK(mxI));
48893 return WAL_RETRY;
48894 }else{
48895 assert( mxReadMark<=pWal->hdr.mxFrame );
48896 pWal->readLock = (i16)mxI;
48899 return rc;
48903 ** Begin a read transaction on the database.
48905 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
48906 ** it takes a snapshot of the state of the WAL and wal-index for the current
48907 ** instant in time. The current thread will continue to use this snapshot.
48908 ** Other threads might append new content to the WAL and wal-index but
48909 ** that extra content is ignored by the current thread.
48911 ** If the database contents have changes since the previous read
48912 ** transaction, then *pChanged is set to 1 before returning. The
48913 ** Pager layer will use this to know that is cache is stale and
48914 ** needs to be flushed.
48916 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
48917 int rc; /* Return code */
48918 int cnt = 0; /* Number of TryBeginRead attempts */
48921 rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
48922 }while( rc==WAL_RETRY );
48923 testcase( (rc&0xff)==SQLITE_BUSY );
48924 testcase( (rc&0xff)==SQLITE_IOERR );
48925 testcase( rc==SQLITE_PROTOCOL );
48926 testcase( rc==SQLITE_OK );
48927 return rc;
48931 ** Finish with a read transaction. All this does is release the
48932 ** read-lock.
48934 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
48935 sqlite3WalEndWriteTransaction(pWal);
48936 if( pWal->readLock>=0 ){
48937 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48938 pWal->readLock = -1;
48943 ** Search the wal file for page pgno. If found, set *piRead to the frame that
48944 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
48945 ** to zero.
48947 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
48948 ** error does occur, the final value of *piRead is undefined.
48950 SQLITE_PRIVATE int sqlite3WalFindFrame(
48951 Wal *pWal, /* WAL handle */
48952 Pgno pgno, /* Database page number to read data for */
48953 u32 *piRead /* OUT: Frame number (or zero) */
48955 u32 iRead = 0; /* If !=0, WAL frame to return data from */
48956 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
48957 int iHash; /* Used to loop through N hash tables */
48959 /* This routine is only be called from within a read transaction. */
48960 assert( pWal->readLock>=0 || pWal->lockError );
48962 /* If the "last page" field of the wal-index header snapshot is 0, then
48963 ** no data will be read from the wal under any circumstances. Return early
48964 ** in this case as an optimization. Likewise, if pWal->readLock==0,
48965 ** then the WAL is ignored by the reader so return early, as if the
48966 ** WAL were empty.
48968 if( iLast==0 || pWal->readLock==0 ){
48969 *piRead = 0;
48970 return SQLITE_OK;
48973 /* Search the hash table or tables for an entry matching page number
48974 ** pgno. Each iteration of the following for() loop searches one
48975 ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
48977 ** This code might run concurrently to the code in walIndexAppend()
48978 ** that adds entries to the wal-index (and possibly to this hash
48979 ** table). This means the value just read from the hash
48980 ** slot (aHash[iKey]) may have been added before or after the
48981 ** current read transaction was opened. Values added after the
48982 ** read transaction was opened may have been written incorrectly -
48983 ** i.e. these slots may contain garbage data. However, we assume
48984 ** that any slots written before the current read transaction was
48985 ** opened remain unmodified.
48987 ** For the reasons above, the if(...) condition featured in the inner
48988 ** loop of the following block is more stringent that would be required
48989 ** if we had exclusive access to the hash-table:
48991 ** (aPgno[iFrame]==pgno):
48992 ** This condition filters out normal hash-table collisions.
48994 ** (iFrame<=iLast):
48995 ** This condition filters out entries that were added to the hash
48996 ** table after the current read-transaction had started.
48998 for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
48999 volatile ht_slot *aHash; /* Pointer to hash table */
49000 volatile u32 *aPgno; /* Pointer to array of page numbers */
49001 u32 iZero; /* Frame number corresponding to aPgno[0] */
49002 int iKey; /* Hash slot index */
49003 int nCollide; /* Number of hash collisions remaining */
49004 int rc; /* Error code */
49006 rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
49007 if( rc!=SQLITE_OK ){
49008 return rc;
49010 nCollide = HASHTABLE_NSLOT;
49011 for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
49012 u32 iFrame = aHash[iKey] + iZero;
49013 if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
49014 /* assert( iFrame>iRead ); -- not true if there is corruption */
49015 iRead = iFrame;
49017 if( (nCollide--)==0 ){
49018 return SQLITE_CORRUPT_BKPT;
49023 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49024 /* If expensive assert() statements are available, do a linear search
49025 ** of the wal-index file content. Make sure the results agree with the
49026 ** result obtained using the hash indexes above. */
49028 u32 iRead2 = 0;
49029 u32 iTest;
49030 for(iTest=iLast; iTest>0; iTest--){
49031 if( walFramePgno(pWal, iTest)==pgno ){
49032 iRead2 = iTest;
49033 break;
49036 assert( iRead==iRead2 );
49038 #endif
49040 *piRead = iRead;
49041 return SQLITE_OK;
49045 ** Read the contents of frame iRead from the wal file into buffer pOut
49046 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
49047 ** error code otherwise.
49049 SQLITE_PRIVATE int sqlite3WalReadFrame(
49050 Wal *pWal, /* WAL handle */
49051 u32 iRead, /* Frame to read */
49052 int nOut, /* Size of buffer pOut in bytes */
49053 u8 *pOut /* Buffer to write page data to */
49055 int sz;
49056 i64 iOffset;
49057 sz = pWal->hdr.szPage;
49058 sz = (sz&0xfe00) + ((sz&0x0001)<<16);
49059 testcase( sz<=32768 );
49060 testcase( sz>=65536 );
49061 iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
49062 /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
49063 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
49067 ** Return the size of the database in pages (or zero, if unknown).
49069 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
49070 if( pWal && ALWAYS(pWal->readLock>=0) ){
49071 return pWal->hdr.nPage;
49073 return 0;
49078 ** This function starts a write transaction on the WAL.
49080 ** A read transaction must have already been started by a prior call
49081 ** to sqlite3WalBeginReadTransaction().
49083 ** If another thread or process has written into the database since
49084 ** the read transaction was started, then it is not possible for this
49085 ** thread to write as doing so would cause a fork. So this routine
49086 ** returns SQLITE_BUSY in that case and no write transaction is started.
49088 ** There can only be a single writer active at a time.
49090 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
49091 int rc;
49093 /* Cannot start a write transaction without first holding a read
49094 ** transaction. */
49095 assert( pWal->readLock>=0 );
49097 if( pWal->readOnly ){
49098 return SQLITE_READONLY;
49101 /* Only one writer allowed at a time. Get the write lock. Return
49102 ** SQLITE_BUSY if unable.
49104 rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
49105 if( rc ){
49106 return rc;
49108 pWal->writeLock = 1;
49110 /* If another connection has written to the database file since the
49111 ** time the read transaction on this connection was started, then
49112 ** the write is disallowed.
49114 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
49115 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49116 pWal->writeLock = 0;
49117 rc = SQLITE_BUSY_SNAPSHOT;
49120 return rc;
49124 ** End a write transaction. The commit has already been done. This
49125 ** routine merely releases the lock.
49127 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
49128 if( pWal->writeLock ){
49129 walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
49130 pWal->writeLock = 0;
49131 pWal->truncateOnCommit = 0;
49133 return SQLITE_OK;
49137 ** If any data has been written (but not committed) to the log file, this
49138 ** function moves the write-pointer back to the start of the transaction.
49140 ** Additionally, the callback function is invoked for each frame written
49141 ** to the WAL since the start of the transaction. If the callback returns
49142 ** other than SQLITE_OK, it is not invoked again and the error code is
49143 ** returned to the caller.
49145 ** Otherwise, if the callback function does not return an error, this
49146 ** function returns SQLITE_OK.
49148 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
49149 int rc = SQLITE_OK;
49150 if( ALWAYS(pWal->writeLock) ){
49151 Pgno iMax = pWal->hdr.mxFrame;
49152 Pgno iFrame;
49154 /* Restore the clients cache of the wal-index header to the state it
49155 ** was in before the client began writing to the database.
49157 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
49159 for(iFrame=pWal->hdr.mxFrame+1;
49160 ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
49161 iFrame++
49163 /* This call cannot fail. Unless the page for which the page number
49164 ** is passed as the second argument is (a) in the cache and
49165 ** (b) has an outstanding reference, then xUndo is either a no-op
49166 ** (if (a) is false) or simply expels the page from the cache (if (b)
49167 ** is false).
49169 ** If the upper layer is doing a rollback, it is guaranteed that there
49170 ** are no outstanding references to any page other than page 1. And
49171 ** page 1 is never written to the log until the transaction is
49172 ** committed. As a result, the call to xUndo may not fail.
49174 assert( walFramePgno(pWal, iFrame)!=1 );
49175 rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
49177 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
49179 assert( rc==SQLITE_OK );
49180 return rc;
49184 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
49185 ** values. This function populates the array with values required to
49186 ** "rollback" the write position of the WAL handle back to the current
49187 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
49189 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
49190 assert( pWal->writeLock );
49191 aWalData[0] = pWal->hdr.mxFrame;
49192 aWalData[1] = pWal->hdr.aFrameCksum[0];
49193 aWalData[2] = pWal->hdr.aFrameCksum[1];
49194 aWalData[3] = pWal->nCkpt;
49198 ** Move the write position of the WAL back to the point identified by
49199 ** the values in the aWalData[] array. aWalData must point to an array
49200 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
49201 ** by a call to WalSavepoint().
49203 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
49204 int rc = SQLITE_OK;
49206 assert( pWal->writeLock );
49207 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
49209 if( aWalData[3]!=pWal->nCkpt ){
49210 /* This savepoint was opened immediately after the write-transaction
49211 ** was started. Right after that, the writer decided to wrap around
49212 ** to the start of the log. Update the savepoint values to match.
49214 aWalData[0] = 0;
49215 aWalData[3] = pWal->nCkpt;
49218 if( aWalData[0]<pWal->hdr.mxFrame ){
49219 pWal->hdr.mxFrame = aWalData[0];
49220 pWal->hdr.aFrameCksum[0] = aWalData[1];
49221 pWal->hdr.aFrameCksum[1] = aWalData[2];
49222 walCleanupHash(pWal);
49225 return rc;
49230 ** This function is called just before writing a set of frames to the log
49231 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
49232 ** to the current log file, it is possible to overwrite the start of the
49233 ** existing log file with the new frames (i.e. "reset" the log). If so,
49234 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
49235 ** unchanged.
49237 ** SQLITE_OK is returned if no error is encountered (regardless of whether
49238 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
49239 ** if an error occurs.
49241 static int walRestartLog(Wal *pWal){
49242 int rc = SQLITE_OK;
49243 int cnt;
49245 if( pWal->readLock==0 ){
49246 volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
49247 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
49248 if( pInfo->nBackfill>0 ){
49249 u32 salt1;
49250 sqlite3_randomness(4, &salt1);
49251 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49252 if( rc==SQLITE_OK ){
49253 /* If all readers are using WAL_READ_LOCK(0) (in other words if no
49254 ** readers are currently using the WAL), then the transactions
49255 ** frames will overwrite the start of the existing log. Update the
49256 ** wal-index header to reflect this.
49258 ** In theory it would be Ok to update the cache of the header only
49259 ** at this point. But updating the actual wal-index header is also
49260 ** safe and means there is no special case for sqlite3WalUndo()
49261 ** to handle if this transaction is rolled back.
49263 int i; /* Loop counter */
49264 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
49266 pWal->nCkpt++;
49267 pWal->hdr.mxFrame = 0;
49268 sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
49269 aSalt[1] = salt1;
49270 walIndexWriteHdr(pWal);
49271 pInfo->nBackfill = 0;
49272 pInfo->aReadMark[1] = 0;
49273 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
49274 assert( pInfo->aReadMark[0]==0 );
49275 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
49276 }else if( rc!=SQLITE_BUSY ){
49277 return rc;
49280 walUnlockShared(pWal, WAL_READ_LOCK(0));
49281 pWal->readLock = -1;
49282 cnt = 0;
49284 int notUsed;
49285 rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
49286 }while( rc==WAL_RETRY );
49287 assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
49288 testcase( (rc&0xff)==SQLITE_IOERR );
49289 testcase( rc==SQLITE_PROTOCOL );
49290 testcase( rc==SQLITE_OK );
49292 return rc;
49296 ** Information about the current state of the WAL file and where
49297 ** the next fsync should occur - passed from sqlite3WalFrames() into
49298 ** walWriteToLog().
49300 typedef struct WalWriter {
49301 Wal *pWal; /* The complete WAL information */
49302 sqlite3_file *pFd; /* The WAL file to which we write */
49303 sqlite3_int64 iSyncPoint; /* Fsync at this offset */
49304 int syncFlags; /* Flags for the fsync */
49305 int szPage; /* Size of one page */
49306 } WalWriter;
49309 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
49310 ** Do a sync when crossing the p->iSyncPoint boundary.
49312 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
49313 ** first write the part before iSyncPoint, then sync, then write the
49314 ** rest.
49316 static int walWriteToLog(
49317 WalWriter *p, /* WAL to write to */
49318 void *pContent, /* Content to be written */
49319 int iAmt, /* Number of bytes to write */
49320 sqlite3_int64 iOffset /* Start writing at this offset */
49322 int rc;
49323 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
49324 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
49325 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
49326 if( rc ) return rc;
49327 iOffset += iFirstAmt;
49328 iAmt -= iFirstAmt;
49329 pContent = (void*)(iFirstAmt + (char*)pContent);
49330 assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
49331 rc = sqlite3OsSync(p->pFd, p->syncFlags);
49332 if( iAmt==0 || rc ) return rc;
49334 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
49335 return rc;
49339 ** Write out a single frame of the WAL
49341 static int walWriteOneFrame(
49342 WalWriter *p, /* Where to write the frame */
49343 PgHdr *pPage, /* The page of the frame to be written */
49344 int nTruncate, /* The commit flag. Usually 0. >0 for commit */
49345 sqlite3_int64 iOffset /* Byte offset at which to write */
49347 int rc; /* Result code from subfunctions */
49348 void *pData; /* Data actually written */
49349 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
49350 #if defined(SQLITE_HAS_CODEC)
49351 if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
49352 #else
49353 pData = pPage->pData;
49354 #endif
49355 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
49356 rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
49357 if( rc ) return rc;
49358 /* Write the page data */
49359 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
49360 return rc;
49364 ** Write a set of frames to the log. The caller must hold the write-lock
49365 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
49367 SQLITE_PRIVATE int sqlite3WalFrames(
49368 Wal *pWal, /* Wal handle to write to */
49369 int szPage, /* Database page-size in bytes */
49370 PgHdr *pList, /* List of dirty pages to write */
49371 Pgno nTruncate, /* Database size after this commit */
49372 int isCommit, /* True if this is a commit */
49373 int sync_flags /* Flags to pass to OsSync() (or 0) */
49375 int rc; /* Used to catch return codes */
49376 u32 iFrame; /* Next frame address */
49377 PgHdr *p; /* Iterator to run through pList with. */
49378 PgHdr *pLast = 0; /* Last frame in list */
49379 int nExtra = 0; /* Number of extra copies of last page */
49380 int szFrame; /* The size of a single frame */
49381 i64 iOffset; /* Next byte to write in WAL file */
49382 WalWriter w; /* The writer */
49384 assert( pList );
49385 assert( pWal->writeLock );
49387 /* If this frame set completes a transaction, then nTruncate>0. If
49388 ** nTruncate==0 then this frame set does not complete the transaction. */
49389 assert( (isCommit!=0)==(nTruncate!=0) );
49391 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49392 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
49393 WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
49394 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
49396 #endif
49398 /* See if it is possible to write these frames into the start of the
49399 ** log file, instead of appending to it at pWal->hdr.mxFrame.
49401 if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
49402 return rc;
49405 /* If this is the first frame written into the log, write the WAL
49406 ** header to the start of the WAL file. See comments at the top of
49407 ** this source file for a description of the WAL header format.
49409 iFrame = pWal->hdr.mxFrame;
49410 if( iFrame==0 ){
49411 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
49412 u32 aCksum[2]; /* Checksum for wal-header */
49414 sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
49415 sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
49416 sqlite3Put4byte(&aWalHdr[8], szPage);
49417 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
49418 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
49419 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
49420 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
49421 sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
49422 sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
49424 pWal->szPage = szPage;
49425 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
49426 pWal->hdr.aFrameCksum[0] = aCksum[0];
49427 pWal->hdr.aFrameCksum[1] = aCksum[1];
49428 pWal->truncateOnCommit = 1;
49430 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
49431 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
49432 if( rc!=SQLITE_OK ){
49433 return rc;
49436 /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
49437 ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
49438 ** an out-of-order write following a WAL restart could result in
49439 ** database corruption. See the ticket:
49441 ** http://localhost:591/sqlite/info/ff5be73dee
49443 if( pWal->syncHeader && sync_flags ){
49444 rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
49445 if( rc ) return rc;
49448 assert( (int)pWal->szPage==szPage );
49450 /* Setup information needed to write frames into the WAL */
49451 w.pWal = pWal;
49452 w.pFd = pWal->pWalFd;
49453 w.iSyncPoint = 0;
49454 w.syncFlags = sync_flags;
49455 w.szPage = szPage;
49456 iOffset = walFrameOffset(iFrame+1, szPage);
49457 szFrame = szPage + WAL_FRAME_HDRSIZE;
49459 /* Write all frames into the log file exactly once */
49460 for(p=pList; p; p=p->pDirty){
49461 int nDbSize; /* 0 normally. Positive == commit flag */
49462 iFrame++;
49463 assert( iOffset==walFrameOffset(iFrame, szPage) );
49464 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
49465 rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
49466 if( rc ) return rc;
49467 pLast = p;
49468 iOffset += szFrame;
49471 /* If this is the end of a transaction, then we might need to pad
49472 ** the transaction and/or sync the WAL file.
49474 ** Padding and syncing only occur if this set of frames complete a
49475 ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
49476 ** or synchonous==OFF, then no padding or syncing are needed.
49478 ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
49479 ** needed and only the sync is done. If padding is needed, then the
49480 ** final frame is repeated (with its commit mark) until the next sector
49481 ** boundary is crossed. Only the part of the WAL prior to the last
49482 ** sector boundary is synced; the part of the last frame that extends
49483 ** past the sector boundary is written after the sync.
49485 if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
49486 if( pWal->padToSectorBoundary ){
49487 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
49488 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
49489 while( iOffset<w.iSyncPoint ){
49490 rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
49491 if( rc ) return rc;
49492 iOffset += szFrame;
49493 nExtra++;
49495 }else{
49496 rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
49500 /* If this frame set completes the first transaction in the WAL and
49501 ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
49502 ** journal size limit, if possible.
49504 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
49505 i64 sz = pWal->mxWalSize;
49506 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
49507 sz = walFrameOffset(iFrame+nExtra+1, szPage);
49509 walLimitSize(pWal, sz);
49510 pWal->truncateOnCommit = 0;
49513 /* Append data to the wal-index. It is not necessary to lock the
49514 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
49515 ** guarantees that there are no other writers, and no data that may
49516 ** be in use by existing readers is being overwritten.
49518 iFrame = pWal->hdr.mxFrame;
49519 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
49520 iFrame++;
49521 rc = walIndexAppend(pWal, iFrame, p->pgno);
49523 while( rc==SQLITE_OK && nExtra>0 ){
49524 iFrame++;
49525 nExtra--;
49526 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
49529 if( rc==SQLITE_OK ){
49530 /* Update the private copy of the header. */
49531 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
49532 testcase( szPage<=32768 );
49533 testcase( szPage>=65536 );
49534 pWal->hdr.mxFrame = iFrame;
49535 if( isCommit ){
49536 pWal->hdr.iChange++;
49537 pWal->hdr.nPage = nTruncate;
49539 /* If this is a commit, update the wal-index header too. */
49540 if( isCommit ){
49541 walIndexWriteHdr(pWal);
49542 pWal->iCallback = iFrame;
49546 WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
49547 return rc;
49551 ** This routine is called to implement sqlite3_wal_checkpoint() and
49552 ** related interfaces.
49554 ** Obtain a CHECKPOINT lock and then backfill as much information as
49555 ** we can from WAL into the database.
49557 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
49558 ** callback. In this case this function runs a blocking checkpoint.
49560 SQLITE_PRIVATE int sqlite3WalCheckpoint(
49561 Wal *pWal, /* Wal connection */
49562 int eMode, /* PASSIVE, FULL or RESTART */
49563 int (*xBusy)(void*), /* Function to call when busy */
49564 void *pBusyArg, /* Context argument for xBusyHandler */
49565 int sync_flags, /* Flags to sync db file with (or 0) */
49566 int nBuf, /* Size of temporary buffer */
49567 u8 *zBuf, /* Temporary buffer to use */
49568 int *pnLog, /* OUT: Number of frames in WAL */
49569 int *pnCkpt /* OUT: Number of backfilled frames in WAL */
49571 int rc; /* Return code */
49572 int isChanged = 0; /* True if a new wal-index header is loaded */
49573 int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
49575 assert( pWal->ckptLock==0 );
49576 assert( pWal->writeLock==0 );
49578 if( pWal->readOnly ) return SQLITE_READONLY;
49579 WALTRACE(("WAL%p: checkpoint begins\n", pWal));
49580 rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
49581 if( rc ){
49582 /* Usually this is SQLITE_BUSY meaning that another thread or process
49583 ** is already running a checkpoint, or maybe a recovery. But it might
49584 ** also be SQLITE_IOERR. */
49585 return rc;
49587 pWal->ckptLock = 1;
49589 /* If this is a blocking-checkpoint, then obtain the write-lock as well
49590 ** to prevent any writers from running while the checkpoint is underway.
49591 ** This has to be done before the call to walIndexReadHdr() below.
49593 ** If the writer lock cannot be obtained, then a passive checkpoint is
49594 ** run instead. Since the checkpointer is not holding the writer lock,
49595 ** there is no point in blocking waiting for any readers. Assuming no
49596 ** other error occurs, this function will return SQLITE_BUSY to the caller.
49598 if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
49599 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
49600 if( rc==SQLITE_OK ){
49601 pWal->writeLock = 1;
49602 }else if( rc==SQLITE_BUSY ){
49603 eMode2 = SQLITE_CHECKPOINT_PASSIVE;
49604 rc = SQLITE_OK;
49608 /* Read the wal-index header. */
49609 if( rc==SQLITE_OK ){
49610 rc = walIndexReadHdr(pWal, &isChanged);
49611 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
49612 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
49616 /* Copy data from the log to the database file. */
49617 if( rc==SQLITE_OK ){
49618 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
49619 rc = SQLITE_CORRUPT_BKPT;
49620 }else{
49621 rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
49624 /* If no error occurred, set the output variables. */
49625 if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
49626 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
49627 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
49631 if( isChanged ){
49632 /* If a new wal-index header was loaded before the checkpoint was
49633 ** performed, then the pager-cache associated with pWal is now
49634 ** out of date. So zero the cached wal-index header to ensure that
49635 ** next time the pager opens a snapshot on this database it knows that
49636 ** the cache needs to be reset.
49638 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49641 /* Release the locks. */
49642 sqlite3WalEndWriteTransaction(pWal);
49643 walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
49644 pWal->ckptLock = 0;
49645 WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
49646 return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
49649 /* Return the value to pass to a sqlite3_wal_hook callback, the
49650 ** number of frames in the WAL at the point of the last commit since
49651 ** sqlite3WalCallback() was called. If no commits have occurred since
49652 ** the last call, then return 0.
49654 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
49655 u32 ret = 0;
49656 if( pWal ){
49657 ret = pWal->iCallback;
49658 pWal->iCallback = 0;
49660 return (int)ret;
49664 ** This function is called to change the WAL subsystem into or out
49665 ** of locking_mode=EXCLUSIVE.
49667 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
49668 ** into locking_mode=NORMAL. This means that we must acquire a lock
49669 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
49670 ** or if the acquisition of the lock fails, then return 0. If the
49671 ** transition out of exclusive-mode is successful, return 1. This
49672 ** operation must occur while the pager is still holding the exclusive
49673 ** lock on the main database file.
49675 ** If op is one, then change from locking_mode=NORMAL into
49676 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
49677 ** be released. Return 1 if the transition is made and 0 if the
49678 ** WAL is already in exclusive-locking mode - meaning that this
49679 ** routine is a no-op. The pager must already hold the exclusive lock
49680 ** on the main database file before invoking this operation.
49682 ** If op is negative, then do a dry-run of the op==1 case but do
49683 ** not actually change anything. The pager uses this to see if it
49684 ** should acquire the database exclusive lock prior to invoking
49685 ** the op==1 case.
49687 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
49688 int rc;
49689 assert( pWal->writeLock==0 );
49690 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
49692 /* pWal->readLock is usually set, but might be -1 if there was a
49693 ** prior error while attempting to acquire are read-lock. This cannot
49694 ** happen if the connection is actually in exclusive mode (as no xShmLock
49695 ** locks are taken in this case). Nor should the pager attempt to
49696 ** upgrade to exclusive-mode following such an error.
49698 assert( pWal->readLock>=0 || pWal->lockError );
49699 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
49701 if( op==0 ){
49702 if( pWal->exclusiveMode ){
49703 pWal->exclusiveMode = 0;
49704 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
49705 pWal->exclusiveMode = 1;
49707 rc = pWal->exclusiveMode==0;
49708 }else{
49709 /* Already in locking_mode=NORMAL */
49710 rc = 0;
49712 }else if( op>0 ){
49713 assert( pWal->exclusiveMode==0 );
49714 assert( pWal->readLock>=0 );
49715 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
49716 pWal->exclusiveMode = 1;
49717 rc = 1;
49718 }else{
49719 rc = pWal->exclusiveMode==0;
49721 return rc;
49725 ** Return true if the argument is non-NULL and the WAL module is using
49726 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
49727 ** WAL module is using shared-memory, return false.
49729 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
49730 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
49733 #ifdef SQLITE_ENABLE_ZIPVFS
49735 ** If the argument is not NULL, it points to a Wal object that holds a
49736 ** read-lock. This function returns the database page-size if it is known,
49737 ** or zero if it is not (or if pWal is NULL).
49739 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
49740 assert( pWal==0 || pWal->readLock>=0 );
49741 return (pWal ? pWal->szPage : 0);
49743 #endif
49745 #endif /* #ifndef SQLITE_OMIT_WAL */
49747 /************** End of wal.c *************************************************/
49748 /************** Begin file btmutex.c *****************************************/
49750 ** 2007 August 27
49752 ** The author disclaims copyright to this source code. In place of
49753 ** a legal notice, here is a blessing:
49755 ** May you do good and not evil.
49756 ** May you find forgiveness for yourself and forgive others.
49757 ** May you share freely, never taking more than you give.
49759 *************************************************************************
49761 ** This file contains code used to implement mutexes on Btree objects.
49762 ** This code really belongs in btree.c. But btree.c is getting too
49763 ** big and we want to break it down some. This packaged seemed like
49764 ** a good breakout.
49766 /************** Include btreeInt.h in the middle of btmutex.c ****************/
49767 /************** Begin file btreeInt.h ****************************************/
49769 ** 2004 April 6
49771 ** The author disclaims copyright to this source code. In place of
49772 ** a legal notice, here is a blessing:
49774 ** May you do good and not evil.
49775 ** May you find forgiveness for yourself and forgive others.
49776 ** May you share freely, never taking more than you give.
49778 *************************************************************************
49779 ** This file implements a external (disk-based) database using BTrees.
49780 ** For a detailed discussion of BTrees, refer to
49782 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
49783 ** "Sorting And Searching", pages 473-480. Addison-Wesley
49784 ** Publishing Company, Reading, Massachusetts.
49786 ** The basic idea is that each page of the file contains N database
49787 ** entries and N+1 pointers to subpages.
49789 ** ----------------------------------------------------------------
49790 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
49791 ** ----------------------------------------------------------------
49793 ** All of the keys on the page that Ptr(0) points to have values less
49794 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
49795 ** values greater than Key(0) and less than Key(1). All of the keys
49796 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
49797 ** so forth.
49799 ** Finding a particular key requires reading O(log(M)) pages from the
49800 ** disk where M is the number of entries in the tree.
49802 ** In this implementation, a single file can hold one or more separate
49803 ** BTrees. Each BTree is identified by the index of its root page. The
49804 ** key and data for any entry are combined to form the "payload". A
49805 ** fixed amount of payload can be carried directly on the database
49806 ** page. If the payload is larger than the preset amount then surplus
49807 ** bytes are stored on overflow pages. The payload for an entry
49808 ** and the preceding pointer are combined to form a "Cell". Each
49809 ** page has a small header which contains the Ptr(N) pointer and other
49810 ** information such as the size of key and data.
49812 ** FORMAT DETAILS
49814 ** The file is divided into pages. The first page is called page 1,
49815 ** the second is page 2, and so forth. A page number of zero indicates
49816 ** "no such page". The page size can be any power of 2 between 512 and 65536.
49817 ** Each page can be either a btree page, a freelist page, an overflow
49818 ** page, or a pointer-map page.
49820 ** The first page is always a btree page. The first 100 bytes of the first
49821 ** page contain a special header (the "file header") that describes the file.
49822 ** The format of the file header is as follows:
49824 ** OFFSET SIZE DESCRIPTION
49825 ** 0 16 Header string: "SQLite format 3\000"
49826 ** 16 2 Page size in bytes. (1 means 65536)
49827 ** 18 1 File format write version
49828 ** 19 1 File format read version
49829 ** 20 1 Bytes of unused space at the end of each page
49830 ** 21 1 Max embedded payload fraction (must be 64)
49831 ** 22 1 Min embedded payload fraction (must be 32)
49832 ** 23 1 Min leaf payload fraction (must be 32)
49833 ** 24 4 File change counter
49834 ** 28 4 Reserved for future use
49835 ** 32 4 First freelist page
49836 ** 36 4 Number of freelist pages in the file
49837 ** 40 60 15 4-byte meta values passed to higher layers
49839 ** 40 4 Schema cookie
49840 ** 44 4 File format of schema layer
49841 ** 48 4 Size of page cache
49842 ** 52 4 Largest root-page (auto/incr_vacuum)
49843 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
49844 ** 60 4 User version
49845 ** 64 4 Incremental vacuum mode
49846 ** 68 4 Application-ID
49847 ** 72 20 unused
49848 ** 92 4 The version-valid-for number
49849 ** 96 4 SQLITE_VERSION_NUMBER
49851 ** All of the integer values are big-endian (most significant byte first).
49853 ** The file change counter is incremented when the database is changed
49854 ** This counter allows other processes to know when the file has changed
49855 ** and thus when they need to flush their cache.
49857 ** The max embedded payload fraction is the amount of the total usable
49858 ** space in a page that can be consumed by a single cell for standard
49859 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
49860 ** is to limit the maximum cell size so that at least 4 cells will fit
49861 ** on one page. Thus the default max embedded payload fraction is 64.
49863 ** If the payload for a cell is larger than the max payload, then extra
49864 ** payload is spilled to overflow pages. Once an overflow page is allocated,
49865 ** as many bytes as possible are moved into the overflow pages without letting
49866 ** the cell size drop below the min embedded payload fraction.
49868 ** The min leaf payload fraction is like the min embedded payload fraction
49869 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
49870 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
49871 ** not specified in the header.
49873 ** Each btree pages is divided into three sections: The header, the
49874 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
49875 ** file header that occurs before the page header.
49877 ** |----------------|
49878 ** | file header | 100 bytes. Page 1 only.
49879 ** |----------------|
49880 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
49881 ** |----------------|
49882 ** | cell pointer | | 2 bytes per cell. Sorted order.
49883 ** | array | | Grows downward
49884 ** | | v
49885 ** |----------------|
49886 ** | unallocated |
49887 ** | space |
49888 ** |----------------| ^ Grows upwards
49889 ** | cell content | | Arbitrary order interspersed with freeblocks.
49890 ** | area | | and free space fragments.
49891 ** |----------------|
49893 ** The page headers looks like this:
49895 ** OFFSET SIZE DESCRIPTION
49896 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
49897 ** 1 2 byte offset to the first freeblock
49898 ** 3 2 number of cells on this page
49899 ** 5 2 first byte of the cell content area
49900 ** 7 1 number of fragmented free bytes
49901 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
49903 ** The flags define the format of this btree page. The leaf flag means that
49904 ** this page has no children. The zerodata flag means that this page carries
49905 ** only keys and no data. The intkey flag means that the key is a integer
49906 ** which is stored in the key size entry of the cell header rather than in
49907 ** the payload area.
49909 ** The cell pointer array begins on the first byte after the page header.
49910 ** The cell pointer array contains zero or more 2-byte numbers which are
49911 ** offsets from the beginning of the page to the cell content in the cell
49912 ** content area. The cell pointers occur in sorted order. The system strives
49913 ** to keep free space after the last cell pointer so that new cells can
49914 ** be easily added without having to defragment the page.
49916 ** Cell content is stored at the very end of the page and grows toward the
49917 ** beginning of the page.
49919 ** Unused space within the cell content area is collected into a linked list of
49920 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
49921 ** to the first freeblock is given in the header. Freeblocks occur in
49922 ** increasing order. Because a freeblock must be at least 4 bytes in size,
49923 ** any group of 3 or fewer unused bytes in the cell content area cannot
49924 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
49925 ** a fragment. The total number of bytes in all fragments is recorded.
49926 ** in the page header at offset 7.
49928 ** SIZE DESCRIPTION
49929 ** 2 Byte offset of the next freeblock
49930 ** 2 Bytes in this freeblock
49932 ** Cells are of variable length. Cells are stored in the cell content area at
49933 ** the end of the page. Pointers to the cells are in the cell pointer array
49934 ** that immediately follows the page header. Cells is not necessarily
49935 ** contiguous or in order, but cell pointers are contiguous and in order.
49937 ** Cell content makes use of variable length integers. A variable
49938 ** length integer is 1 to 9 bytes where the lower 7 bits of each
49939 ** byte are used. The integer consists of all bytes that have bit 8 set and
49940 ** the first byte with bit 8 clear. The most significant byte of the integer
49941 ** appears first. A variable-length integer may not be more than 9 bytes long.
49942 ** As a special case, all 8 bytes of the 9th byte are used as data. This
49943 ** allows a 64-bit integer to be encoded in 9 bytes.
49945 ** 0x00 becomes 0x00000000
49946 ** 0x7f becomes 0x0000007f
49947 ** 0x81 0x00 becomes 0x00000080
49948 ** 0x82 0x00 becomes 0x00000100
49949 ** 0x80 0x7f becomes 0x0000007f
49950 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
49951 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
49953 ** Variable length integers are used for rowids and to hold the number of
49954 ** bytes of key and data in a btree cell.
49956 ** The content of a cell looks like this:
49958 ** SIZE DESCRIPTION
49959 ** 4 Page number of the left child. Omitted if leaf flag is set.
49960 ** var Number of bytes of data. Omitted if the zerodata flag is set.
49961 ** var Number of bytes of key. Or the key itself if intkey flag is set.
49962 ** * Payload
49963 ** 4 First page of the overflow chain. Omitted if no overflow
49965 ** Overflow pages form a linked list. Each page except the last is completely
49966 ** filled with data (pagesize - 4 bytes). The last page can have as little
49967 ** as 1 byte of data.
49969 ** SIZE DESCRIPTION
49970 ** 4 Page number of next overflow page
49971 ** * Data
49973 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
49974 ** file header points to the first in a linked list of trunk page. Each trunk
49975 ** page points to multiple leaf pages. The content of a leaf page is
49976 ** unspecified. A trunk page looks like this:
49978 ** SIZE DESCRIPTION
49979 ** 4 Page number of next trunk page
49980 ** 4 Number of leaf pointers on this page
49981 ** * zero or more pages numbers of leaves
49985 /* The following value is the maximum cell size assuming a maximum page
49986 ** size give above.
49988 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
49990 /* The maximum number of cells on a single page of the database. This
49991 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
49992 ** plus 2 bytes for the index to the cell in the page header). Such
49993 ** small cells will be rare, but they are possible.
49995 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
49997 /* Forward declarations */
49998 typedef struct MemPage MemPage;
49999 typedef struct BtLock BtLock;
50002 ** This is a magic string that appears at the beginning of every
50003 ** SQLite database in order to identify the file as a real database.
50005 ** You can change this value at compile-time by specifying a
50006 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
50007 ** header must be exactly 16 bytes including the zero-terminator so
50008 ** the string itself should be 15 characters long. If you change
50009 ** the header, then your custom library will not be able to read
50010 ** databases generated by the standard tools and the standard tools
50011 ** will not be able to read databases created by your custom library.
50013 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
50014 # define SQLITE_FILE_HEADER "SQLite format 3"
50015 #endif
50018 ** Page type flags. An ORed combination of these flags appear as the
50019 ** first byte of on-disk image of every BTree page.
50021 #define PTF_INTKEY 0x01
50022 #define PTF_ZERODATA 0x02
50023 #define PTF_LEAFDATA 0x04
50024 #define PTF_LEAF 0x08
50027 ** As each page of the file is loaded into memory, an instance of the following
50028 ** structure is appended and initialized to zero. This structure stores
50029 ** information about the page that is decoded from the raw file page.
50031 ** The pParent field points back to the parent page. This allows us to
50032 ** walk up the BTree from any leaf to the root. Care must be taken to
50033 ** unref() the parent page pointer when this page is no longer referenced.
50034 ** The pageDestructor() routine handles that chore.
50036 ** Access to all fields of this structure is controlled by the mutex
50037 ** stored in MemPage.pBt->mutex.
50039 struct MemPage {
50040 u8 isInit; /* True if previously initialized. MUST BE FIRST! */
50041 u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
50042 u8 intKey; /* True if intkey flag is set */
50043 u8 leaf; /* True if leaf flag is set */
50044 u8 hasData; /* True if this page stores data */
50045 u8 hdrOffset; /* 100 for page 1. 0 otherwise */
50046 u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
50047 u8 max1bytePayload; /* min(maxLocal,127) */
50048 u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
50049 u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
50050 u16 cellOffset; /* Index in aData of first cell pointer */
50051 u16 nFree; /* Number of free bytes on the page */
50052 u16 nCell; /* Number of cells on this page, local and ovfl */
50053 u16 maskPage; /* Mask for page offset */
50054 u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
50055 ** non-overflow cell */
50056 u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
50057 BtShared *pBt; /* Pointer to BtShared that this page is part of */
50058 u8 *aData; /* Pointer to disk image of the page data */
50059 u8 *aDataEnd; /* One byte past the end of usable data */
50060 u8 *aCellIdx; /* The cell index area */
50061 DbPage *pDbPage; /* Pager page handle */
50062 Pgno pgno; /* Page number for this page */
50066 ** The in-memory image of a disk page has the auxiliary information appended
50067 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
50068 ** that extra information.
50070 #define EXTRA_SIZE sizeof(MemPage)
50073 ** A linked list of the following structures is stored at BtShared.pLock.
50074 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
50075 ** is opened on the table with root page BtShared.iTable. Locks are removed
50076 ** from this list when a transaction is committed or rolled back, or when
50077 ** a btree handle is closed.
50079 struct BtLock {
50080 Btree *pBtree; /* Btree handle holding this lock */
50081 Pgno iTable; /* Root page of table */
50082 u8 eLock; /* READ_LOCK or WRITE_LOCK */
50083 BtLock *pNext; /* Next in BtShared.pLock list */
50086 /* Candidate values for BtLock.eLock */
50087 #define READ_LOCK 1
50088 #define WRITE_LOCK 2
50090 /* A Btree handle
50092 ** A database connection contains a pointer to an instance of
50093 ** this object for every database file that it has open. This structure
50094 ** is opaque to the database connection. The database connection cannot
50095 ** see the internals of this structure and only deals with pointers to
50096 ** this structure.
50098 ** For some database files, the same underlying database cache might be
50099 ** shared between multiple connections. In that case, each connection
50100 ** has it own instance of this object. But each instance of this object
50101 ** points to the same BtShared object. The database cache and the
50102 ** schema associated with the database file are all contained within
50103 ** the BtShared object.
50105 ** All fields in this structure are accessed under sqlite3.mutex.
50106 ** The pBt pointer itself may not be changed while there exists cursors
50107 ** in the referenced BtShared that point back to this Btree since those
50108 ** cursors have to go through this Btree to find their BtShared and
50109 ** they often do so without holding sqlite3.mutex.
50111 struct Btree {
50112 sqlite3 *db; /* The database connection holding this btree */
50113 BtShared *pBt; /* Sharable content of this btree */
50114 u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
50115 u8 sharable; /* True if we can share pBt with another db */
50116 u8 locked; /* True if db currently has pBt locked */
50117 int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
50118 int nBackup; /* Number of backup operations reading this btree */
50119 Btree *pNext; /* List of other sharable Btrees from the same db */
50120 Btree *pPrev; /* Back pointer of the same list */
50121 #ifndef SQLITE_OMIT_SHARED_CACHE
50122 BtLock lock; /* Object used to lock page 1 */
50123 #endif
50127 ** Btree.inTrans may take one of the following values.
50129 ** If the shared-data extension is enabled, there may be multiple users
50130 ** of the Btree structure. At most one of these may open a write transaction,
50131 ** but any number may have active read transactions.
50133 #define TRANS_NONE 0
50134 #define TRANS_READ 1
50135 #define TRANS_WRITE 2
50138 ** An instance of this object represents a single database file.
50140 ** A single database file can be in use at the same time by two
50141 ** or more database connections. When two or more connections are
50142 ** sharing the same database file, each connection has it own
50143 ** private Btree object for the file and each of those Btrees points
50144 ** to this one BtShared object. BtShared.nRef is the number of
50145 ** connections currently sharing this database file.
50147 ** Fields in this structure are accessed under the BtShared.mutex
50148 ** mutex, except for nRef and pNext which are accessed under the
50149 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
50150 ** may not be modified once it is initially set as long as nRef>0.
50151 ** The pSchema field may be set once under BtShared.mutex and
50152 ** thereafter is unchanged as long as nRef>0.
50154 ** isPending:
50156 ** If a BtShared client fails to obtain a write-lock on a database
50157 ** table (because there exists one or more read-locks on the table),
50158 ** the shared-cache enters 'pending-lock' state and isPending is
50159 ** set to true.
50161 ** The shared-cache leaves the 'pending lock' state when either of
50162 ** the following occur:
50164 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
50165 ** 2) The number of locks held by other connections drops to zero.
50167 ** while in the 'pending-lock' state, no connection may start a new
50168 ** transaction.
50170 ** This feature is included to help prevent writer-starvation.
50172 struct BtShared {
50173 Pager *pPager; /* The page cache */
50174 sqlite3 *db; /* Database connection currently using this Btree */
50175 BtCursor *pCursor; /* A list of all open cursors */
50176 MemPage *pPage1; /* First page of the database */
50177 u8 openFlags; /* Flags to sqlite3BtreeOpen() */
50178 #ifndef SQLITE_OMIT_AUTOVACUUM
50179 u8 autoVacuum; /* True if auto-vacuum is enabled */
50180 u8 incrVacuum; /* True if incr-vacuum is enabled */
50181 u8 bDoTruncate; /* True to truncate db on commit */
50182 #endif
50183 u8 inTransaction; /* Transaction state */
50184 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
50185 u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
50186 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
50187 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
50188 u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
50189 u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
50190 u32 pageSize; /* Total number of bytes on a page */
50191 u32 usableSize; /* Number of usable bytes on each page */
50192 int nTransaction; /* Number of open transactions (read + write) */
50193 u32 nPage; /* Number of pages in the database */
50194 void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
50195 void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
50196 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
50197 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
50198 #ifndef SQLITE_OMIT_SHARED_CACHE
50199 int nRef; /* Number of references to this structure */
50200 BtShared *pNext; /* Next on a list of sharable BtShared structs */
50201 BtLock *pLock; /* List of locks held on this shared-btree struct */
50202 Btree *pWriter; /* Btree with currently open write transaction */
50203 #endif
50204 u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
50208 ** Allowed values for BtShared.btsFlags
50210 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
50211 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
50212 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
50213 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
50214 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
50215 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
50216 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
50219 ** An instance of the following structure is used to hold information
50220 ** about a cell. The parseCellPtr() function fills in this structure
50221 ** based on information extract from the raw disk page.
50223 typedef struct CellInfo CellInfo;
50224 struct CellInfo {
50225 i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
50226 u8 *pCell; /* Pointer to the start of cell content */
50227 u32 nData; /* Number of bytes of data */
50228 u32 nPayload; /* Total amount of payload */
50229 u16 nHeader; /* Size of the cell content header in bytes */
50230 u16 nLocal; /* Amount of payload held locally */
50231 u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
50232 u16 nSize; /* Size of the cell content on the main b-tree page */
50236 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
50237 ** this will be declared corrupt. This value is calculated based on a
50238 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
50239 ** root-node and 3 for all other internal nodes.
50241 ** If a tree that appears to be taller than this is encountered, it is
50242 ** assumed that the database is corrupt.
50244 #define BTCURSOR_MAX_DEPTH 20
50247 ** A cursor is a pointer to a particular entry within a particular
50248 ** b-tree within a database file.
50250 ** The entry is identified by its MemPage and the index in
50251 ** MemPage.aCell[] of the entry.
50253 ** A single database file can be shared by two more database connections,
50254 ** but cursors cannot be shared. Each cursor is associated with a
50255 ** particular database connection identified BtCursor.pBtree.db.
50257 ** Fields in this structure are accessed under the BtShared.mutex
50258 ** found at self->pBt->mutex.
50260 struct BtCursor {
50261 Btree *pBtree; /* The Btree to which this cursor belongs */
50262 BtShared *pBt; /* The BtShared this cursor points to */
50263 BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
50264 struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
50265 #ifndef SQLITE_OMIT_INCRBLOB
50266 Pgno *aOverflow; /* Cache of overflow page locations */
50267 #endif
50268 Pgno pgnoRoot; /* The root page of this tree */
50269 sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
50270 CellInfo info; /* A parse of the cell we are pointing at */
50271 i64 nKey; /* Size of pKey, or last integer key */
50272 void *pKey; /* Saved key that was cursor's last known position */
50273 int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
50274 u8 wrFlag; /* True if writable */
50275 u8 atLast; /* Cursor pointing to the last entry */
50276 u8 validNKey; /* True if info.nKey is valid */
50277 u8 eState; /* One of the CURSOR_XXX constants (see below) */
50278 #ifndef SQLITE_OMIT_INCRBLOB
50279 u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
50280 #endif
50281 u8 hints; /* As configured by CursorSetHints() */
50282 i16 iPage; /* Index of current page in apPage */
50283 u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
50284 MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
50288 ** Potential values for BtCursor.eState.
50290 ** CURSOR_INVALID:
50291 ** Cursor does not point to a valid entry. This can happen (for example)
50292 ** because the table is empty or because BtreeCursorFirst() has not been
50293 ** called.
50295 ** CURSOR_VALID:
50296 ** Cursor points to a valid entry. getPayload() etc. may be called.
50298 ** CURSOR_SKIPNEXT:
50299 ** Cursor is valid except that the Cursor.skipNext field is non-zero
50300 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
50301 ** operation should be a no-op.
50303 ** CURSOR_REQUIRESEEK:
50304 ** The table that this cursor was opened on still exists, but has been
50305 ** modified since the cursor was last used. The cursor position is saved
50306 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
50307 ** this state, restoreCursorPosition() can be called to attempt to
50308 ** seek the cursor to the saved position.
50310 ** CURSOR_FAULT:
50311 ** A unrecoverable error (an I/O error or a malloc failure) has occurred
50312 ** on a different connection that shares the BtShared cache with this
50313 ** cursor. The error has left the cache in an inconsistent state.
50314 ** Do nothing else with this cursor. Any attempt to use the cursor
50315 ** should return the error code stored in BtCursor.skip
50317 #define CURSOR_INVALID 0
50318 #define CURSOR_VALID 1
50319 #define CURSOR_SKIPNEXT 2
50320 #define CURSOR_REQUIRESEEK 3
50321 #define CURSOR_FAULT 4
50324 ** The database page the PENDING_BYTE occupies. This page is never used.
50326 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
50329 ** These macros define the location of the pointer-map entry for a
50330 ** database page. The first argument to each is the number of usable
50331 ** bytes on each page of the database (often 1024). The second is the
50332 ** page number to look up in the pointer map.
50334 ** PTRMAP_PAGENO returns the database page number of the pointer-map
50335 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
50336 ** the offset of the requested map entry.
50338 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
50339 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
50340 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
50341 ** this test.
50343 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
50344 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
50345 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
50348 ** The pointer map is a lookup table that identifies the parent page for
50349 ** each child page in the database file. The parent page is the page that
50350 ** contains a pointer to the child. Every page in the database contains
50351 ** 0 or 1 parent pages. (In this context 'database page' refers
50352 ** to any page that is not part of the pointer map itself.) Each pointer map
50353 ** entry consists of a single byte 'type' and a 4 byte parent page number.
50354 ** The PTRMAP_XXX identifiers below are the valid types.
50356 ** The purpose of the pointer map is to facility moving pages from one
50357 ** position in the file to another as part of autovacuum. When a page
50358 ** is moved, the pointer in its parent must be updated to point to the
50359 ** new location. The pointer map is used to locate the parent page quickly.
50361 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
50362 ** used in this case.
50364 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
50365 ** is not used in this case.
50367 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
50368 ** overflow pages. The page number identifies the page that
50369 ** contains the cell with a pointer to this overflow page.
50371 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
50372 ** overflow pages. The page-number identifies the previous
50373 ** page in the overflow page list.
50375 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
50376 ** identifies the parent page in the btree.
50378 #define PTRMAP_ROOTPAGE 1
50379 #define PTRMAP_FREEPAGE 2
50380 #define PTRMAP_OVERFLOW1 3
50381 #define PTRMAP_OVERFLOW2 4
50382 #define PTRMAP_BTREE 5
50384 /* A bunch of assert() statements to check the transaction state variables
50385 ** of handle p (type Btree*) are internally consistent.
50387 #define btreeIntegrity(p) \
50388 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
50389 assert( p->pBt->inTransaction>=p->inTrans );
50393 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
50394 ** if the database supports auto-vacuum or not. Because it is used
50395 ** within an expression that is an argument to another macro
50396 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
50397 ** So, this macro is defined instead.
50399 #ifndef SQLITE_OMIT_AUTOVACUUM
50400 #define ISAUTOVACUUM (pBt->autoVacuum)
50401 #else
50402 #define ISAUTOVACUUM 0
50403 #endif
50407 ** This structure is passed around through all the sanity checking routines
50408 ** in order to keep track of some global state information.
50410 ** The aRef[] array is allocated so that there is 1 bit for each page in
50411 ** the database. As the integrity-check proceeds, for each page used in
50412 ** the database the corresponding bit is set. This allows integrity-check to
50413 ** detect pages that are used twice and orphaned pages (both of which
50414 ** indicate corruption).
50416 typedef struct IntegrityCk IntegrityCk;
50417 struct IntegrityCk {
50418 BtShared *pBt; /* The tree being checked out */
50419 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
50420 u8 *aPgRef; /* 1 bit per page in the db (see above) */
50421 Pgno nPage; /* Number of pages in the database */
50422 int mxErr; /* Stop accumulating errors when this reaches zero */
50423 int nErr; /* Number of messages written to zErrMsg so far */
50424 int mallocFailed; /* A memory allocation error has occurred */
50425 StrAccum errMsg; /* Accumulate the error message text here */
50429 ** Routines to read or write a two- and four-byte big-endian integer values.
50431 #define get2byte(x) ((x)[0]<<8 | (x)[1])
50432 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
50433 #define get4byte sqlite3Get4byte
50434 #define put4byte sqlite3Put4byte
50436 /************** End of btreeInt.h ********************************************/
50437 /************** Continuing where we left off in btmutex.c ********************/
50438 #ifndef SQLITE_OMIT_SHARED_CACHE
50439 #if SQLITE_THREADSAFE
50442 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
50443 ** set BtShared.db to the database handle associated with p and the
50444 ** p->locked boolean to true.
50446 static void lockBtreeMutex(Btree *p){
50447 assert( p->locked==0 );
50448 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
50449 assert( sqlite3_mutex_held(p->db->mutex) );
50451 sqlite3_mutex_enter(p->pBt->mutex);
50452 p->pBt->db = p->db;
50453 p->locked = 1;
50457 ** Release the BtShared mutex associated with B-Tree handle p and
50458 ** clear the p->locked boolean.
50460 static void unlockBtreeMutex(Btree *p){
50461 BtShared *pBt = p->pBt;
50462 assert( p->locked==1 );
50463 assert( sqlite3_mutex_held(pBt->mutex) );
50464 assert( sqlite3_mutex_held(p->db->mutex) );
50465 assert( p->db==pBt->db );
50467 sqlite3_mutex_leave(pBt->mutex);
50468 p->locked = 0;
50472 ** Enter a mutex on the given BTree object.
50474 ** If the object is not sharable, then no mutex is ever required
50475 ** and this routine is a no-op. The underlying mutex is non-recursive.
50476 ** But we keep a reference count in Btree.wantToLock so the behavior
50477 ** of this interface is recursive.
50479 ** To avoid deadlocks, multiple Btrees are locked in the same order
50480 ** by all database connections. The p->pNext is a list of other
50481 ** Btrees belonging to the same database connection as the p Btree
50482 ** which need to be locked after p. If we cannot get a lock on
50483 ** p, then first unlock all of the others on p->pNext, then wait
50484 ** for the lock to become available on p, then relock all of the
50485 ** subsequent Btrees that desire a lock.
50487 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
50488 Btree *pLater;
50490 /* Some basic sanity checking on the Btree. The list of Btrees
50491 ** connected by pNext and pPrev should be in sorted order by
50492 ** Btree.pBt value. All elements of the list should belong to
50493 ** the same connection. Only shared Btrees are on the list. */
50494 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
50495 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
50496 assert( p->pNext==0 || p->pNext->db==p->db );
50497 assert( p->pPrev==0 || p->pPrev->db==p->db );
50498 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
50500 /* Check for locking consistency */
50501 assert( !p->locked || p->wantToLock>0 );
50502 assert( p->sharable || p->wantToLock==0 );
50504 /* We should already hold a lock on the database connection */
50505 assert( sqlite3_mutex_held(p->db->mutex) );
50507 /* Unless the database is sharable and unlocked, then BtShared.db
50508 ** should already be set correctly. */
50509 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
50511 if( !p->sharable ) return;
50512 p->wantToLock++;
50513 if( p->locked ) return;
50515 /* In most cases, we should be able to acquire the lock we
50516 ** want without having to go throught the ascending lock
50517 ** procedure that follows. Just be sure not to block.
50519 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
50520 p->pBt->db = p->db;
50521 p->locked = 1;
50522 return;
50525 /* To avoid deadlock, first release all locks with a larger
50526 ** BtShared address. Then acquire our lock. Then reacquire
50527 ** the other BtShared locks that we used to hold in ascending
50528 ** order.
50530 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
50531 assert( pLater->sharable );
50532 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
50533 assert( !pLater->locked || pLater->wantToLock>0 );
50534 if( pLater->locked ){
50535 unlockBtreeMutex(pLater);
50538 lockBtreeMutex(p);
50539 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
50540 if( pLater->wantToLock ){
50541 lockBtreeMutex(pLater);
50547 ** Exit the recursive mutex on a Btree.
50549 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
50550 if( p->sharable ){
50551 assert( p->wantToLock>0 );
50552 p->wantToLock--;
50553 if( p->wantToLock==0 ){
50554 unlockBtreeMutex(p);
50559 #ifndef NDEBUG
50561 ** Return true if the BtShared mutex is held on the btree, or if the
50562 ** B-Tree is not marked as sharable.
50564 ** This routine is used only from within assert() statements.
50566 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
50567 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
50568 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
50569 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
50570 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
50572 return (p->sharable==0 || p->locked);
50574 #endif
50577 #ifndef SQLITE_OMIT_INCRBLOB
50579 ** Enter and leave a mutex on a Btree given a cursor owned by that
50580 ** Btree. These entry points are used by incremental I/O and can be
50581 ** omitted if that module is not used.
50583 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
50584 sqlite3BtreeEnter(pCur->pBtree);
50586 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
50587 sqlite3BtreeLeave(pCur->pBtree);
50589 #endif /* SQLITE_OMIT_INCRBLOB */
50593 ** Enter the mutex on every Btree associated with a database
50594 ** connection. This is needed (for example) prior to parsing
50595 ** a statement since we will be comparing table and column names
50596 ** against all schemas and we do not want those schemas being
50597 ** reset out from under us.
50599 ** There is a corresponding leave-all procedures.
50601 ** Enter the mutexes in accending order by BtShared pointer address
50602 ** to avoid the possibility of deadlock when two threads with
50603 ** two or more btrees in common both try to lock all their btrees
50604 ** at the same instant.
50606 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
50607 int i;
50608 Btree *p;
50609 assert( sqlite3_mutex_held(db->mutex) );
50610 for(i=0; i<db->nDb; i++){
50611 p = db->aDb[i].pBt;
50612 if( p ) sqlite3BtreeEnter(p);
50615 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
50616 int i;
50617 Btree *p;
50618 assert( sqlite3_mutex_held(db->mutex) );
50619 for(i=0; i<db->nDb; i++){
50620 p = db->aDb[i].pBt;
50621 if( p ) sqlite3BtreeLeave(p);
50626 ** Return true if a particular Btree requires a lock. Return FALSE if
50627 ** no lock is ever required since it is not sharable.
50629 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
50630 return p->sharable;
50633 #ifndef NDEBUG
50635 ** Return true if the current thread holds the database connection
50636 ** mutex and all required BtShared mutexes.
50638 ** This routine is used inside assert() statements only.
50640 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
50641 int i;
50642 if( !sqlite3_mutex_held(db->mutex) ){
50643 return 0;
50645 for(i=0; i<db->nDb; i++){
50646 Btree *p;
50647 p = db->aDb[i].pBt;
50648 if( p && p->sharable &&
50649 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
50650 return 0;
50653 return 1;
50655 #endif /* NDEBUG */
50657 #ifndef NDEBUG
50659 ** Return true if the correct mutexes are held for accessing the
50660 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
50661 ** access are:
50663 ** (1) The mutex on db
50664 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
50666 ** If pSchema is not NULL, then iDb is computed from pSchema and
50667 ** db using sqlite3SchemaToIndex().
50669 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
50670 Btree *p;
50671 assert( db!=0 );
50672 if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
50673 assert( iDb>=0 && iDb<db->nDb );
50674 if( !sqlite3_mutex_held(db->mutex) ) return 0;
50675 if( iDb==1 ) return 1;
50676 p = db->aDb[iDb].pBt;
50677 assert( p!=0 );
50678 return p->sharable==0 || p->locked==1;
50680 #endif /* NDEBUG */
50682 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
50684 ** The following are special cases for mutex enter routines for use
50685 ** in single threaded applications that use shared cache. Except for
50686 ** these two routines, all mutex operations are no-ops in that case and
50687 ** are null #defines in btree.h.
50689 ** If shared cache is disabled, then all btree mutex routines, including
50690 ** the ones below, are no-ops and are null #defines in btree.h.
50693 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
50694 p->pBt->db = p->db;
50696 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
50697 int i;
50698 for(i=0; i<db->nDb; i++){
50699 Btree *p = db->aDb[i].pBt;
50700 if( p ){
50701 p->pBt->db = p->db;
50705 #endif /* if SQLITE_THREADSAFE */
50706 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
50708 /************** End of btmutex.c *********************************************/
50709 /************** Begin file btree.c *******************************************/
50711 ** 2004 April 6
50713 ** The author disclaims copyright to this source code. In place of
50714 ** a legal notice, here is a blessing:
50716 ** May you do good and not evil.
50717 ** May you find forgiveness for yourself and forgive others.
50718 ** May you share freely, never taking more than you give.
50720 *************************************************************************
50721 ** This file implements a external (disk-based) database using BTrees.
50722 ** See the header comment on "btreeInt.h" for additional information.
50723 ** Including a description of file format and an overview of operation.
50727 ** The header string that appears at the beginning of every
50728 ** SQLite database.
50730 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
50733 ** Set this global variable to 1 to enable tracing using the TRACE
50734 ** macro.
50736 #if 0
50737 int sqlite3BtreeTrace=1; /* True to enable tracing */
50738 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
50739 #else
50740 # define TRACE(X)
50741 #endif
50744 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
50745 ** But if the value is zero, make it 65536.
50747 ** This routine is used to extract the "offset to cell content area" value
50748 ** from the header of a btree page. If the page size is 65536 and the page
50749 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
50750 ** This routine makes the necessary adjustment to 65536.
50752 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
50755 ** Values passed as the 5th argument to allocateBtreePage()
50757 #define BTALLOC_ANY 0 /* Allocate any page */
50758 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
50759 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
50762 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
50763 ** defined, or 0 if it is. For example:
50765 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
50767 #ifndef SQLITE_OMIT_AUTOVACUUM
50768 #define IfNotOmitAV(expr) (expr)
50769 #else
50770 #define IfNotOmitAV(expr) 0
50771 #endif
50773 #ifndef SQLITE_OMIT_SHARED_CACHE
50775 ** A list of BtShared objects that are eligible for participation
50776 ** in shared cache. This variable has file scope during normal builds,
50777 ** but the test harness needs to access it so we make it global for
50778 ** test builds.
50780 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
50782 #ifdef SQLITE_TEST
50783 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
50784 #else
50785 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
50786 #endif
50787 #endif /* SQLITE_OMIT_SHARED_CACHE */
50789 #ifndef SQLITE_OMIT_SHARED_CACHE
50791 ** Enable or disable the shared pager and schema features.
50793 ** This routine has no effect on existing database connections.
50794 ** The shared cache setting effects only future calls to
50795 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
50797 SQLITE_API int sqlite3_enable_shared_cache(int enable){
50798 sqlite3GlobalConfig.sharedCacheEnabled = enable;
50799 return SQLITE_OK;
50801 #endif
50805 #ifdef SQLITE_OMIT_SHARED_CACHE
50807 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
50808 ** and clearAllSharedCacheTableLocks()
50809 ** manipulate entries in the BtShared.pLock linked list used to store
50810 ** shared-cache table level locks. If the library is compiled with the
50811 ** shared-cache feature disabled, then there is only ever one user
50812 ** of each BtShared structure and so this locking is not necessary.
50813 ** So define the lock related functions as no-ops.
50815 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
50816 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
50817 #define clearAllSharedCacheTableLocks(a)
50818 #define downgradeAllSharedCacheTableLocks(a)
50819 #define hasSharedCacheTableLock(a,b,c,d) 1
50820 #define hasReadConflicts(a, b) 0
50821 #endif
50823 #ifndef SQLITE_OMIT_SHARED_CACHE
50825 #ifdef SQLITE_DEBUG
50827 **** This function is only used as part of an assert() statement. ***
50829 ** Check to see if pBtree holds the required locks to read or write to the
50830 ** table with root page iRoot. Return 1 if it does and 0 if not.
50832 ** For example, when writing to a table with root-page iRoot via
50833 ** Btree connection pBtree:
50835 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
50837 ** When writing to an index that resides in a sharable database, the
50838 ** caller should have first obtained a lock specifying the root page of
50839 ** the corresponding table. This makes things a bit more complicated,
50840 ** as this module treats each table as a separate structure. To determine
50841 ** the table corresponding to the index being written, this
50842 ** function has to search through the database schema.
50844 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
50845 ** hold a write-lock on the schema table (root page 1). This is also
50846 ** acceptable.
50848 static int hasSharedCacheTableLock(
50849 Btree *pBtree, /* Handle that must hold lock */
50850 Pgno iRoot, /* Root page of b-tree */
50851 int isIndex, /* True if iRoot is the root of an index b-tree */
50852 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
50854 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
50855 Pgno iTab = 0;
50856 BtLock *pLock;
50858 /* If this database is not shareable, or if the client is reading
50859 ** and has the read-uncommitted flag set, then no lock is required.
50860 ** Return true immediately.
50862 if( (pBtree->sharable==0)
50863 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
50865 return 1;
50868 /* If the client is reading or writing an index and the schema is
50869 ** not loaded, then it is too difficult to actually check to see if
50870 ** the correct locks are held. So do not bother - just return true.
50871 ** This case does not come up very often anyhow.
50873 if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
50874 return 1;
50877 /* Figure out the root-page that the lock should be held on. For table
50878 ** b-trees, this is just the root page of the b-tree being read or
50879 ** written. For index b-trees, it is the root page of the associated
50880 ** table. */
50881 if( isIndex ){
50882 HashElem *p;
50883 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
50884 Index *pIdx = (Index *)sqliteHashData(p);
50885 if( pIdx->tnum==(int)iRoot ){
50886 iTab = pIdx->pTable->tnum;
50889 }else{
50890 iTab = iRoot;
50893 /* Search for the required lock. Either a write-lock on root-page iTab, a
50894 ** write-lock on the schema table, or (if the client is reading) a
50895 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
50896 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
50897 if( pLock->pBtree==pBtree
50898 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
50899 && pLock->eLock>=eLockType
50901 return 1;
50905 /* Failed to find the required lock. */
50906 return 0;
50908 #endif /* SQLITE_DEBUG */
50910 #ifdef SQLITE_DEBUG
50912 **** This function may be used as part of assert() statements only. ****
50914 ** Return true if it would be illegal for pBtree to write into the
50915 ** table or index rooted at iRoot because other shared connections are
50916 ** simultaneously reading that same table or index.
50918 ** It is illegal for pBtree to write if some other Btree object that
50919 ** shares the same BtShared object is currently reading or writing
50920 ** the iRoot table. Except, if the other Btree object has the
50921 ** read-uncommitted flag set, then it is OK for the other object to
50922 ** have a read cursor.
50924 ** For example, before writing to any part of the table or index
50925 ** rooted at page iRoot, one should call:
50927 ** assert( !hasReadConflicts(pBtree, iRoot) );
50929 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
50930 BtCursor *p;
50931 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
50932 if( p->pgnoRoot==iRoot
50933 && p->pBtree!=pBtree
50934 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
50936 return 1;
50939 return 0;
50941 #endif /* #ifdef SQLITE_DEBUG */
50944 ** Query to see if Btree handle p may obtain a lock of type eLock
50945 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
50946 ** SQLITE_OK if the lock may be obtained (by calling
50947 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
50949 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
50950 BtShared *pBt = p->pBt;
50951 BtLock *pIter;
50953 assert( sqlite3BtreeHoldsMutex(p) );
50954 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
50955 assert( p->db!=0 );
50956 assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
50958 /* If requesting a write-lock, then the Btree must have an open write
50959 ** transaction on this file. And, obviously, for this to be so there
50960 ** must be an open write transaction on the file itself.
50962 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
50963 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
50965 /* This routine is a no-op if the shared-cache is not enabled */
50966 if( !p->sharable ){
50967 return SQLITE_OK;
50970 /* If some other connection is holding an exclusive lock, the
50971 ** requested lock may not be obtained.
50973 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
50974 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
50975 return SQLITE_LOCKED_SHAREDCACHE;
50978 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50979 /* The condition (pIter->eLock!=eLock) in the following if(...)
50980 ** statement is a simplification of:
50982 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
50984 ** since we know that if eLock==WRITE_LOCK, then no other connection
50985 ** may hold a WRITE_LOCK on any table in this file (since there can
50986 ** only be a single writer).
50988 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
50989 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
50990 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
50991 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
50992 if( eLock==WRITE_LOCK ){
50993 assert( p==pBt->pWriter );
50994 pBt->btsFlags |= BTS_PENDING;
50996 return SQLITE_LOCKED_SHAREDCACHE;
50999 return SQLITE_OK;
51001 #endif /* !SQLITE_OMIT_SHARED_CACHE */
51003 #ifndef SQLITE_OMIT_SHARED_CACHE
51005 ** Add a lock on the table with root-page iTable to the shared-btree used
51006 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
51007 ** WRITE_LOCK.
51009 ** This function assumes the following:
51011 ** (a) The specified Btree object p is connected to a sharable
51012 ** database (one with the BtShared.sharable flag set), and
51014 ** (b) No other Btree objects hold a lock that conflicts
51015 ** with the requested lock (i.e. querySharedCacheTableLock() has
51016 ** already been called and returned SQLITE_OK).
51018 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
51019 ** is returned if a malloc attempt fails.
51021 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
51022 BtShared *pBt = p->pBt;
51023 BtLock *pLock = 0;
51024 BtLock *pIter;
51026 assert( sqlite3BtreeHoldsMutex(p) );
51027 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
51028 assert( p->db!=0 );
51030 /* A connection with the read-uncommitted flag set will never try to
51031 ** obtain a read-lock using this function. The only read-lock obtained
51032 ** by a connection in read-uncommitted mode is on the sqlite_master
51033 ** table, and that lock is obtained in BtreeBeginTrans(). */
51034 assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
51036 /* This function should only be called on a sharable b-tree after it
51037 ** has been determined that no other b-tree holds a conflicting lock. */
51038 assert( p->sharable );
51039 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
51041 /* First search the list for an existing lock on this table. */
51042 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51043 if( pIter->iTable==iTable && pIter->pBtree==p ){
51044 pLock = pIter;
51045 break;
51049 /* If the above search did not find a BtLock struct associating Btree p
51050 ** with table iTable, allocate one and link it into the list.
51052 if( !pLock ){
51053 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
51054 if( !pLock ){
51055 return SQLITE_NOMEM;
51057 pLock->iTable = iTable;
51058 pLock->pBtree = p;
51059 pLock->pNext = pBt->pLock;
51060 pBt->pLock = pLock;
51063 /* Set the BtLock.eLock variable to the maximum of the current lock
51064 ** and the requested lock. This means if a write-lock was already held
51065 ** and a read-lock requested, we don't incorrectly downgrade the lock.
51067 assert( WRITE_LOCK>READ_LOCK );
51068 if( eLock>pLock->eLock ){
51069 pLock->eLock = eLock;
51072 return SQLITE_OK;
51074 #endif /* !SQLITE_OMIT_SHARED_CACHE */
51076 #ifndef SQLITE_OMIT_SHARED_CACHE
51078 ** Release all the table locks (locks obtained via calls to
51079 ** the setSharedCacheTableLock() procedure) held by Btree object p.
51081 ** This function assumes that Btree p has an open read or write
51082 ** transaction. If it does not, then the BTS_PENDING flag
51083 ** may be incorrectly cleared.
51085 static void clearAllSharedCacheTableLocks(Btree *p){
51086 BtShared *pBt = p->pBt;
51087 BtLock **ppIter = &pBt->pLock;
51089 assert( sqlite3BtreeHoldsMutex(p) );
51090 assert( p->sharable || 0==*ppIter );
51091 assert( p->inTrans>0 );
51093 while( *ppIter ){
51094 BtLock *pLock = *ppIter;
51095 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
51096 assert( pLock->pBtree->inTrans>=pLock->eLock );
51097 if( pLock->pBtree==p ){
51098 *ppIter = pLock->pNext;
51099 assert( pLock->iTable!=1 || pLock==&p->lock );
51100 if( pLock->iTable!=1 ){
51101 sqlite3_free(pLock);
51103 }else{
51104 ppIter = &pLock->pNext;
51108 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
51109 if( pBt->pWriter==p ){
51110 pBt->pWriter = 0;
51111 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
51112 }else if( pBt->nTransaction==2 ){
51113 /* This function is called when Btree p is concluding its
51114 ** transaction. If there currently exists a writer, and p is not
51115 ** that writer, then the number of locks held by connections other
51116 ** than the writer must be about to drop to zero. In this case
51117 ** set the BTS_PENDING flag to 0.
51119 ** If there is not currently a writer, then BTS_PENDING must
51120 ** be zero already. So this next line is harmless in that case.
51122 pBt->btsFlags &= ~BTS_PENDING;
51127 ** This function changes all write-locks held by Btree p into read-locks.
51129 static void downgradeAllSharedCacheTableLocks(Btree *p){
51130 BtShared *pBt = p->pBt;
51131 if( pBt->pWriter==p ){
51132 BtLock *pLock;
51133 pBt->pWriter = 0;
51134 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
51135 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
51136 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
51137 pLock->eLock = READ_LOCK;
51142 #endif /* SQLITE_OMIT_SHARED_CACHE */
51144 static void releasePage(MemPage *pPage); /* Forward reference */
51147 ***** This routine is used inside of assert() only ****
51149 ** Verify that the cursor holds the mutex on its BtShared
51151 #ifdef SQLITE_DEBUG
51152 static int cursorHoldsMutex(BtCursor *p){
51153 return sqlite3_mutex_held(p->pBt->mutex);
51155 #endif
51158 #ifndef SQLITE_OMIT_INCRBLOB
51160 ** Invalidate the overflow page-list cache for cursor pCur, if any.
51162 static void invalidateOverflowCache(BtCursor *pCur){
51163 assert( cursorHoldsMutex(pCur) );
51164 sqlite3_free(pCur->aOverflow);
51165 pCur->aOverflow = 0;
51169 ** Invalidate the overflow page-list cache for all cursors opened
51170 ** on the shared btree structure pBt.
51172 static void invalidateAllOverflowCache(BtShared *pBt){
51173 BtCursor *p;
51174 assert( sqlite3_mutex_held(pBt->mutex) );
51175 for(p=pBt->pCursor; p; p=p->pNext){
51176 invalidateOverflowCache(p);
51181 ** This function is called before modifying the contents of a table
51182 ** to invalidate any incrblob cursors that are open on the
51183 ** row or one of the rows being modified.
51185 ** If argument isClearTable is true, then the entire contents of the
51186 ** table is about to be deleted. In this case invalidate all incrblob
51187 ** cursors open on any row within the table with root-page pgnoRoot.
51189 ** Otherwise, if argument isClearTable is false, then the row with
51190 ** rowid iRow is being replaced or deleted. In this case invalidate
51191 ** only those incrblob cursors open on that specific row.
51193 static void invalidateIncrblobCursors(
51194 Btree *pBtree, /* The database file to check */
51195 i64 iRow, /* The rowid that might be changing */
51196 int isClearTable /* True if all rows are being deleted */
51198 BtCursor *p;
51199 BtShared *pBt = pBtree->pBt;
51200 assert( sqlite3BtreeHoldsMutex(pBtree) );
51201 for(p=pBt->pCursor; p; p=p->pNext){
51202 if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
51203 p->eState = CURSOR_INVALID;
51208 #else
51209 /* Stub functions when INCRBLOB is omitted */
51210 #define invalidateOverflowCache(x)
51211 #define invalidateAllOverflowCache(x)
51212 #define invalidateIncrblobCursors(x,y,z)
51213 #endif /* SQLITE_OMIT_INCRBLOB */
51216 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
51217 ** when a page that previously contained data becomes a free-list leaf
51218 ** page.
51220 ** The BtShared.pHasContent bitvec exists to work around an obscure
51221 ** bug caused by the interaction of two useful IO optimizations surrounding
51222 ** free-list leaf pages:
51224 ** 1) When all data is deleted from a page and the page becomes
51225 ** a free-list leaf page, the page is not written to the database
51226 ** (as free-list leaf pages contain no meaningful data). Sometimes
51227 ** such a page is not even journalled (as it will not be modified,
51228 ** why bother journalling it?).
51230 ** 2) When a free-list leaf page is reused, its content is not read
51231 ** from the database or written to the journal file (why should it
51232 ** be, if it is not at all meaningful?).
51234 ** By themselves, these optimizations work fine and provide a handy
51235 ** performance boost to bulk delete or insert operations. However, if
51236 ** a page is moved to the free-list and then reused within the same
51237 ** transaction, a problem comes up. If the page is not journalled when
51238 ** it is moved to the free-list and it is also not journalled when it
51239 ** is extracted from the free-list and reused, then the original data
51240 ** may be lost. In the event of a rollback, it may not be possible
51241 ** to restore the database to its original configuration.
51243 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
51244 ** moved to become a free-list leaf page, the corresponding bit is
51245 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
51246 ** optimization 2 above is omitted if the corresponding bit is already
51247 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
51248 ** at the end of every transaction.
51250 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
51251 int rc = SQLITE_OK;
51252 if( !pBt->pHasContent ){
51253 assert( pgno<=pBt->nPage );
51254 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
51255 if( !pBt->pHasContent ){
51256 rc = SQLITE_NOMEM;
51259 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
51260 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
51262 return rc;
51266 ** Query the BtShared.pHasContent vector.
51268 ** This function is called when a free-list leaf page is removed from the
51269 ** free-list for reuse. It returns false if it is safe to retrieve the
51270 ** page from the pager layer with the 'no-content' flag set. True otherwise.
51272 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
51273 Bitvec *p = pBt->pHasContent;
51274 return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
51278 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
51279 ** invoked at the conclusion of each write-transaction.
51281 static void btreeClearHasContent(BtShared *pBt){
51282 sqlite3BitvecDestroy(pBt->pHasContent);
51283 pBt->pHasContent = 0;
51287 ** Release all of the apPage[] pages for a cursor.
51289 static void btreeReleaseAllCursorPages(BtCursor *pCur){
51290 int i;
51291 for(i=0; i<=pCur->iPage; i++){
51292 releasePage(pCur->apPage[i]);
51293 pCur->apPage[i] = 0;
51295 pCur->iPage = -1;
51300 ** Save the current cursor position in the variables BtCursor.nKey
51301 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
51303 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
51304 ** prior to calling this routine.
51306 static int saveCursorPosition(BtCursor *pCur){
51307 int rc;
51309 assert( CURSOR_VALID==pCur->eState );
51310 assert( 0==pCur->pKey );
51311 assert( cursorHoldsMutex(pCur) );
51313 rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
51314 assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
51316 /* If this is an intKey table, then the above call to BtreeKeySize()
51317 ** stores the integer key in pCur->nKey. In this case this value is
51318 ** all that is required. Otherwise, if pCur is not open on an intKey
51319 ** table, then malloc space for and store the pCur->nKey bytes of key
51320 ** data.
51322 if( 0==pCur->apPage[0]->intKey ){
51323 void *pKey = sqlite3Malloc( (int)pCur->nKey );
51324 if( pKey ){
51325 rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
51326 if( rc==SQLITE_OK ){
51327 pCur->pKey = pKey;
51328 }else{
51329 sqlite3_free(pKey);
51331 }else{
51332 rc = SQLITE_NOMEM;
51335 assert( !pCur->apPage[0]->intKey || !pCur->pKey );
51337 if( rc==SQLITE_OK ){
51338 btreeReleaseAllCursorPages(pCur);
51339 pCur->eState = CURSOR_REQUIRESEEK;
51342 invalidateOverflowCache(pCur);
51343 return rc;
51347 ** Save the positions of all cursors (except pExcept) that are open on
51348 ** the table with root-page iRoot. Usually, this is called just before cursor
51349 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
51351 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
51352 BtCursor *p;
51353 assert( sqlite3_mutex_held(pBt->mutex) );
51354 assert( pExcept==0 || pExcept->pBt==pBt );
51355 for(p=pBt->pCursor; p; p=p->pNext){
51356 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
51357 if( p->eState==CURSOR_VALID ){
51358 int rc = saveCursorPosition(p);
51359 if( SQLITE_OK!=rc ){
51360 return rc;
51362 }else{
51363 testcase( p->iPage>0 );
51364 btreeReleaseAllCursorPages(p);
51368 return SQLITE_OK;
51372 ** Clear the current cursor position.
51374 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
51375 assert( cursorHoldsMutex(pCur) );
51376 sqlite3_free(pCur->pKey);
51377 pCur->pKey = 0;
51378 pCur->eState = CURSOR_INVALID;
51382 ** In this version of BtreeMoveto, pKey is a packed index record
51383 ** such as is generated by the OP_MakeRecord opcode. Unpack the
51384 ** record and then call BtreeMovetoUnpacked() to do the work.
51386 static int btreeMoveto(
51387 BtCursor *pCur, /* Cursor open on the btree to be searched */
51388 const void *pKey, /* Packed key if the btree is an index */
51389 i64 nKey, /* Integer key for tables. Size of pKey for indices */
51390 int bias, /* Bias search to the high end */
51391 int *pRes /* Write search results here */
51393 int rc; /* Status code */
51394 UnpackedRecord *pIdxKey; /* Unpacked index key */
51395 char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
51396 char *pFree = 0;
51398 if( pKey ){
51399 assert( nKey==(i64)(int)nKey );
51400 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
51401 pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
51403 if( pIdxKey==0 ) return SQLITE_NOMEM;
51404 sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
51405 if( pIdxKey->nField==0 ){
51406 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
51407 return SQLITE_CORRUPT_BKPT;
51409 }else{
51410 pIdxKey = 0;
51412 rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
51413 if( pFree ){
51414 sqlite3DbFree(pCur->pKeyInfo->db, pFree);
51416 return rc;
51420 ** Restore the cursor to the position it was in (or as close to as possible)
51421 ** when saveCursorPosition() was called. Note that this call deletes the
51422 ** saved position info stored by saveCursorPosition(), so there can be
51423 ** at most one effective restoreCursorPosition() call after each
51424 ** saveCursorPosition().
51426 static int btreeRestoreCursorPosition(BtCursor *pCur){
51427 int rc;
51428 assert( cursorHoldsMutex(pCur) );
51429 assert( pCur->eState>=CURSOR_REQUIRESEEK );
51430 if( pCur->eState==CURSOR_FAULT ){
51431 return pCur->skipNext;
51433 pCur->eState = CURSOR_INVALID;
51434 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
51435 if( rc==SQLITE_OK ){
51436 sqlite3_free(pCur->pKey);
51437 pCur->pKey = 0;
51438 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
51439 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
51440 pCur->eState = CURSOR_SKIPNEXT;
51443 return rc;
51446 #define restoreCursorPosition(p) \
51447 (p->eState>=CURSOR_REQUIRESEEK ? \
51448 btreeRestoreCursorPosition(p) : \
51449 SQLITE_OK)
51452 ** Determine whether or not a cursor has moved from the position it
51453 ** was last placed at. Cursors can move when the row they are pointing
51454 ** at is deleted out from under them.
51456 ** This routine returns an error code if something goes wrong. The
51457 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
51459 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
51460 int rc;
51462 rc = restoreCursorPosition(pCur);
51463 if( rc ){
51464 *pHasMoved = 1;
51465 return rc;
51467 if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
51468 *pHasMoved = 1;
51469 }else{
51470 *pHasMoved = 0;
51472 return SQLITE_OK;
51475 #ifndef SQLITE_OMIT_AUTOVACUUM
51477 ** Given a page number of a regular database page, return the page
51478 ** number for the pointer-map page that contains the entry for the
51479 ** input page number.
51481 ** Return 0 (not a valid page) for pgno==1 since there is
51482 ** no pointer map associated with page 1. The integrity_check logic
51483 ** requires that ptrmapPageno(*,1)!=1.
51485 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
51486 int nPagesPerMapPage;
51487 Pgno iPtrMap, ret;
51488 assert( sqlite3_mutex_held(pBt->mutex) );
51489 if( pgno<2 ) return 0;
51490 nPagesPerMapPage = (pBt->usableSize/5)+1;
51491 iPtrMap = (pgno-2)/nPagesPerMapPage;
51492 ret = (iPtrMap*nPagesPerMapPage) + 2;
51493 if( ret==PENDING_BYTE_PAGE(pBt) ){
51494 ret++;
51496 return ret;
51500 ** Write an entry into the pointer map.
51502 ** This routine updates the pointer map entry for page number 'key'
51503 ** so that it maps to type 'eType' and parent page number 'pgno'.
51505 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
51506 ** a no-op. If an error occurs, the appropriate error code is written
51507 ** into *pRC.
51509 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
51510 DbPage *pDbPage; /* The pointer map page */
51511 u8 *pPtrmap; /* The pointer map data */
51512 Pgno iPtrmap; /* The pointer map page number */
51513 int offset; /* Offset in pointer map page */
51514 int rc; /* Return code from subfunctions */
51516 if( *pRC ) return;
51518 assert( sqlite3_mutex_held(pBt->mutex) );
51519 /* The master-journal page number must never be used as a pointer map page */
51520 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
51522 assert( pBt->autoVacuum );
51523 if( key==0 ){
51524 *pRC = SQLITE_CORRUPT_BKPT;
51525 return;
51527 iPtrmap = PTRMAP_PAGENO(pBt, key);
51528 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
51529 if( rc!=SQLITE_OK ){
51530 *pRC = rc;
51531 return;
51533 offset = PTRMAP_PTROFFSET(iPtrmap, key);
51534 if( offset<0 ){
51535 *pRC = SQLITE_CORRUPT_BKPT;
51536 goto ptrmap_exit;
51538 assert( offset <= (int)pBt->usableSize-5 );
51539 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
51541 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
51542 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
51543 *pRC= rc = sqlite3PagerWrite(pDbPage);
51544 if( rc==SQLITE_OK ){
51545 pPtrmap[offset] = eType;
51546 put4byte(&pPtrmap[offset+1], parent);
51550 ptrmap_exit:
51551 sqlite3PagerUnref(pDbPage);
51555 ** Read an entry from the pointer map.
51557 ** This routine retrieves the pointer map entry for page 'key', writing
51558 ** the type and parent page number to *pEType and *pPgno respectively.
51559 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
51561 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
51562 DbPage *pDbPage; /* The pointer map page */
51563 int iPtrmap; /* Pointer map page index */
51564 u8 *pPtrmap; /* Pointer map page data */
51565 int offset; /* Offset of entry in pointer map */
51566 int rc;
51568 assert( sqlite3_mutex_held(pBt->mutex) );
51570 iPtrmap = PTRMAP_PAGENO(pBt, key);
51571 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
51572 if( rc!=0 ){
51573 return rc;
51575 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
51577 offset = PTRMAP_PTROFFSET(iPtrmap, key);
51578 if( offset<0 ){
51579 sqlite3PagerUnref(pDbPage);
51580 return SQLITE_CORRUPT_BKPT;
51582 assert( offset <= (int)pBt->usableSize-5 );
51583 assert( pEType!=0 );
51584 *pEType = pPtrmap[offset];
51585 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
51587 sqlite3PagerUnref(pDbPage);
51588 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
51589 return SQLITE_OK;
51592 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
51593 #define ptrmapPut(w,x,y,z,rc)
51594 #define ptrmapGet(w,x,y,z) SQLITE_OK
51595 #define ptrmapPutOvflPtr(x, y, rc)
51596 #endif
51599 ** Given a btree page and a cell index (0 means the first cell on
51600 ** the page, 1 means the second cell, and so forth) return a pointer
51601 ** to the cell content.
51603 ** This routine works only for pages that do not contain overflow cells.
51605 #define findCell(P,I) \
51606 ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
51607 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
51611 ** This a more complex version of findCell() that works for
51612 ** pages that do contain overflow cells.
51614 static u8 *findOverflowCell(MemPage *pPage, int iCell){
51615 int i;
51616 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51617 for(i=pPage->nOverflow-1; i>=0; i--){
51618 int k;
51619 k = pPage->aiOvfl[i];
51620 if( k<=iCell ){
51621 if( k==iCell ){
51622 return pPage->apOvfl[i];
51624 iCell--;
51627 return findCell(pPage, iCell);
51631 ** Parse a cell content block and fill in the CellInfo structure. There
51632 ** are two versions of this function. btreeParseCell() takes a
51633 ** cell index as the second argument and btreeParseCellPtr()
51634 ** takes a pointer to the body of the cell as its second argument.
51636 ** Within this file, the parseCell() macro can be called instead of
51637 ** btreeParseCellPtr(). Using some compilers, this will be faster.
51639 static void btreeParseCellPtr(
51640 MemPage *pPage, /* Page containing the cell */
51641 u8 *pCell, /* Pointer to the cell text. */
51642 CellInfo *pInfo /* Fill in this structure */
51644 u16 n; /* Number bytes in cell content header */
51645 u32 nPayload; /* Number of bytes of cell payload */
51647 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51649 pInfo->pCell = pCell;
51650 assert( pPage->leaf==0 || pPage->leaf==1 );
51651 n = pPage->childPtrSize;
51652 assert( n==4-4*pPage->leaf );
51653 if( pPage->intKey ){
51654 if( pPage->hasData ){
51655 assert( n==0 );
51656 n = getVarint32(pCell, nPayload);
51657 }else{
51658 nPayload = 0;
51660 n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
51661 pInfo->nData = nPayload;
51662 }else{
51663 pInfo->nData = 0;
51664 n += getVarint32(&pCell[n], nPayload);
51665 pInfo->nKey = nPayload;
51667 pInfo->nPayload = nPayload;
51668 pInfo->nHeader = n;
51669 testcase( nPayload==pPage->maxLocal );
51670 testcase( nPayload==pPage->maxLocal+1 );
51671 if( likely(nPayload<=pPage->maxLocal) ){
51672 /* This is the (easy) common case where the entire payload fits
51673 ** on the local page. No overflow is required.
51675 if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
51676 pInfo->nLocal = (u16)nPayload;
51677 pInfo->iOverflow = 0;
51678 }else{
51679 /* If the payload will not fit completely on the local page, we have
51680 ** to decide how much to store locally and how much to spill onto
51681 ** overflow pages. The strategy is to minimize the amount of unused
51682 ** space on overflow pages while keeping the amount of local storage
51683 ** in between minLocal and maxLocal.
51685 ** Warning: changing the way overflow payload is distributed in any
51686 ** way will result in an incompatible file format.
51688 int minLocal; /* Minimum amount of payload held locally */
51689 int maxLocal; /* Maximum amount of payload held locally */
51690 int surplus; /* Overflow payload available for local storage */
51692 minLocal = pPage->minLocal;
51693 maxLocal = pPage->maxLocal;
51694 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
51695 testcase( surplus==maxLocal );
51696 testcase( surplus==maxLocal+1 );
51697 if( surplus <= maxLocal ){
51698 pInfo->nLocal = (u16)surplus;
51699 }else{
51700 pInfo->nLocal = (u16)minLocal;
51702 pInfo->iOverflow = (u16)(pInfo->nLocal + n);
51703 pInfo->nSize = pInfo->iOverflow + 4;
51706 #define parseCell(pPage, iCell, pInfo) \
51707 btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
51708 static void btreeParseCell(
51709 MemPage *pPage, /* Page containing the cell */
51710 int iCell, /* The cell index. First cell is 0 */
51711 CellInfo *pInfo /* Fill in this structure */
51713 parseCell(pPage, iCell, pInfo);
51717 ** Compute the total number of bytes that a Cell needs in the cell
51718 ** data area of the btree-page. The return number includes the cell
51719 ** data header and the local payload, but not any overflow page or
51720 ** the space used by the cell pointer.
51722 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
51723 u8 *pIter = &pCell[pPage->childPtrSize];
51724 u32 nSize;
51726 #ifdef SQLITE_DEBUG
51727 /* The value returned by this function should always be the same as
51728 ** the (CellInfo.nSize) value found by doing a full parse of the
51729 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
51730 ** this function verifies that this invariant is not violated. */
51731 CellInfo debuginfo;
51732 btreeParseCellPtr(pPage, pCell, &debuginfo);
51733 #endif
51735 if( pPage->intKey ){
51736 u8 *pEnd;
51737 if( pPage->hasData ){
51738 pIter += getVarint32(pIter, nSize);
51739 }else{
51740 nSize = 0;
51743 /* pIter now points at the 64-bit integer key value, a variable length
51744 ** integer. The following block moves pIter to point at the first byte
51745 ** past the end of the key value. */
51746 pEnd = &pIter[9];
51747 while( (*pIter++)&0x80 && pIter<pEnd );
51748 }else{
51749 pIter += getVarint32(pIter, nSize);
51752 testcase( nSize==pPage->maxLocal );
51753 testcase( nSize==pPage->maxLocal+1 );
51754 if( nSize>pPage->maxLocal ){
51755 int minLocal = pPage->minLocal;
51756 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
51757 testcase( nSize==pPage->maxLocal );
51758 testcase( nSize==pPage->maxLocal+1 );
51759 if( nSize>pPage->maxLocal ){
51760 nSize = minLocal;
51762 nSize += 4;
51764 nSize += (u32)(pIter - pCell);
51766 /* The minimum size of any cell is 4 bytes. */
51767 if( nSize<4 ){
51768 nSize = 4;
51771 assert( nSize==debuginfo.nSize );
51772 return (u16)nSize;
51775 #ifdef SQLITE_DEBUG
51776 /* This variation on cellSizePtr() is used inside of assert() statements
51777 ** only. */
51778 static u16 cellSize(MemPage *pPage, int iCell){
51779 return cellSizePtr(pPage, findCell(pPage, iCell));
51781 #endif
51783 #ifndef SQLITE_OMIT_AUTOVACUUM
51785 ** If the cell pCell, part of page pPage contains a pointer
51786 ** to an overflow page, insert an entry into the pointer-map
51787 ** for the overflow page.
51789 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
51790 CellInfo info;
51791 if( *pRC ) return;
51792 assert( pCell!=0 );
51793 btreeParseCellPtr(pPage, pCell, &info);
51794 assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
51795 if( info.iOverflow ){
51796 Pgno ovfl = get4byte(&pCell[info.iOverflow]);
51797 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
51800 #endif
51804 ** Defragment the page given. All Cells are moved to the
51805 ** end of the page and all free space is collected into one
51806 ** big FreeBlk that occurs in between the header and cell
51807 ** pointer array and the cell content area.
51809 static int defragmentPage(MemPage *pPage){
51810 int i; /* Loop counter */
51811 int pc; /* Address of a i-th cell */
51812 int hdr; /* Offset to the page header */
51813 int size; /* Size of a cell */
51814 int usableSize; /* Number of usable bytes on a page */
51815 int cellOffset; /* Offset to the cell pointer array */
51816 int cbrk; /* Offset to the cell content area */
51817 int nCell; /* Number of cells on the page */
51818 unsigned char *data; /* The page data */
51819 unsigned char *temp; /* Temp area for cell content */
51820 int iCellFirst; /* First allowable cell index */
51821 int iCellLast; /* Last possible cell index */
51824 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51825 assert( pPage->pBt!=0 );
51826 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
51827 assert( pPage->nOverflow==0 );
51828 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51829 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
51830 data = pPage->aData;
51831 hdr = pPage->hdrOffset;
51832 cellOffset = pPage->cellOffset;
51833 nCell = pPage->nCell;
51834 assert( nCell==get2byte(&data[hdr+3]) );
51835 usableSize = pPage->pBt->usableSize;
51836 cbrk = get2byte(&data[hdr+5]);
51837 memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
51838 cbrk = usableSize;
51839 iCellFirst = cellOffset + 2*nCell;
51840 iCellLast = usableSize - 4;
51841 for(i=0; i<nCell; i++){
51842 u8 *pAddr; /* The i-th cell pointer */
51843 pAddr = &data[cellOffset + i*2];
51844 pc = get2byte(pAddr);
51845 testcase( pc==iCellFirst );
51846 testcase( pc==iCellLast );
51847 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51848 /* These conditions have already been verified in btreeInitPage()
51849 ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
51851 if( pc<iCellFirst || pc>iCellLast ){
51852 return SQLITE_CORRUPT_BKPT;
51854 #endif
51855 assert( pc>=iCellFirst && pc<=iCellLast );
51856 size = cellSizePtr(pPage, &temp[pc]);
51857 cbrk -= size;
51858 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51859 if( cbrk<iCellFirst ){
51860 return SQLITE_CORRUPT_BKPT;
51862 #else
51863 if( cbrk<iCellFirst || pc+size>usableSize ){
51864 return SQLITE_CORRUPT_BKPT;
51866 #endif
51867 assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
51868 testcase( cbrk+size==usableSize );
51869 testcase( pc+size==usableSize );
51870 memcpy(&data[cbrk], &temp[pc], size);
51871 put2byte(pAddr, cbrk);
51873 assert( cbrk>=iCellFirst );
51874 put2byte(&data[hdr+5], cbrk);
51875 data[hdr+1] = 0;
51876 data[hdr+2] = 0;
51877 data[hdr+7] = 0;
51878 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
51879 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51880 if( cbrk-iCellFirst!=pPage->nFree ){
51881 return SQLITE_CORRUPT_BKPT;
51883 return SQLITE_OK;
51887 ** Allocate nByte bytes of space from within the B-Tree page passed
51888 ** as the first argument. Write into *pIdx the index into pPage->aData[]
51889 ** of the first byte of allocated space. Return either SQLITE_OK or
51890 ** an error code (usually SQLITE_CORRUPT).
51892 ** The caller guarantees that there is sufficient space to make the
51893 ** allocation. This routine might need to defragment in order to bring
51894 ** all the space together, however. This routine will avoid using
51895 ** the first two bytes past the cell pointer area since presumably this
51896 ** allocation is being made in order to insert a new cell, so we will
51897 ** also end up needing a new cell pointer.
51899 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
51900 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
51901 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
51902 int nFrag; /* Number of fragmented bytes on pPage */
51903 int top; /* First byte of cell content area */
51904 int gap; /* First byte of gap between cell pointers and cell content */
51905 int rc; /* Integer return code */
51906 int usableSize; /* Usable size of the page */
51908 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51909 assert( pPage->pBt );
51910 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51911 assert( nByte>=0 ); /* Minimum cell size is 4 */
51912 assert( pPage->nFree>=nByte );
51913 assert( pPage->nOverflow==0 );
51914 usableSize = pPage->pBt->usableSize;
51915 assert( nByte < usableSize-8 );
51917 nFrag = data[hdr+7];
51918 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
51919 gap = pPage->cellOffset + 2*pPage->nCell;
51920 top = get2byteNotZero(&data[hdr+5]);
51921 if( gap>top ) return SQLITE_CORRUPT_BKPT;
51922 testcase( gap+2==top );
51923 testcase( gap+1==top );
51924 testcase( gap==top );
51926 if( nFrag>=60 ){
51927 /* Always defragment highly fragmented pages */
51928 rc = defragmentPage(pPage);
51929 if( rc ) return rc;
51930 top = get2byteNotZero(&data[hdr+5]);
51931 }else if( gap+2<=top ){
51932 /* Search the freelist looking for a free slot big enough to satisfy
51933 ** the request. The allocation is made from the first free slot in
51934 ** the list that is large enough to accommodate it.
51936 int pc, addr;
51937 for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
51938 int size; /* Size of the free slot */
51939 if( pc>usableSize-4 || pc<addr+4 ){
51940 return SQLITE_CORRUPT_BKPT;
51942 size = get2byte(&data[pc+2]);
51943 if( size>=nByte ){
51944 int x = size - nByte;
51945 testcase( x==4 );
51946 testcase( x==3 );
51947 if( x<4 ){
51948 /* Remove the slot from the free-list. Update the number of
51949 ** fragmented bytes within the page. */
51950 memcpy(&data[addr], &data[pc], 2);
51951 data[hdr+7] = (u8)(nFrag + x);
51952 }else if( size+pc > usableSize ){
51953 return SQLITE_CORRUPT_BKPT;
51954 }else{
51955 /* The slot remains on the free-list. Reduce its size to account
51956 ** for the portion used by the new allocation. */
51957 put2byte(&data[pc+2], x);
51959 *pIdx = pc + x;
51960 return SQLITE_OK;
51965 /* Check to make sure there is enough space in the gap to satisfy
51966 ** the allocation. If not, defragment.
51968 testcase( gap+2+nByte==top );
51969 if( gap+2+nByte>top ){
51970 rc = defragmentPage(pPage);
51971 if( rc ) return rc;
51972 top = get2byteNotZero(&data[hdr+5]);
51973 assert( gap+nByte<=top );
51977 /* Allocate memory from the gap in between the cell pointer array
51978 ** and the cell content area. The btreeInitPage() call has already
51979 ** validated the freelist. Given that the freelist is valid, there
51980 ** is no way that the allocation can extend off the end of the page.
51981 ** The assert() below verifies the previous sentence.
51983 top -= nByte;
51984 put2byte(&data[hdr+5], top);
51985 assert( top+nByte <= (int)pPage->pBt->usableSize );
51986 *pIdx = top;
51987 return SQLITE_OK;
51991 ** Return a section of the pPage->aData to the freelist.
51992 ** The first byte of the new free block is pPage->aDisk[start]
51993 ** and the size of the block is "size" bytes.
51995 ** Most of the effort here is involved in coalesing adjacent
51996 ** free blocks into a single big free block.
51998 static int freeSpace(MemPage *pPage, int start, int size){
51999 int addr, pbegin, hdr;
52000 int iLast; /* Largest possible freeblock offset */
52001 unsigned char *data = pPage->aData;
52003 assert( pPage->pBt!=0 );
52004 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52005 assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
52006 assert( (start + size) <= (int)pPage->pBt->usableSize );
52007 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52008 assert( size>=0 ); /* Minimum cell size is 4 */
52010 if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
52011 /* Overwrite deleted information with zeros when the secure_delete
52012 ** option is enabled */
52013 memset(&data[start], 0, size);
52016 /* Add the space back into the linked list of freeblocks. Note that
52017 ** even though the freeblock list was checked by btreeInitPage(),
52018 ** btreeInitPage() did not detect overlapping cells or
52019 ** freeblocks that overlapped cells. Nor does it detect when the
52020 ** cell content area exceeds the value in the page header. If these
52021 ** situations arise, then subsequent insert operations might corrupt
52022 ** the freelist. So we do need to check for corruption while scanning
52023 ** the freelist.
52025 hdr = pPage->hdrOffset;
52026 addr = hdr + 1;
52027 iLast = pPage->pBt->usableSize - 4;
52028 assert( start<=iLast );
52029 while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
52030 if( pbegin<addr+4 ){
52031 return SQLITE_CORRUPT_BKPT;
52033 addr = pbegin;
52035 if( pbegin>iLast ){
52036 return SQLITE_CORRUPT_BKPT;
52038 assert( pbegin>addr || pbegin==0 );
52039 put2byte(&data[addr], start);
52040 put2byte(&data[start], pbegin);
52041 put2byte(&data[start+2], size);
52042 pPage->nFree = pPage->nFree + (u16)size;
52044 /* Coalesce adjacent free blocks */
52045 addr = hdr + 1;
52046 while( (pbegin = get2byte(&data[addr]))>0 ){
52047 int pnext, psize, x;
52048 assert( pbegin>addr );
52049 assert( pbegin <= (int)pPage->pBt->usableSize-4 );
52050 pnext = get2byte(&data[pbegin]);
52051 psize = get2byte(&data[pbegin+2]);
52052 if( pbegin + psize + 3 >= pnext && pnext>0 ){
52053 int frag = pnext - (pbegin+psize);
52054 if( (frag<0) || (frag>(int)data[hdr+7]) ){
52055 return SQLITE_CORRUPT_BKPT;
52057 data[hdr+7] -= (u8)frag;
52058 x = get2byte(&data[pnext]);
52059 put2byte(&data[pbegin], x);
52060 x = pnext + get2byte(&data[pnext+2]) - pbegin;
52061 put2byte(&data[pbegin+2], x);
52062 }else{
52063 addr = pbegin;
52067 /* If the cell content area begins with a freeblock, remove it. */
52068 if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
52069 int top;
52070 pbegin = get2byte(&data[hdr+1]);
52071 memcpy(&data[hdr+1], &data[pbegin], 2);
52072 top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
52073 put2byte(&data[hdr+5], top);
52075 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52076 return SQLITE_OK;
52080 ** Decode the flags byte (the first byte of the header) for a page
52081 ** and initialize fields of the MemPage structure accordingly.
52083 ** Only the following combinations are supported. Anything different
52084 ** indicates a corrupt database files:
52086 ** PTF_ZERODATA
52087 ** PTF_ZERODATA | PTF_LEAF
52088 ** PTF_LEAFDATA | PTF_INTKEY
52089 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
52091 static int decodeFlags(MemPage *pPage, int flagByte){
52092 BtShared *pBt; /* A copy of pPage->pBt */
52094 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
52095 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52096 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
52097 flagByte &= ~PTF_LEAF;
52098 pPage->childPtrSize = 4-4*pPage->leaf;
52099 pBt = pPage->pBt;
52100 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
52101 pPage->intKey = 1;
52102 pPage->hasData = pPage->leaf;
52103 pPage->maxLocal = pBt->maxLeaf;
52104 pPage->minLocal = pBt->minLeaf;
52105 }else if( flagByte==PTF_ZERODATA ){
52106 pPage->intKey = 0;
52107 pPage->hasData = 0;
52108 pPage->maxLocal = pBt->maxLocal;
52109 pPage->minLocal = pBt->minLocal;
52110 }else{
52111 return SQLITE_CORRUPT_BKPT;
52113 pPage->max1bytePayload = pBt->max1bytePayload;
52114 return SQLITE_OK;
52118 ** Initialize the auxiliary information for a disk block.
52120 ** Return SQLITE_OK on success. If we see that the page does
52121 ** not contain a well-formed database page, then return
52122 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
52123 ** guarantee that the page is well-formed. It only shows that
52124 ** we failed to detect any corruption.
52126 static int btreeInitPage(MemPage *pPage){
52128 assert( pPage->pBt!=0 );
52129 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52130 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
52131 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
52132 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
52134 if( !pPage->isInit ){
52135 u16 pc; /* Address of a freeblock within pPage->aData[] */
52136 u8 hdr; /* Offset to beginning of page header */
52137 u8 *data; /* Equal to pPage->aData */
52138 BtShared *pBt; /* The main btree structure */
52139 int usableSize; /* Amount of usable space on each page */
52140 u16 cellOffset; /* Offset from start of page to first cell pointer */
52141 int nFree; /* Number of unused bytes on the page */
52142 int top; /* First byte of the cell content area */
52143 int iCellFirst; /* First allowable cell or freeblock offset */
52144 int iCellLast; /* Last possible cell or freeblock offset */
52146 pBt = pPage->pBt;
52148 hdr = pPage->hdrOffset;
52149 data = pPage->aData;
52150 if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
52151 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
52152 pPage->maskPage = (u16)(pBt->pageSize - 1);
52153 pPage->nOverflow = 0;
52154 usableSize = pBt->usableSize;
52155 pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
52156 pPage->aDataEnd = &data[usableSize];
52157 pPage->aCellIdx = &data[cellOffset];
52158 top = get2byteNotZero(&data[hdr+5]);
52159 pPage->nCell = get2byte(&data[hdr+3]);
52160 if( pPage->nCell>MX_CELL(pBt) ){
52161 /* To many cells for a single page. The page must be corrupt */
52162 return SQLITE_CORRUPT_BKPT;
52164 testcase( pPage->nCell==MX_CELL(pBt) );
52166 /* A malformed database page might cause us to read past the end
52167 ** of page when parsing a cell.
52169 ** The following block of code checks early to see if a cell extends
52170 ** past the end of a page boundary and causes SQLITE_CORRUPT to be
52171 ** returned if it does.
52173 iCellFirst = cellOffset + 2*pPage->nCell;
52174 iCellLast = usableSize - 4;
52175 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
52177 int i; /* Index into the cell pointer array */
52178 int sz; /* Size of a cell */
52180 if( !pPage->leaf ) iCellLast--;
52181 for(i=0; i<pPage->nCell; i++){
52182 pc = get2byte(&data[cellOffset+i*2]);
52183 testcase( pc==iCellFirst );
52184 testcase( pc==iCellLast );
52185 if( pc<iCellFirst || pc>iCellLast ){
52186 return SQLITE_CORRUPT_BKPT;
52188 sz = cellSizePtr(pPage, &data[pc]);
52189 testcase( pc+sz==usableSize );
52190 if( pc+sz>usableSize ){
52191 return SQLITE_CORRUPT_BKPT;
52194 if( !pPage->leaf ) iCellLast++;
52196 #endif
52198 /* Compute the total free space on the page */
52199 pc = get2byte(&data[hdr+1]);
52200 nFree = data[hdr+7] + top;
52201 while( pc>0 ){
52202 u16 next, size;
52203 if( pc<iCellFirst || pc>iCellLast ){
52204 /* Start of free block is off the page */
52205 return SQLITE_CORRUPT_BKPT;
52207 next = get2byte(&data[pc]);
52208 size = get2byte(&data[pc+2]);
52209 if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
52210 /* Free blocks must be in ascending order. And the last byte of
52211 ** the free-block must lie on the database page. */
52212 return SQLITE_CORRUPT_BKPT;
52214 nFree = nFree + size;
52215 pc = next;
52218 /* At this point, nFree contains the sum of the offset to the start
52219 ** of the cell-content area plus the number of free bytes within
52220 ** the cell-content area. If this is greater than the usable-size
52221 ** of the page, then the page must be corrupted. This check also
52222 ** serves to verify that the offset to the start of the cell-content
52223 ** area, according to the page header, lies within the page.
52225 if( nFree>usableSize ){
52226 return SQLITE_CORRUPT_BKPT;
52228 pPage->nFree = (u16)(nFree - iCellFirst);
52229 pPage->isInit = 1;
52231 return SQLITE_OK;
52235 ** Set up a raw page so that it looks like a database page holding
52236 ** no entries.
52238 static void zeroPage(MemPage *pPage, int flags){
52239 unsigned char *data = pPage->aData;
52240 BtShared *pBt = pPage->pBt;
52241 u8 hdr = pPage->hdrOffset;
52242 u16 first;
52244 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
52245 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
52246 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
52247 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52248 assert( sqlite3_mutex_held(pBt->mutex) );
52249 if( pBt->btsFlags & BTS_SECURE_DELETE ){
52250 memset(&data[hdr], 0, pBt->usableSize - hdr);
52252 data[hdr] = (char)flags;
52253 first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
52254 memset(&data[hdr+1], 0, 4);
52255 data[hdr+7] = 0;
52256 put2byte(&data[hdr+5], pBt->usableSize);
52257 pPage->nFree = (u16)(pBt->usableSize - first);
52258 decodeFlags(pPage, flags);
52259 pPage->hdrOffset = hdr;
52260 pPage->cellOffset = first;
52261 pPage->aDataEnd = &data[pBt->usableSize];
52262 pPage->aCellIdx = &data[first];
52263 pPage->nOverflow = 0;
52264 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
52265 pPage->maskPage = (u16)(pBt->pageSize - 1);
52266 pPage->nCell = 0;
52267 pPage->isInit = 1;
52272 ** Convert a DbPage obtained from the pager into a MemPage used by
52273 ** the btree layer.
52275 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
52276 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
52277 pPage->aData = sqlite3PagerGetData(pDbPage);
52278 pPage->pDbPage = pDbPage;
52279 pPage->pBt = pBt;
52280 pPage->pgno = pgno;
52281 pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
52282 return pPage;
52286 ** Get a page from the pager. Initialize the MemPage.pBt and
52287 ** MemPage.aData elements if needed.
52289 ** If the noContent flag is set, it means that we do not care about
52290 ** the content of the page at this time. So do not go to the disk
52291 ** to fetch the content. Just fill in the content with zeros for now.
52292 ** If in the future we call sqlite3PagerWrite() on this page, that
52293 ** means we have started to be concerned about content and the disk
52294 ** read should occur at that point.
52296 static int btreeGetPage(
52297 BtShared *pBt, /* The btree */
52298 Pgno pgno, /* Number of the page to fetch */
52299 MemPage **ppPage, /* Return the page in this parameter */
52300 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
52302 int rc;
52303 DbPage *pDbPage;
52305 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
52306 assert( sqlite3_mutex_held(pBt->mutex) );
52307 rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
52308 if( rc ) return rc;
52309 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
52310 return SQLITE_OK;
52314 ** Retrieve a page from the pager cache. If the requested page is not
52315 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
52316 ** MemPage.aData elements if needed.
52318 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
52319 DbPage *pDbPage;
52320 assert( sqlite3_mutex_held(pBt->mutex) );
52321 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
52322 if( pDbPage ){
52323 return btreePageFromDbPage(pDbPage, pgno, pBt);
52325 return 0;
52329 ** Return the size of the database file in pages. If there is any kind of
52330 ** error, return ((unsigned int)-1).
52332 static Pgno btreePagecount(BtShared *pBt){
52333 return pBt->nPage;
52335 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
52336 assert( sqlite3BtreeHoldsMutex(p) );
52337 assert( ((p->pBt->nPage)&0x8000000)==0 );
52338 return (int)btreePagecount(p->pBt);
52342 ** Get a page from the pager and initialize it. This routine is just a
52343 ** convenience wrapper around separate calls to btreeGetPage() and
52344 ** btreeInitPage().
52346 ** If an error occurs, then the value *ppPage is set to is undefined. It
52347 ** may remain unchanged, or it may be set to an invalid value.
52349 static int getAndInitPage(
52350 BtShared *pBt, /* The database file */
52351 Pgno pgno, /* Number of the page to get */
52352 MemPage **ppPage, /* Write the page pointer here */
52353 int bReadonly /* PAGER_GET_READONLY or 0 */
52355 int rc;
52356 assert( sqlite3_mutex_held(pBt->mutex) );
52357 assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
52359 if( pgno>btreePagecount(pBt) ){
52360 rc = SQLITE_CORRUPT_BKPT;
52361 }else{
52362 rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
52363 if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
52364 rc = btreeInitPage(*ppPage);
52365 if( rc!=SQLITE_OK ){
52366 releasePage(*ppPage);
52371 testcase( pgno==0 );
52372 assert( pgno!=0 || rc==SQLITE_CORRUPT );
52373 return rc;
52377 ** Release a MemPage. This should be called once for each prior
52378 ** call to btreeGetPage.
52380 static void releasePage(MemPage *pPage){
52381 if( pPage ){
52382 assert( pPage->aData );
52383 assert( pPage->pBt );
52384 assert( pPage->pDbPage!=0 );
52385 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
52386 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
52387 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52388 sqlite3PagerUnrefNotNull(pPage->pDbPage);
52393 ** During a rollback, when the pager reloads information into the cache
52394 ** so that the cache is restored to its original state at the start of
52395 ** the transaction, for each page restored this routine is called.
52397 ** This routine needs to reset the extra data section at the end of the
52398 ** page to agree with the restored data.
52400 static void pageReinit(DbPage *pData){
52401 MemPage *pPage;
52402 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
52403 assert( sqlite3PagerPageRefcount(pData)>0 );
52404 if( pPage->isInit ){
52405 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52406 pPage->isInit = 0;
52407 if( sqlite3PagerPageRefcount(pData)>1 ){
52408 /* pPage might not be a btree page; it might be an overflow page
52409 ** or ptrmap page or a free page. In those cases, the following
52410 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
52411 ** But no harm is done by this. And it is very important that
52412 ** btreeInitPage() be called on every btree page so we make
52413 ** the call for every page that comes in for re-initing. */
52414 btreeInitPage(pPage);
52420 ** Invoke the busy handler for a btree.
52422 static int btreeInvokeBusyHandler(void *pArg){
52423 BtShared *pBt = (BtShared*)pArg;
52424 assert( pBt->db );
52425 assert( sqlite3_mutex_held(pBt->db->mutex) );
52426 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
52430 ** Open a database file.
52432 ** zFilename is the name of the database file. If zFilename is NULL
52433 ** then an ephemeral database is created. The ephemeral database might
52434 ** be exclusively in memory, or it might use a disk-based memory cache.
52435 ** Either way, the ephemeral database will be automatically deleted
52436 ** when sqlite3BtreeClose() is called.
52438 ** If zFilename is ":memory:" then an in-memory database is created
52439 ** that is automatically destroyed when it is closed.
52441 ** The "flags" parameter is a bitmask that might contain bits like
52442 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
52444 ** If the database is already opened in the same database connection
52445 ** and we are in shared cache mode, then the open will fail with an
52446 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
52447 ** objects in the same database connection since doing so will lead
52448 ** to problems with locking.
52450 SQLITE_PRIVATE int sqlite3BtreeOpen(
52451 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
52452 const char *zFilename, /* Name of the file containing the BTree database */
52453 sqlite3 *db, /* Associated database handle */
52454 Btree **ppBtree, /* Pointer to new Btree object written here */
52455 int flags, /* Options */
52456 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
52458 BtShared *pBt = 0; /* Shared part of btree structure */
52459 Btree *p; /* Handle to return */
52460 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
52461 int rc = SQLITE_OK; /* Result code from this function */
52462 u8 nReserve; /* Byte of unused space on each page */
52463 unsigned char zDbHeader[100]; /* Database header content */
52465 /* True if opening an ephemeral, temporary database */
52466 const int isTempDb = zFilename==0 || zFilename[0]==0;
52468 /* Set the variable isMemdb to true for an in-memory database, or
52469 ** false for a file-based database.
52471 #ifdef SQLITE_OMIT_MEMORYDB
52472 const int isMemdb = 0;
52473 #else
52474 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
52475 || (isTempDb && sqlite3TempInMemory(db))
52476 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
52477 #endif
52479 assert( db!=0 );
52480 assert( pVfs!=0 );
52481 assert( sqlite3_mutex_held(db->mutex) );
52482 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
52484 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
52485 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
52487 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
52488 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
52490 if( isMemdb ){
52491 flags |= BTREE_MEMORY;
52493 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
52494 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
52496 p = sqlite3MallocZero(sizeof(Btree));
52497 if( !p ){
52498 return SQLITE_NOMEM;
52500 p->inTrans = TRANS_NONE;
52501 p->db = db;
52502 #ifndef SQLITE_OMIT_SHARED_CACHE
52503 p->lock.pBtree = p;
52504 p->lock.iTable = 1;
52505 #endif
52507 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
52509 ** If this Btree is a candidate for shared cache, try to find an
52510 ** existing BtShared object that we can share with
52512 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
52513 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
52514 int nFullPathname = pVfs->mxPathname+1;
52515 char *zFullPathname = sqlite3Malloc(nFullPathname);
52516 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
52517 p->sharable = 1;
52518 if( !zFullPathname ){
52519 sqlite3_free(p);
52520 return SQLITE_NOMEM;
52522 if( isMemdb ){
52523 memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
52524 }else{
52525 rc = sqlite3OsFullPathname(pVfs, zFilename,
52526 nFullPathname, zFullPathname);
52527 if( rc ){
52528 sqlite3_free(zFullPathname);
52529 sqlite3_free(p);
52530 return rc;
52533 #if SQLITE_THREADSAFE
52534 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
52535 sqlite3_mutex_enter(mutexOpen);
52536 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
52537 sqlite3_mutex_enter(mutexShared);
52538 #endif
52539 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
52540 assert( pBt->nRef>0 );
52541 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
52542 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
52543 int iDb;
52544 for(iDb=db->nDb-1; iDb>=0; iDb--){
52545 Btree *pExisting = db->aDb[iDb].pBt;
52546 if( pExisting && pExisting->pBt==pBt ){
52547 sqlite3_mutex_leave(mutexShared);
52548 sqlite3_mutex_leave(mutexOpen);
52549 sqlite3_free(zFullPathname);
52550 sqlite3_free(p);
52551 return SQLITE_CONSTRAINT;
52554 p->pBt = pBt;
52555 pBt->nRef++;
52556 break;
52559 sqlite3_mutex_leave(mutexShared);
52560 sqlite3_free(zFullPathname);
52562 #ifdef SQLITE_DEBUG
52563 else{
52564 /* In debug mode, we mark all persistent databases as sharable
52565 ** even when they are not. This exercises the locking code and
52566 ** gives more opportunity for asserts(sqlite3_mutex_held())
52567 ** statements to find locking problems.
52569 p->sharable = 1;
52571 #endif
52573 #endif
52574 if( pBt==0 ){
52576 ** The following asserts make sure that structures used by the btree are
52577 ** the right size. This is to guard against size changes that result
52578 ** when compiling on a different architecture.
52580 assert( sizeof(i64)==8 || sizeof(i64)==4 );
52581 assert( sizeof(u64)==8 || sizeof(u64)==4 );
52582 assert( sizeof(u32)==4 );
52583 assert( sizeof(u16)==2 );
52584 assert( sizeof(Pgno)==4 );
52586 pBt = sqlite3MallocZero( sizeof(*pBt) );
52587 if( pBt==0 ){
52588 rc = SQLITE_NOMEM;
52589 goto btree_open_out;
52591 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
52592 EXTRA_SIZE, flags, vfsFlags, pageReinit);
52593 if( rc==SQLITE_OK ){
52594 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
52595 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
52597 if( rc!=SQLITE_OK ){
52598 goto btree_open_out;
52600 pBt->openFlags = (u8)flags;
52601 pBt->db = db;
52602 sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
52603 p->pBt = pBt;
52605 pBt->pCursor = 0;
52606 pBt->pPage1 = 0;
52607 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
52608 #ifdef SQLITE_SECURE_DELETE
52609 pBt->btsFlags |= BTS_SECURE_DELETE;
52610 #endif
52611 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
52612 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
52613 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
52614 pBt->pageSize = 0;
52615 #ifndef SQLITE_OMIT_AUTOVACUUM
52616 /* If the magic name ":memory:" will create an in-memory database, then
52617 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
52618 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
52619 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
52620 ** regular file-name. In this case the auto-vacuum applies as per normal.
52622 if( zFilename && !isMemdb ){
52623 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
52624 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
52626 #endif
52627 nReserve = 0;
52628 }else{
52629 nReserve = zDbHeader[20];
52630 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52631 #ifndef SQLITE_OMIT_AUTOVACUUM
52632 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
52633 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
52634 #endif
52636 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
52637 if( rc ) goto btree_open_out;
52638 pBt->usableSize = pBt->pageSize - nReserve;
52639 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
52641 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
52642 /* Add the new BtShared object to the linked list sharable BtShareds.
52644 if( p->sharable ){
52645 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
52646 pBt->nRef = 1;
52647 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
52648 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
52649 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
52650 if( pBt->mutex==0 ){
52651 rc = SQLITE_NOMEM;
52652 db->mallocFailed = 0;
52653 goto btree_open_out;
52656 sqlite3_mutex_enter(mutexShared);
52657 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
52658 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
52659 sqlite3_mutex_leave(mutexShared);
52661 #endif
52664 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
52665 /* If the new Btree uses a sharable pBtShared, then link the new
52666 ** Btree into the list of all sharable Btrees for the same connection.
52667 ** The list is kept in ascending order by pBt address.
52669 if( p->sharable ){
52670 int i;
52671 Btree *pSib;
52672 for(i=0; i<db->nDb; i++){
52673 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
52674 while( pSib->pPrev ){ pSib = pSib->pPrev; }
52675 if( p->pBt<pSib->pBt ){
52676 p->pNext = pSib;
52677 p->pPrev = 0;
52678 pSib->pPrev = p;
52679 }else{
52680 while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
52681 pSib = pSib->pNext;
52683 p->pNext = pSib->pNext;
52684 p->pPrev = pSib;
52685 if( p->pNext ){
52686 p->pNext->pPrev = p;
52688 pSib->pNext = p;
52690 break;
52694 #endif
52695 *ppBtree = p;
52697 btree_open_out:
52698 if( rc!=SQLITE_OK ){
52699 if( pBt && pBt->pPager ){
52700 sqlite3PagerClose(pBt->pPager);
52702 sqlite3_free(pBt);
52703 sqlite3_free(p);
52704 *ppBtree = 0;
52705 }else{
52706 /* If the B-Tree was successfully opened, set the pager-cache size to the
52707 ** default value. Except, when opening on an existing shared pager-cache,
52708 ** do not change the pager-cache size.
52710 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
52711 sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
52714 if( mutexOpen ){
52715 assert( sqlite3_mutex_held(mutexOpen) );
52716 sqlite3_mutex_leave(mutexOpen);
52718 return rc;
52722 ** Decrement the BtShared.nRef counter. When it reaches zero,
52723 ** remove the BtShared structure from the sharing list. Return
52724 ** true if the BtShared.nRef counter reaches zero and return
52725 ** false if it is still positive.
52727 static int removeFromSharingList(BtShared *pBt){
52728 #ifndef SQLITE_OMIT_SHARED_CACHE
52729 MUTEX_LOGIC( sqlite3_mutex *pMaster; )
52730 BtShared *pList;
52731 int removed = 0;
52733 assert( sqlite3_mutex_notheld(pBt->mutex) );
52734 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
52735 sqlite3_mutex_enter(pMaster);
52736 pBt->nRef--;
52737 if( pBt->nRef<=0 ){
52738 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
52739 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
52740 }else{
52741 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
52742 while( ALWAYS(pList) && pList->pNext!=pBt ){
52743 pList=pList->pNext;
52745 if( ALWAYS(pList) ){
52746 pList->pNext = pBt->pNext;
52749 if( SQLITE_THREADSAFE ){
52750 sqlite3_mutex_free(pBt->mutex);
52752 removed = 1;
52754 sqlite3_mutex_leave(pMaster);
52755 return removed;
52756 #else
52757 return 1;
52758 #endif
52762 ** Make sure pBt->pTmpSpace points to an allocation of
52763 ** MX_CELL_SIZE(pBt) bytes.
52765 static void allocateTempSpace(BtShared *pBt){
52766 if( !pBt->pTmpSpace ){
52767 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
52769 /* One of the uses of pBt->pTmpSpace is to format cells before
52770 ** inserting them into a leaf page (function fillInCell()). If
52771 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
52772 ** by the various routines that manipulate binary cells. Which
52773 ** can mean that fillInCell() only initializes the first 2 or 3
52774 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
52775 ** it into a database page. This is not actually a problem, but it
52776 ** does cause a valgrind error when the 1 or 2 bytes of unitialized
52777 ** data is passed to system call write(). So to avoid this error,
52778 ** zero the first 4 bytes of temp space here. */
52779 if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
52784 ** Free the pBt->pTmpSpace allocation
52786 static void freeTempSpace(BtShared *pBt){
52787 sqlite3PageFree( pBt->pTmpSpace);
52788 pBt->pTmpSpace = 0;
52792 ** Close an open database and invalidate all cursors.
52794 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
52795 BtShared *pBt = p->pBt;
52796 BtCursor *pCur;
52798 /* Close all cursors opened via this handle. */
52799 assert( sqlite3_mutex_held(p->db->mutex) );
52800 sqlite3BtreeEnter(p);
52801 pCur = pBt->pCursor;
52802 while( pCur ){
52803 BtCursor *pTmp = pCur;
52804 pCur = pCur->pNext;
52805 if( pTmp->pBtree==p ){
52806 sqlite3BtreeCloseCursor(pTmp);
52810 /* Rollback any active transaction and free the handle structure.
52811 ** The call to sqlite3BtreeRollback() drops any table-locks held by
52812 ** this handle.
52814 sqlite3BtreeRollback(p, SQLITE_OK);
52815 sqlite3BtreeLeave(p);
52817 /* If there are still other outstanding references to the shared-btree
52818 ** structure, return now. The remainder of this procedure cleans
52819 ** up the shared-btree.
52821 assert( p->wantToLock==0 && p->locked==0 );
52822 if( !p->sharable || removeFromSharingList(pBt) ){
52823 /* The pBt is no longer on the sharing list, so we can access
52824 ** it without having to hold the mutex.
52826 ** Clean out and delete the BtShared object.
52828 assert( !pBt->pCursor );
52829 sqlite3PagerClose(pBt->pPager);
52830 if( pBt->xFreeSchema && pBt->pSchema ){
52831 pBt->xFreeSchema(pBt->pSchema);
52833 sqlite3DbFree(0, pBt->pSchema);
52834 freeTempSpace(pBt);
52835 sqlite3_free(pBt);
52838 #ifndef SQLITE_OMIT_SHARED_CACHE
52839 assert( p->wantToLock==0 );
52840 assert( p->locked==0 );
52841 if( p->pPrev ) p->pPrev->pNext = p->pNext;
52842 if( p->pNext ) p->pNext->pPrev = p->pPrev;
52843 #endif
52845 sqlite3_free(p);
52846 return SQLITE_OK;
52850 ** Change the limit on the number of pages allowed in the cache.
52852 ** The maximum number of cache pages is set to the absolute
52853 ** value of mxPage. If mxPage is negative, the pager will
52854 ** operate asynchronously - it will not stop to do fsync()s
52855 ** to insure data is written to the disk surface before
52856 ** continuing. Transactions still work if synchronous is off,
52857 ** and the database cannot be corrupted if this program
52858 ** crashes. But if the operating system crashes or there is
52859 ** an abrupt power failure when synchronous is off, the database
52860 ** could be left in an inconsistent and unrecoverable state.
52861 ** Synchronous is on by default so database corruption is not
52862 ** normally a worry.
52864 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
52865 BtShared *pBt = p->pBt;
52866 assert( sqlite3_mutex_held(p->db->mutex) );
52867 sqlite3BtreeEnter(p);
52868 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
52869 sqlite3BtreeLeave(p);
52870 return SQLITE_OK;
52874 ** Change the limit on the amount of the database file that may be
52875 ** memory mapped.
52877 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
52878 BtShared *pBt = p->pBt;
52879 assert( sqlite3_mutex_held(p->db->mutex) );
52880 sqlite3BtreeEnter(p);
52881 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
52882 sqlite3BtreeLeave(p);
52883 return SQLITE_OK;
52887 ** Change the way data is synced to disk in order to increase or decrease
52888 ** how well the database resists damage due to OS crashes and power
52889 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
52890 ** there is a high probability of damage) Level 2 is the default. There
52891 ** is a very low but non-zero probability of damage. Level 3 reduces the
52892 ** probability of damage to near zero but with a write performance reduction.
52894 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
52895 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
52896 Btree *p, /* The btree to set the safety level on */
52897 unsigned pgFlags /* Various PAGER_* flags */
52899 BtShared *pBt = p->pBt;
52900 assert( sqlite3_mutex_held(p->db->mutex) );
52901 sqlite3BtreeEnter(p);
52902 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
52903 sqlite3BtreeLeave(p);
52904 return SQLITE_OK;
52906 #endif
52909 ** Return TRUE if the given btree is set to safety level 1. In other
52910 ** words, return TRUE if no sync() occurs on the disk files.
52912 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
52913 BtShared *pBt = p->pBt;
52914 int rc;
52915 assert( sqlite3_mutex_held(p->db->mutex) );
52916 sqlite3BtreeEnter(p);
52917 assert( pBt && pBt->pPager );
52918 rc = sqlite3PagerNosync(pBt->pPager);
52919 sqlite3BtreeLeave(p);
52920 return rc;
52924 ** Change the default pages size and the number of reserved bytes per page.
52925 ** Or, if the page size has already been fixed, return SQLITE_READONLY
52926 ** without changing anything.
52928 ** The page size must be a power of 2 between 512 and 65536. If the page
52929 ** size supplied does not meet this constraint then the page size is not
52930 ** changed.
52932 ** Page sizes are constrained to be a power of two so that the region
52933 ** of the database file used for locking (beginning at PENDING_BYTE,
52934 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
52935 ** at the beginning of a page.
52937 ** If parameter nReserve is less than zero, then the number of reserved
52938 ** bytes per page is left unchanged.
52940 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
52941 ** and autovacuum mode can no longer be changed.
52943 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
52944 int rc = SQLITE_OK;
52945 BtShared *pBt = p->pBt;
52946 assert( nReserve>=-1 && nReserve<=255 );
52947 sqlite3BtreeEnter(p);
52948 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
52949 sqlite3BtreeLeave(p);
52950 return SQLITE_READONLY;
52952 if( nReserve<0 ){
52953 nReserve = pBt->pageSize - pBt->usableSize;
52955 assert( nReserve>=0 && nReserve<=255 );
52956 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
52957 ((pageSize-1)&pageSize)==0 ){
52958 assert( (pageSize & 7)==0 );
52959 assert( !pBt->pPage1 && !pBt->pCursor );
52960 pBt->pageSize = (u32)pageSize;
52961 freeTempSpace(pBt);
52963 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
52964 pBt->usableSize = pBt->pageSize - (u16)nReserve;
52965 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52966 sqlite3BtreeLeave(p);
52967 return rc;
52971 ** Return the currently defined page size
52973 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
52974 return p->pBt->pageSize;
52977 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
52979 ** This function is similar to sqlite3BtreeGetReserve(), except that it
52980 ** may only be called if it is guaranteed that the b-tree mutex is already
52981 ** held.
52983 ** This is useful in one special case in the backup API code where it is
52984 ** known that the shared b-tree mutex is held, but the mutex on the
52985 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
52986 ** were to be called, it might collide with some other operation on the
52987 ** database handle that owns *p, causing undefined behavior.
52989 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
52990 assert( sqlite3_mutex_held(p->pBt->mutex) );
52991 return p->pBt->pageSize - p->pBt->usableSize;
52993 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
52995 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
52997 ** Return the number of bytes of space at the end of every page that
52998 ** are intentually left unused. This is the "reserved" space that is
52999 ** sometimes used by extensions.
53001 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
53002 int n;
53003 sqlite3BtreeEnter(p);
53004 n = p->pBt->pageSize - p->pBt->usableSize;
53005 sqlite3BtreeLeave(p);
53006 return n;
53010 ** Set the maximum page count for a database if mxPage is positive.
53011 ** No changes are made if mxPage is 0 or negative.
53012 ** Regardless of the value of mxPage, return the maximum page count.
53014 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
53015 int n;
53016 sqlite3BtreeEnter(p);
53017 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
53018 sqlite3BtreeLeave(p);
53019 return n;
53023 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
53024 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
53025 ** setting after the change.
53027 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
53028 int b;
53029 if( p==0 ) return 0;
53030 sqlite3BtreeEnter(p);
53031 if( newFlag>=0 ){
53032 p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
53033 if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
53035 b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
53036 sqlite3BtreeLeave(p);
53037 return b;
53039 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
53042 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
53043 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
53044 ** is disabled. The default value for the auto-vacuum property is
53045 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
53047 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
53048 #ifdef SQLITE_OMIT_AUTOVACUUM
53049 return SQLITE_READONLY;
53050 #else
53051 BtShared *pBt = p->pBt;
53052 int rc = SQLITE_OK;
53053 u8 av = (u8)autoVacuum;
53055 sqlite3BtreeEnter(p);
53056 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
53057 rc = SQLITE_READONLY;
53058 }else{
53059 pBt->autoVacuum = av ?1:0;
53060 pBt->incrVacuum = av==2 ?1:0;
53062 sqlite3BtreeLeave(p);
53063 return rc;
53064 #endif
53068 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
53069 ** enabled 1 is returned. Otherwise 0.
53071 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
53072 #ifdef SQLITE_OMIT_AUTOVACUUM
53073 return BTREE_AUTOVACUUM_NONE;
53074 #else
53075 int rc;
53076 sqlite3BtreeEnter(p);
53077 rc = (
53078 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
53079 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
53080 BTREE_AUTOVACUUM_INCR
53082 sqlite3BtreeLeave(p);
53083 return rc;
53084 #endif
53089 ** Get a reference to pPage1 of the database file. This will
53090 ** also acquire a readlock on that file.
53092 ** SQLITE_OK is returned on success. If the file is not a
53093 ** well-formed database file, then SQLITE_CORRUPT is returned.
53094 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
53095 ** is returned if we run out of memory.
53097 static int lockBtree(BtShared *pBt){
53098 int rc; /* Result code from subfunctions */
53099 MemPage *pPage1; /* Page 1 of the database file */
53100 int nPage; /* Number of pages in the database */
53101 int nPageFile = 0; /* Number of pages in the database file */
53102 int nPageHeader; /* Number of pages in the database according to hdr */
53104 assert( sqlite3_mutex_held(pBt->mutex) );
53105 assert( pBt->pPage1==0 );
53106 rc = sqlite3PagerSharedLock(pBt->pPager);
53107 if( rc!=SQLITE_OK ) return rc;
53108 rc = btreeGetPage(pBt, 1, &pPage1, 0);
53109 if( rc!=SQLITE_OK ) return rc;
53111 /* Do some checking to help insure the file we opened really is
53112 ** a valid database file.
53114 nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
53115 sqlite3PagerPagecount(pBt->pPager, &nPageFile);
53116 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
53117 nPage = nPageFile;
53119 if( nPage>0 ){
53120 u32 pageSize;
53121 u32 usableSize;
53122 u8 *page1 = pPage1->aData;
53123 rc = SQLITE_NOTADB;
53124 if( memcmp(page1, zMagicHeader, 16)!=0 ){
53125 goto page1_init_failed;
53128 #ifdef SQLITE_OMIT_WAL
53129 if( page1[18]>1 ){
53130 pBt->btsFlags |= BTS_READ_ONLY;
53132 if( page1[19]>1 ){
53133 goto page1_init_failed;
53135 #else
53136 if( page1[18]>2 ){
53137 pBt->btsFlags |= BTS_READ_ONLY;
53139 if( page1[19]>2 ){
53140 goto page1_init_failed;
53143 /* If the write version is set to 2, this database should be accessed
53144 ** in WAL mode. If the log is not already open, open it now. Then
53145 ** return SQLITE_OK and return without populating BtShared.pPage1.
53146 ** The caller detects this and calls this function again. This is
53147 ** required as the version of page 1 currently in the page1 buffer
53148 ** may not be the latest version - there may be a newer one in the log
53149 ** file.
53151 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
53152 int isOpen = 0;
53153 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
53154 if( rc!=SQLITE_OK ){
53155 goto page1_init_failed;
53156 }else if( isOpen==0 ){
53157 releasePage(pPage1);
53158 return SQLITE_OK;
53160 rc = SQLITE_NOTADB;
53162 #endif
53164 /* The maximum embedded fraction must be exactly 25%. And the minimum
53165 ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
53166 ** The original design allowed these amounts to vary, but as of
53167 ** version 3.6.0, we require them to be fixed.
53169 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
53170 goto page1_init_failed;
53172 pageSize = (page1[16]<<8) | (page1[17]<<16);
53173 if( ((pageSize-1)&pageSize)!=0
53174 || pageSize>SQLITE_MAX_PAGE_SIZE
53175 || pageSize<=256
53177 goto page1_init_failed;
53179 assert( (pageSize & 7)==0 );
53180 usableSize = pageSize - page1[20];
53181 if( (u32)pageSize!=pBt->pageSize ){
53182 /* After reading the first page of the database assuming a page size
53183 ** of BtShared.pageSize, we have discovered that the page-size is
53184 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
53185 ** zero and return SQLITE_OK. The caller will call this function
53186 ** again with the correct page-size.
53188 releasePage(pPage1);
53189 pBt->usableSize = usableSize;
53190 pBt->pageSize = pageSize;
53191 freeTempSpace(pBt);
53192 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
53193 pageSize-usableSize);
53194 return rc;
53196 if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
53197 rc = SQLITE_CORRUPT_BKPT;
53198 goto page1_init_failed;
53200 if( usableSize<480 ){
53201 goto page1_init_failed;
53203 pBt->pageSize = pageSize;
53204 pBt->usableSize = usableSize;
53205 #ifndef SQLITE_OMIT_AUTOVACUUM
53206 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
53207 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
53208 #endif
53211 /* maxLocal is the maximum amount of payload to store locally for
53212 ** a cell. Make sure it is small enough so that at least minFanout
53213 ** cells can will fit on one page. We assume a 10-byte page header.
53214 ** Besides the payload, the cell must store:
53215 ** 2-byte pointer to the cell
53216 ** 4-byte child pointer
53217 ** 9-byte nKey value
53218 ** 4-byte nData value
53219 ** 4-byte overflow page pointer
53220 ** So a cell consists of a 2-byte pointer, a header which is as much as
53221 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
53222 ** page pointer.
53224 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
53225 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
53226 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
53227 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
53228 if( pBt->maxLocal>127 ){
53229 pBt->max1bytePayload = 127;
53230 }else{
53231 pBt->max1bytePayload = (u8)pBt->maxLocal;
53233 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
53234 pBt->pPage1 = pPage1;
53235 pBt->nPage = nPage;
53236 return SQLITE_OK;
53238 page1_init_failed:
53239 releasePage(pPage1);
53240 pBt->pPage1 = 0;
53241 return rc;
53244 #ifndef NDEBUG
53246 ** Return the number of cursors open on pBt. This is for use
53247 ** in assert() expressions, so it is only compiled if NDEBUG is not
53248 ** defined.
53250 ** Only write cursors are counted if wrOnly is true. If wrOnly is
53251 ** false then all cursors are counted.
53253 ** For the purposes of this routine, a cursor is any cursor that
53254 ** is capable of reading or writing to the databse. Cursors that
53255 ** have been tripped into the CURSOR_FAULT state are not counted.
53257 static int countValidCursors(BtShared *pBt, int wrOnly){
53258 BtCursor *pCur;
53259 int r = 0;
53260 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
53261 if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
53263 return r;
53265 #endif
53268 ** If there are no outstanding cursors and we are not in the middle
53269 ** of a transaction but there is a read lock on the database, then
53270 ** this routine unrefs the first page of the database file which
53271 ** has the effect of releasing the read lock.
53273 ** If there is a transaction in progress, this routine is a no-op.
53275 static void unlockBtreeIfUnused(BtShared *pBt){
53276 assert( sqlite3_mutex_held(pBt->mutex) );
53277 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
53278 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
53279 assert( pBt->pPage1->aData );
53280 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
53281 assert( pBt->pPage1->aData );
53282 releasePage(pBt->pPage1);
53283 pBt->pPage1 = 0;
53288 ** If pBt points to an empty file then convert that empty file
53289 ** into a new empty database by initializing the first page of
53290 ** the database.
53292 static int newDatabase(BtShared *pBt){
53293 MemPage *pP1;
53294 unsigned char *data;
53295 int rc;
53297 assert( sqlite3_mutex_held(pBt->mutex) );
53298 if( pBt->nPage>0 ){
53299 return SQLITE_OK;
53301 pP1 = pBt->pPage1;
53302 assert( pP1!=0 );
53303 data = pP1->aData;
53304 rc = sqlite3PagerWrite(pP1->pDbPage);
53305 if( rc ) return rc;
53306 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
53307 assert( sizeof(zMagicHeader)==16 );
53308 data[16] = (u8)((pBt->pageSize>>8)&0xff);
53309 data[17] = (u8)((pBt->pageSize>>16)&0xff);
53310 data[18] = 1;
53311 data[19] = 1;
53312 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
53313 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
53314 data[21] = 64;
53315 data[22] = 32;
53316 data[23] = 32;
53317 memset(&data[24], 0, 100-24);
53318 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
53319 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
53320 #ifndef SQLITE_OMIT_AUTOVACUUM
53321 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
53322 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
53323 put4byte(&data[36 + 4*4], pBt->autoVacuum);
53324 put4byte(&data[36 + 7*4], pBt->incrVacuum);
53325 #endif
53326 pBt->nPage = 1;
53327 data[31] = 1;
53328 return SQLITE_OK;
53332 ** Initialize the first page of the database file (creating a database
53333 ** consisting of a single page and no schema objects). Return SQLITE_OK
53334 ** if successful, or an SQLite error code otherwise.
53336 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
53337 int rc;
53338 sqlite3BtreeEnter(p);
53339 p->pBt->nPage = 0;
53340 rc = newDatabase(p->pBt);
53341 sqlite3BtreeLeave(p);
53342 return rc;
53346 ** Attempt to start a new transaction. A write-transaction
53347 ** is started if the second argument is nonzero, otherwise a read-
53348 ** transaction. If the second argument is 2 or more and exclusive
53349 ** transaction is started, meaning that no other process is allowed
53350 ** to access the database. A preexisting transaction may not be
53351 ** upgraded to exclusive by calling this routine a second time - the
53352 ** exclusivity flag only works for a new transaction.
53354 ** A write-transaction must be started before attempting any
53355 ** changes to the database. None of the following routines
53356 ** will work unless a transaction is started first:
53358 ** sqlite3BtreeCreateTable()
53359 ** sqlite3BtreeCreateIndex()
53360 ** sqlite3BtreeClearTable()
53361 ** sqlite3BtreeDropTable()
53362 ** sqlite3BtreeInsert()
53363 ** sqlite3BtreeDelete()
53364 ** sqlite3BtreeUpdateMeta()
53366 ** If an initial attempt to acquire the lock fails because of lock contention
53367 ** and the database was previously unlocked, then invoke the busy handler
53368 ** if there is one. But if there was previously a read-lock, do not
53369 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
53370 ** returned when there is already a read-lock in order to avoid a deadlock.
53372 ** Suppose there are two processes A and B. A has a read lock and B has
53373 ** a reserved lock. B tries to promote to exclusive but is blocked because
53374 ** of A's read lock. A tries to promote to reserved but is blocked by B.
53375 ** One or the other of the two processes must give way or there can be
53376 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
53377 ** when A already has a read lock, we encourage A to give up and let B
53378 ** proceed.
53380 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
53381 sqlite3 *pBlock = 0;
53382 BtShared *pBt = p->pBt;
53383 int rc = SQLITE_OK;
53385 sqlite3BtreeEnter(p);
53386 btreeIntegrity(p);
53388 /* If the btree is already in a write-transaction, or it
53389 ** is already in a read-transaction and a read-transaction
53390 ** is requested, this is a no-op.
53392 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
53393 goto trans_begun;
53395 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
53397 /* Write transactions are not possible on a read-only database */
53398 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
53399 rc = SQLITE_READONLY;
53400 goto trans_begun;
53403 #ifndef SQLITE_OMIT_SHARED_CACHE
53404 /* If another database handle has already opened a write transaction
53405 ** on this shared-btree structure and a second write transaction is
53406 ** requested, return SQLITE_LOCKED.
53408 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
53409 || (pBt->btsFlags & BTS_PENDING)!=0
53411 pBlock = pBt->pWriter->db;
53412 }else if( wrflag>1 ){
53413 BtLock *pIter;
53414 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
53415 if( pIter->pBtree!=p ){
53416 pBlock = pIter->pBtree->db;
53417 break;
53421 if( pBlock ){
53422 sqlite3ConnectionBlocked(p->db, pBlock);
53423 rc = SQLITE_LOCKED_SHAREDCACHE;
53424 goto trans_begun;
53426 #endif
53428 /* Any read-only or read-write transaction implies a read-lock on
53429 ** page 1. So if some other shared-cache client already has a write-lock
53430 ** on page 1, the transaction cannot be opened. */
53431 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
53432 if( SQLITE_OK!=rc ) goto trans_begun;
53434 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
53435 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
53436 do {
53437 /* Call lockBtree() until either pBt->pPage1 is populated or
53438 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
53439 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
53440 ** reading page 1 it discovers that the page-size of the database
53441 ** file is not pBt->pageSize. In this case lockBtree() will update
53442 ** pBt->pageSize to the page-size of the file on disk.
53444 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
53446 if( rc==SQLITE_OK && wrflag ){
53447 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
53448 rc = SQLITE_READONLY;
53449 }else{
53450 rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
53451 if( rc==SQLITE_OK ){
53452 rc = newDatabase(pBt);
53457 if( rc!=SQLITE_OK ){
53458 unlockBtreeIfUnused(pBt);
53460 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
53461 btreeInvokeBusyHandler(pBt) );
53463 if( rc==SQLITE_OK ){
53464 if( p->inTrans==TRANS_NONE ){
53465 pBt->nTransaction++;
53466 #ifndef SQLITE_OMIT_SHARED_CACHE
53467 if( p->sharable ){
53468 assert( p->lock.pBtree==p && p->lock.iTable==1 );
53469 p->lock.eLock = READ_LOCK;
53470 p->lock.pNext = pBt->pLock;
53471 pBt->pLock = &p->lock;
53473 #endif
53475 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
53476 if( p->inTrans>pBt->inTransaction ){
53477 pBt->inTransaction = p->inTrans;
53479 if( wrflag ){
53480 MemPage *pPage1 = pBt->pPage1;
53481 #ifndef SQLITE_OMIT_SHARED_CACHE
53482 assert( !pBt->pWriter );
53483 pBt->pWriter = p;
53484 pBt->btsFlags &= ~BTS_EXCLUSIVE;
53485 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
53486 #endif
53488 /* If the db-size header field is incorrect (as it may be if an old
53489 ** client has been writing the database file), update it now. Doing
53490 ** this sooner rather than later means the database size can safely
53491 ** re-read the database size from page 1 if a savepoint or transaction
53492 ** rollback occurs within the transaction.
53494 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
53495 rc = sqlite3PagerWrite(pPage1->pDbPage);
53496 if( rc==SQLITE_OK ){
53497 put4byte(&pPage1->aData[28], pBt->nPage);
53504 trans_begun:
53505 if( rc==SQLITE_OK && wrflag ){
53506 /* This call makes sure that the pager has the correct number of
53507 ** open savepoints. If the second parameter is greater than 0 and
53508 ** the sub-journal is not already open, then it will be opened here.
53510 rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
53513 btreeIntegrity(p);
53514 sqlite3BtreeLeave(p);
53515 return rc;
53518 #ifndef SQLITE_OMIT_AUTOVACUUM
53521 ** Set the pointer-map entries for all children of page pPage. Also, if
53522 ** pPage contains cells that point to overflow pages, set the pointer
53523 ** map entries for the overflow pages as well.
53525 static int setChildPtrmaps(MemPage *pPage){
53526 int i; /* Counter variable */
53527 int nCell; /* Number of cells in page pPage */
53528 int rc; /* Return code */
53529 BtShared *pBt = pPage->pBt;
53530 u8 isInitOrig = pPage->isInit;
53531 Pgno pgno = pPage->pgno;
53533 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53534 rc = btreeInitPage(pPage);
53535 if( rc!=SQLITE_OK ){
53536 goto set_child_ptrmaps_out;
53538 nCell = pPage->nCell;
53540 for(i=0; i<nCell; i++){
53541 u8 *pCell = findCell(pPage, i);
53543 ptrmapPutOvflPtr(pPage, pCell, &rc);
53545 if( !pPage->leaf ){
53546 Pgno childPgno = get4byte(pCell);
53547 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
53551 if( !pPage->leaf ){
53552 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53553 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
53556 set_child_ptrmaps_out:
53557 pPage->isInit = isInitOrig;
53558 return rc;
53562 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
53563 ** that it points to iTo. Parameter eType describes the type of pointer to
53564 ** be modified, as follows:
53566 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
53567 ** page of pPage.
53569 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
53570 ** page pointed to by one of the cells on pPage.
53572 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
53573 ** overflow page in the list.
53575 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
53576 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53577 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53578 if( eType==PTRMAP_OVERFLOW2 ){
53579 /* The pointer is always the first 4 bytes of the page in this case. */
53580 if( get4byte(pPage->aData)!=iFrom ){
53581 return SQLITE_CORRUPT_BKPT;
53583 put4byte(pPage->aData, iTo);
53584 }else{
53585 u8 isInitOrig = pPage->isInit;
53586 int i;
53587 int nCell;
53589 btreeInitPage(pPage);
53590 nCell = pPage->nCell;
53592 for(i=0; i<nCell; i++){
53593 u8 *pCell = findCell(pPage, i);
53594 if( eType==PTRMAP_OVERFLOW1 ){
53595 CellInfo info;
53596 btreeParseCellPtr(pPage, pCell, &info);
53597 if( info.iOverflow
53598 && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
53599 && iFrom==get4byte(&pCell[info.iOverflow])
53601 put4byte(&pCell[info.iOverflow], iTo);
53602 break;
53604 }else{
53605 if( get4byte(pCell)==iFrom ){
53606 put4byte(pCell, iTo);
53607 break;
53612 if( i==nCell ){
53613 if( eType!=PTRMAP_BTREE ||
53614 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
53615 return SQLITE_CORRUPT_BKPT;
53617 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
53620 pPage->isInit = isInitOrig;
53622 return SQLITE_OK;
53627 ** Move the open database page pDbPage to location iFreePage in the
53628 ** database. The pDbPage reference remains valid.
53630 ** The isCommit flag indicates that there is no need to remember that
53631 ** the journal needs to be sync()ed before database page pDbPage->pgno
53632 ** can be written to. The caller has already promised not to write to that
53633 ** page.
53635 static int relocatePage(
53636 BtShared *pBt, /* Btree */
53637 MemPage *pDbPage, /* Open page to move */
53638 u8 eType, /* Pointer map 'type' entry for pDbPage */
53639 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
53640 Pgno iFreePage, /* The location to move pDbPage to */
53641 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
53643 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
53644 Pgno iDbPage = pDbPage->pgno;
53645 Pager *pPager = pBt->pPager;
53646 int rc;
53648 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
53649 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
53650 assert( sqlite3_mutex_held(pBt->mutex) );
53651 assert( pDbPage->pBt==pBt );
53653 /* Move page iDbPage from its current location to page number iFreePage */
53654 TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
53655 iDbPage, iFreePage, iPtrPage, eType));
53656 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
53657 if( rc!=SQLITE_OK ){
53658 return rc;
53660 pDbPage->pgno = iFreePage;
53662 /* If pDbPage was a btree-page, then it may have child pages and/or cells
53663 ** that point to overflow pages. The pointer map entries for all these
53664 ** pages need to be changed.
53666 ** If pDbPage is an overflow page, then the first 4 bytes may store a
53667 ** pointer to a subsequent overflow page. If this is the case, then
53668 ** the pointer map needs to be updated for the subsequent overflow page.
53670 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
53671 rc = setChildPtrmaps(pDbPage);
53672 if( rc!=SQLITE_OK ){
53673 return rc;
53675 }else{
53676 Pgno nextOvfl = get4byte(pDbPage->aData);
53677 if( nextOvfl!=0 ){
53678 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
53679 if( rc!=SQLITE_OK ){
53680 return rc;
53685 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
53686 ** that it points at iFreePage. Also fix the pointer map entry for
53687 ** iPtrPage.
53689 if( eType!=PTRMAP_ROOTPAGE ){
53690 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
53691 if( rc!=SQLITE_OK ){
53692 return rc;
53694 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
53695 if( rc!=SQLITE_OK ){
53696 releasePage(pPtrPage);
53697 return rc;
53699 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
53700 releasePage(pPtrPage);
53701 if( rc==SQLITE_OK ){
53702 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
53705 return rc;
53708 /* Forward declaration required by incrVacuumStep(). */
53709 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
53712 ** Perform a single step of an incremental-vacuum. If successful, return
53713 ** SQLITE_OK. If there is no work to do (and therefore no point in
53714 ** calling this function again), return SQLITE_DONE. Or, if an error
53715 ** occurs, return some other error code.
53717 ** More specificly, this function attempts to re-organize the database so
53718 ** that the last page of the file currently in use is no longer in use.
53720 ** Parameter nFin is the number of pages that this database would contain
53721 ** were this function called until it returns SQLITE_DONE.
53723 ** If the bCommit parameter is non-zero, this function assumes that the
53724 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
53725 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
53726 ** operation, or false for an incremental vacuum.
53728 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
53729 Pgno nFreeList; /* Number of pages still on the free-list */
53730 int rc;
53732 assert( sqlite3_mutex_held(pBt->mutex) );
53733 assert( iLastPg>nFin );
53735 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
53736 u8 eType;
53737 Pgno iPtrPage;
53739 nFreeList = get4byte(&pBt->pPage1->aData[36]);
53740 if( nFreeList==0 ){
53741 return SQLITE_DONE;
53744 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
53745 if( rc!=SQLITE_OK ){
53746 return rc;
53748 if( eType==PTRMAP_ROOTPAGE ){
53749 return SQLITE_CORRUPT_BKPT;
53752 if( eType==PTRMAP_FREEPAGE ){
53753 if( bCommit==0 ){
53754 /* Remove the page from the files free-list. This is not required
53755 ** if bCommit is non-zero. In that case, the free-list will be
53756 ** truncated to zero after this function returns, so it doesn't
53757 ** matter if it still contains some garbage entries.
53759 Pgno iFreePg;
53760 MemPage *pFreePg;
53761 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
53762 if( rc!=SQLITE_OK ){
53763 return rc;
53765 assert( iFreePg==iLastPg );
53766 releasePage(pFreePg);
53768 } else {
53769 Pgno iFreePg; /* Index of free page to move pLastPg to */
53770 MemPage *pLastPg;
53771 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
53772 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
53774 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
53775 if( rc!=SQLITE_OK ){
53776 return rc;
53779 /* If bCommit is zero, this loop runs exactly once and page pLastPg
53780 ** is swapped with the first free page pulled off the free list.
53782 ** On the other hand, if bCommit is greater than zero, then keep
53783 ** looping until a free-page located within the first nFin pages
53784 ** of the file is found.
53786 if( bCommit==0 ){
53787 eMode = BTALLOC_LE;
53788 iNear = nFin;
53790 do {
53791 MemPage *pFreePg;
53792 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
53793 if( rc!=SQLITE_OK ){
53794 releasePage(pLastPg);
53795 return rc;
53797 releasePage(pFreePg);
53798 }while( bCommit && iFreePg>nFin );
53799 assert( iFreePg<iLastPg );
53801 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
53802 releasePage(pLastPg);
53803 if( rc!=SQLITE_OK ){
53804 return rc;
53809 if( bCommit==0 ){
53810 do {
53811 iLastPg--;
53812 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
53813 pBt->bDoTruncate = 1;
53814 pBt->nPage = iLastPg;
53816 return SQLITE_OK;
53820 ** The database opened by the first argument is an auto-vacuum database
53821 ** nOrig pages in size containing nFree free pages. Return the expected
53822 ** size of the database in pages following an auto-vacuum operation.
53824 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
53825 int nEntry; /* Number of entries on one ptrmap page */
53826 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
53827 Pgno nFin; /* Return value */
53829 nEntry = pBt->usableSize/5;
53830 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
53831 nFin = nOrig - nFree - nPtrmap;
53832 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
53833 nFin--;
53835 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
53836 nFin--;
53839 return nFin;
53843 ** A write-transaction must be opened before calling this function.
53844 ** It performs a single unit of work towards an incremental vacuum.
53846 ** If the incremental vacuum is finished after this function has run,
53847 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
53848 ** SQLITE_OK is returned. Otherwise an SQLite error code.
53850 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
53851 int rc;
53852 BtShared *pBt = p->pBt;
53854 sqlite3BtreeEnter(p);
53855 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
53856 if( !pBt->autoVacuum ){
53857 rc = SQLITE_DONE;
53858 }else{
53859 Pgno nOrig = btreePagecount(pBt);
53860 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
53861 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
53863 if( nOrig<nFin ){
53864 rc = SQLITE_CORRUPT_BKPT;
53865 }else if( nFree>0 ){
53866 rc = saveAllCursors(pBt, 0, 0);
53867 if( rc==SQLITE_OK ){
53868 invalidateAllOverflowCache(pBt);
53869 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
53871 if( rc==SQLITE_OK ){
53872 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53873 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
53875 }else{
53876 rc = SQLITE_DONE;
53879 sqlite3BtreeLeave(p);
53880 return rc;
53884 ** This routine is called prior to sqlite3PagerCommit when a transaction
53885 ** is committed for an auto-vacuum database.
53887 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
53888 ** the database file should be truncated to during the commit process.
53889 ** i.e. the database has been reorganized so that only the first *pnTrunc
53890 ** pages are in use.
53892 static int autoVacuumCommit(BtShared *pBt){
53893 int rc = SQLITE_OK;
53894 Pager *pPager = pBt->pPager;
53895 VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
53897 assert( sqlite3_mutex_held(pBt->mutex) );
53898 invalidateAllOverflowCache(pBt);
53899 assert(pBt->autoVacuum);
53900 if( !pBt->incrVacuum ){
53901 Pgno nFin; /* Number of pages in database after autovacuuming */
53902 Pgno nFree; /* Number of pages on the freelist initially */
53903 Pgno iFree; /* The next page to be freed */
53904 Pgno nOrig; /* Database size before freeing */
53906 nOrig = btreePagecount(pBt);
53907 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
53908 /* It is not possible to create a database for which the final page
53909 ** is either a pointer-map page or the pending-byte page. If one
53910 ** is encountered, this indicates corruption.
53912 return SQLITE_CORRUPT_BKPT;
53915 nFree = get4byte(&pBt->pPage1->aData[36]);
53916 nFin = finalDbSize(pBt, nOrig, nFree);
53917 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
53918 if( nFin<nOrig ){
53919 rc = saveAllCursors(pBt, 0, 0);
53921 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
53922 rc = incrVacuumStep(pBt, nFin, iFree, 1);
53924 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
53925 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53926 put4byte(&pBt->pPage1->aData[32], 0);
53927 put4byte(&pBt->pPage1->aData[36], 0);
53928 put4byte(&pBt->pPage1->aData[28], nFin);
53929 pBt->bDoTruncate = 1;
53930 pBt->nPage = nFin;
53932 if( rc!=SQLITE_OK ){
53933 sqlite3PagerRollback(pPager);
53937 assert( nRef>=sqlite3PagerRefcount(pPager) );
53938 return rc;
53941 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
53942 # define setChildPtrmaps(x) SQLITE_OK
53943 #endif
53946 ** This routine does the first phase of a two-phase commit. This routine
53947 ** causes a rollback journal to be created (if it does not already exist)
53948 ** and populated with enough information so that if a power loss occurs
53949 ** the database can be restored to its original state by playing back
53950 ** the journal. Then the contents of the journal are flushed out to
53951 ** the disk. After the journal is safely on oxide, the changes to the
53952 ** database are written into the database file and flushed to oxide.
53953 ** At the end of this call, the rollback journal still exists on the
53954 ** disk and we are still holding all locks, so the transaction has not
53955 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
53956 ** commit process.
53958 ** This call is a no-op if no write-transaction is currently active on pBt.
53960 ** Otherwise, sync the database file for the btree pBt. zMaster points to
53961 ** the name of a master journal file that should be written into the
53962 ** individual journal file, or is NULL, indicating no master journal file
53963 ** (single database transaction).
53965 ** When this is called, the master journal should already have been
53966 ** created, populated with this journal pointer and synced to disk.
53968 ** Once this is routine has returned, the only thing required to commit
53969 ** the write-transaction for this database file is to delete the journal.
53971 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
53972 int rc = SQLITE_OK;
53973 if( p->inTrans==TRANS_WRITE ){
53974 BtShared *pBt = p->pBt;
53975 sqlite3BtreeEnter(p);
53976 #ifndef SQLITE_OMIT_AUTOVACUUM
53977 if( pBt->autoVacuum ){
53978 rc = autoVacuumCommit(pBt);
53979 if( rc!=SQLITE_OK ){
53980 sqlite3BtreeLeave(p);
53981 return rc;
53984 if( pBt->bDoTruncate ){
53985 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
53987 #endif
53988 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
53989 sqlite3BtreeLeave(p);
53991 return rc;
53995 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
53996 ** at the conclusion of a transaction.
53998 static void btreeEndTransaction(Btree *p){
53999 BtShared *pBt = p->pBt;
54000 sqlite3 *db = p->db;
54001 assert( sqlite3BtreeHoldsMutex(p) );
54003 #ifndef SQLITE_OMIT_AUTOVACUUM
54004 pBt->bDoTruncate = 0;
54005 #endif
54006 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
54007 /* If there are other active statements that belong to this database
54008 ** handle, downgrade to a read-only transaction. The other statements
54009 ** may still be reading from the database. */
54010 downgradeAllSharedCacheTableLocks(p);
54011 p->inTrans = TRANS_READ;
54012 }else{
54013 /* If the handle had any kind of transaction open, decrement the
54014 ** transaction count of the shared btree. If the transaction count
54015 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
54016 ** call below will unlock the pager. */
54017 if( p->inTrans!=TRANS_NONE ){
54018 clearAllSharedCacheTableLocks(p);
54019 pBt->nTransaction--;
54020 if( 0==pBt->nTransaction ){
54021 pBt->inTransaction = TRANS_NONE;
54025 /* Set the current transaction state to TRANS_NONE and unlock the
54026 ** pager if this call closed the only read or write transaction. */
54027 p->inTrans = TRANS_NONE;
54028 unlockBtreeIfUnused(pBt);
54031 btreeIntegrity(p);
54035 ** Commit the transaction currently in progress.
54037 ** This routine implements the second phase of a 2-phase commit. The
54038 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
54039 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
54040 ** routine did all the work of writing information out to disk and flushing the
54041 ** contents so that they are written onto the disk platter. All this
54042 ** routine has to do is delete or truncate or zero the header in the
54043 ** the rollback journal (which causes the transaction to commit) and
54044 ** drop locks.
54046 ** Normally, if an error occurs while the pager layer is attempting to
54047 ** finalize the underlying journal file, this function returns an error and
54048 ** the upper layer will attempt a rollback. However, if the second argument
54049 ** is non-zero then this b-tree transaction is part of a multi-file
54050 ** transaction. In this case, the transaction has already been committed
54051 ** (by deleting a master journal file) and the caller will ignore this
54052 ** functions return code. So, even if an error occurs in the pager layer,
54053 ** reset the b-tree objects internal state to indicate that the write
54054 ** transaction has been closed. This is quite safe, as the pager will have
54055 ** transitioned to the error state.
54057 ** This will release the write lock on the database file. If there
54058 ** are no active cursors, it also releases the read lock.
54060 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
54062 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
54063 sqlite3BtreeEnter(p);
54064 btreeIntegrity(p);
54066 /* If the handle has a write-transaction open, commit the shared-btrees
54067 ** transaction and set the shared state to TRANS_READ.
54069 if( p->inTrans==TRANS_WRITE ){
54070 int rc;
54071 BtShared *pBt = p->pBt;
54072 assert( pBt->inTransaction==TRANS_WRITE );
54073 assert( pBt->nTransaction>0 );
54074 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
54075 if( rc!=SQLITE_OK && bCleanup==0 ){
54076 sqlite3BtreeLeave(p);
54077 return rc;
54079 pBt->inTransaction = TRANS_READ;
54080 btreeClearHasContent(pBt);
54083 btreeEndTransaction(p);
54084 sqlite3BtreeLeave(p);
54085 return SQLITE_OK;
54089 ** Do both phases of a commit.
54091 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
54092 int rc;
54093 sqlite3BtreeEnter(p);
54094 rc = sqlite3BtreeCommitPhaseOne(p, 0);
54095 if( rc==SQLITE_OK ){
54096 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
54098 sqlite3BtreeLeave(p);
54099 return rc;
54103 ** This routine sets the state to CURSOR_FAULT and the error
54104 ** code to errCode for every cursor on BtShared that pBtree
54105 ** references.
54107 ** Every cursor is tripped, including cursors that belong
54108 ** to other database connections that happen to be sharing
54109 ** the cache with pBtree.
54111 ** This routine gets called when a rollback occurs.
54112 ** All cursors using the same cache must be tripped
54113 ** to prevent them from trying to use the btree after
54114 ** the rollback. The rollback may have deleted tables
54115 ** or moved root pages, so it is not sufficient to
54116 ** save the state of the cursor. The cursor must be
54117 ** invalidated.
54119 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
54120 BtCursor *p;
54121 if( pBtree==0 ) return;
54122 sqlite3BtreeEnter(pBtree);
54123 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
54124 int i;
54125 sqlite3BtreeClearCursor(p);
54126 p->eState = CURSOR_FAULT;
54127 p->skipNext = errCode;
54128 for(i=0; i<=p->iPage; i++){
54129 releasePage(p->apPage[i]);
54130 p->apPage[i] = 0;
54133 sqlite3BtreeLeave(pBtree);
54137 ** Rollback the transaction in progress. All cursors will be
54138 ** invalided by this operation. Any attempt to use a cursor
54139 ** that was open at the beginning of this operation will result
54140 ** in an error.
54142 ** This will release the write lock on the database file. If there
54143 ** are no active cursors, it also releases the read lock.
54145 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
54146 int rc;
54147 BtShared *pBt = p->pBt;
54148 MemPage *pPage1;
54150 sqlite3BtreeEnter(p);
54151 if( tripCode==SQLITE_OK ){
54152 rc = tripCode = saveAllCursors(pBt, 0, 0);
54153 }else{
54154 rc = SQLITE_OK;
54156 if( tripCode ){
54157 sqlite3BtreeTripAllCursors(p, tripCode);
54159 btreeIntegrity(p);
54161 if( p->inTrans==TRANS_WRITE ){
54162 int rc2;
54164 assert( TRANS_WRITE==pBt->inTransaction );
54165 rc2 = sqlite3PagerRollback(pBt->pPager);
54166 if( rc2!=SQLITE_OK ){
54167 rc = rc2;
54170 /* The rollback may have destroyed the pPage1->aData value. So
54171 ** call btreeGetPage() on page 1 again to make
54172 ** sure pPage1->aData is set correctly. */
54173 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
54174 int nPage = get4byte(28+(u8*)pPage1->aData);
54175 testcase( nPage==0 );
54176 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
54177 testcase( pBt->nPage!=nPage );
54178 pBt->nPage = nPage;
54179 releasePage(pPage1);
54181 assert( countValidCursors(pBt, 1)==0 );
54182 pBt->inTransaction = TRANS_READ;
54183 btreeClearHasContent(pBt);
54186 btreeEndTransaction(p);
54187 sqlite3BtreeLeave(p);
54188 return rc;
54192 ** Start a statement subtransaction. The subtransaction can can be rolled
54193 ** back independently of the main transaction. You must start a transaction
54194 ** before starting a subtransaction. The subtransaction is ended automatically
54195 ** if the main transaction commits or rolls back.
54197 ** Statement subtransactions are used around individual SQL statements
54198 ** that are contained within a BEGIN...COMMIT block. If a constraint
54199 ** error occurs within the statement, the effect of that one statement
54200 ** can be rolled back without having to rollback the entire transaction.
54202 ** A statement sub-transaction is implemented as an anonymous savepoint. The
54203 ** value passed as the second parameter is the total number of savepoints,
54204 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
54205 ** are no active savepoints and no other statement-transactions open,
54206 ** iStatement is 1. This anonymous savepoint can be released or rolled back
54207 ** using the sqlite3BtreeSavepoint() function.
54209 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
54210 int rc;
54211 BtShared *pBt = p->pBt;
54212 sqlite3BtreeEnter(p);
54213 assert( p->inTrans==TRANS_WRITE );
54214 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
54215 assert( iStatement>0 );
54216 assert( iStatement>p->db->nSavepoint );
54217 assert( pBt->inTransaction==TRANS_WRITE );
54218 /* At the pager level, a statement transaction is a savepoint with
54219 ** an index greater than all savepoints created explicitly using
54220 ** SQL statements. It is illegal to open, release or rollback any
54221 ** such savepoints while the statement transaction savepoint is active.
54223 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
54224 sqlite3BtreeLeave(p);
54225 return rc;
54229 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
54230 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
54231 ** savepoint identified by parameter iSavepoint, depending on the value
54232 ** of op.
54234 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
54235 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
54236 ** contents of the entire transaction are rolled back. This is different
54237 ** from a normal transaction rollback, as no locks are released and the
54238 ** transaction remains open.
54240 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
54241 int rc = SQLITE_OK;
54242 if( p && p->inTrans==TRANS_WRITE ){
54243 BtShared *pBt = p->pBt;
54244 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
54245 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
54246 sqlite3BtreeEnter(p);
54247 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
54248 if( rc==SQLITE_OK ){
54249 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
54250 pBt->nPage = 0;
54252 rc = newDatabase(pBt);
54253 pBt->nPage = get4byte(28 + pBt->pPage1->aData);
54255 /* The database size was written into the offset 28 of the header
54256 ** when the transaction started, so we know that the value at offset
54257 ** 28 is nonzero. */
54258 assert( pBt->nPage>0 );
54260 sqlite3BtreeLeave(p);
54262 return rc;
54266 ** Create a new cursor for the BTree whose root is on the page
54267 ** iTable. If a read-only cursor is requested, it is assumed that
54268 ** the caller already has at least a read-only transaction open
54269 ** on the database already. If a write-cursor is requested, then
54270 ** the caller is assumed to have an open write transaction.
54272 ** If wrFlag==0, then the cursor can only be used for reading.
54273 ** If wrFlag==1, then the cursor can be used for reading or for
54274 ** writing if other conditions for writing are also met. These
54275 ** are the conditions that must be met in order for writing to
54276 ** be allowed:
54278 ** 1: The cursor must have been opened with wrFlag==1
54280 ** 2: Other database connections that share the same pager cache
54281 ** but which are not in the READ_UNCOMMITTED state may not have
54282 ** cursors open with wrFlag==0 on the same table. Otherwise
54283 ** the changes made by this write cursor would be visible to
54284 ** the read cursors in the other database connection.
54286 ** 3: The database must be writable (not on read-only media)
54288 ** 4: There must be an active transaction.
54290 ** No checking is done to make sure that page iTable really is the
54291 ** root page of a b-tree. If it is not, then the cursor acquired
54292 ** will not work correctly.
54294 ** It is assumed that the sqlite3BtreeCursorZero() has been called
54295 ** on pCur to initialize the memory space prior to invoking this routine.
54297 static int btreeCursor(
54298 Btree *p, /* The btree */
54299 int iTable, /* Root page of table to open */
54300 int wrFlag, /* 1 to write. 0 read-only */
54301 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
54302 BtCursor *pCur /* Space for new cursor */
54304 BtShared *pBt = p->pBt; /* Shared b-tree handle */
54306 assert( sqlite3BtreeHoldsMutex(p) );
54307 assert( wrFlag==0 || wrFlag==1 );
54309 /* The following assert statements verify that if this is a sharable
54310 ** b-tree database, the connection is holding the required table locks,
54311 ** and that no other connection has any open cursor that conflicts with
54312 ** this lock. */
54313 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
54314 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
54316 /* Assert that the caller has opened the required transaction. */
54317 assert( p->inTrans>TRANS_NONE );
54318 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
54319 assert( pBt->pPage1 && pBt->pPage1->aData );
54321 if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
54322 return SQLITE_READONLY;
54324 if( iTable==1 && btreePagecount(pBt)==0 ){
54325 assert( wrFlag==0 );
54326 iTable = 0;
54329 /* Now that no other errors can occur, finish filling in the BtCursor
54330 ** variables and link the cursor into the BtShared list. */
54331 pCur->pgnoRoot = (Pgno)iTable;
54332 pCur->iPage = -1;
54333 pCur->pKeyInfo = pKeyInfo;
54334 pCur->pBtree = p;
54335 pCur->pBt = pBt;
54336 pCur->wrFlag = (u8)wrFlag;
54337 pCur->pNext = pBt->pCursor;
54338 if( pCur->pNext ){
54339 pCur->pNext->pPrev = pCur;
54341 pBt->pCursor = pCur;
54342 pCur->eState = CURSOR_INVALID;
54343 pCur->cachedRowid = 0;
54344 return SQLITE_OK;
54346 SQLITE_PRIVATE int sqlite3BtreeCursor(
54347 Btree *p, /* The btree */
54348 int iTable, /* Root page of table to open */
54349 int wrFlag, /* 1 to write. 0 read-only */
54350 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
54351 BtCursor *pCur /* Write new cursor here */
54353 int rc;
54354 sqlite3BtreeEnter(p);
54355 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
54356 sqlite3BtreeLeave(p);
54357 return rc;
54361 ** Return the size of a BtCursor object in bytes.
54363 ** This interfaces is needed so that users of cursors can preallocate
54364 ** sufficient storage to hold a cursor. The BtCursor object is opaque
54365 ** to users so they cannot do the sizeof() themselves - they must call
54366 ** this routine.
54368 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
54369 return ROUND8(sizeof(BtCursor));
54373 ** Initialize memory that will be converted into a BtCursor object.
54375 ** The simple approach here would be to memset() the entire object
54376 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
54377 ** do not need to be zeroed and they are large, so we can save a lot
54378 ** of run-time by skipping the initialization of those elements.
54380 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
54381 memset(p, 0, offsetof(BtCursor, iPage));
54385 ** Set the cached rowid value of every cursor in the same database file
54386 ** as pCur and having the same root page number as pCur. The value is
54387 ** set to iRowid.
54389 ** Only positive rowid values are considered valid for this cache.
54390 ** The cache is initialized to zero, indicating an invalid cache.
54391 ** A btree will work fine with zero or negative rowids. We just cannot
54392 ** cache zero or negative rowids, which means tables that use zero or
54393 ** negative rowids might run a little slower. But in practice, zero
54394 ** or negative rowids are very uncommon so this should not be a problem.
54396 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
54397 BtCursor *p;
54398 for(p=pCur->pBt->pCursor; p; p=p->pNext){
54399 if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
54401 assert( pCur->cachedRowid==iRowid );
54405 ** Return the cached rowid for the given cursor. A negative or zero
54406 ** return value indicates that the rowid cache is invalid and should be
54407 ** ignored. If the rowid cache has never before been set, then a
54408 ** zero is returned.
54410 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
54411 return pCur->cachedRowid;
54415 ** Close a cursor. The read lock on the database file is released
54416 ** when the last cursor is closed.
54418 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
54419 Btree *pBtree = pCur->pBtree;
54420 if( pBtree ){
54421 int i;
54422 BtShared *pBt = pCur->pBt;
54423 sqlite3BtreeEnter(pBtree);
54424 sqlite3BtreeClearCursor(pCur);
54425 if( pCur->pPrev ){
54426 pCur->pPrev->pNext = pCur->pNext;
54427 }else{
54428 pBt->pCursor = pCur->pNext;
54430 if( pCur->pNext ){
54431 pCur->pNext->pPrev = pCur->pPrev;
54433 for(i=0; i<=pCur->iPage; i++){
54434 releasePage(pCur->apPage[i]);
54436 unlockBtreeIfUnused(pBt);
54437 invalidateOverflowCache(pCur);
54438 /* sqlite3_free(pCur); */
54439 sqlite3BtreeLeave(pBtree);
54441 return SQLITE_OK;
54445 ** Make sure the BtCursor* given in the argument has a valid
54446 ** BtCursor.info structure. If it is not already valid, call
54447 ** btreeParseCell() to fill it in.
54449 ** BtCursor.info is a cache of the information in the current cell.
54450 ** Using this cache reduces the number of calls to btreeParseCell().
54452 ** 2007-06-25: There is a bug in some versions of MSVC that cause the
54453 ** compiler to crash when getCellInfo() is implemented as a macro.
54454 ** But there is a measureable speed advantage to using the macro on gcc
54455 ** (when less compiler optimizations like -Os or -O0 are used and the
54456 ** compiler is not doing agressive inlining.) So we use a real function
54457 ** for MSVC and a macro for everything else. Ticket #2457.
54459 #ifndef NDEBUG
54460 static void assertCellInfo(BtCursor *pCur){
54461 CellInfo info;
54462 int iPage = pCur->iPage;
54463 memset(&info, 0, sizeof(info));
54464 btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
54465 assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
54467 #else
54468 #define assertCellInfo(x)
54469 #endif
54470 #ifdef _MSC_VER
54471 /* Use a real function in MSVC to work around bugs in that compiler. */
54472 static void getCellInfo(BtCursor *pCur){
54473 if( pCur->info.nSize==0 ){
54474 int iPage = pCur->iPage;
54475 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
54476 pCur->validNKey = 1;
54477 }else{
54478 assertCellInfo(pCur);
54481 #else /* if not _MSC_VER */
54482 /* Use a macro in all other compilers so that the function is inlined */
54483 #define getCellInfo(pCur) \
54484 if( pCur->info.nSize==0 ){ \
54485 int iPage = pCur->iPage; \
54486 btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
54487 pCur->validNKey = 1; \
54488 }else{ \
54489 assertCellInfo(pCur); \
54491 #endif /* _MSC_VER */
54493 #ifndef NDEBUG /* The next routine used only within assert() statements */
54495 ** Return true if the given BtCursor is valid. A valid cursor is one
54496 ** that is currently pointing to a row in a (non-empty) table.
54497 ** This is a verification routine is used only within assert() statements.
54499 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
54500 return pCur && pCur->eState==CURSOR_VALID;
54502 #endif /* NDEBUG */
54505 ** Set *pSize to the size of the buffer needed to hold the value of
54506 ** the key for the current entry. If the cursor is not pointing
54507 ** to a valid entry, *pSize is set to 0.
54509 ** For a table with the INTKEY flag set, this routine returns the key
54510 ** itself, not the number of bytes in the key.
54512 ** The caller must position the cursor prior to invoking this routine.
54514 ** This routine cannot fail. It always returns SQLITE_OK.
54516 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
54517 assert( cursorHoldsMutex(pCur) );
54518 assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
54519 if( pCur->eState!=CURSOR_VALID ){
54520 *pSize = 0;
54521 }else{
54522 getCellInfo(pCur);
54523 *pSize = pCur->info.nKey;
54525 return SQLITE_OK;
54529 ** Set *pSize to the number of bytes of data in the entry the
54530 ** cursor currently points to.
54532 ** The caller must guarantee that the cursor is pointing to a non-NULL
54533 ** valid entry. In other words, the calling procedure must guarantee
54534 ** that the cursor has Cursor.eState==CURSOR_VALID.
54536 ** Failure is not possible. This function always returns SQLITE_OK.
54537 ** It might just as well be a procedure (returning void) but we continue
54538 ** to return an integer result code for historical reasons.
54540 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
54541 assert( cursorHoldsMutex(pCur) );
54542 assert( pCur->eState==CURSOR_VALID );
54543 getCellInfo(pCur);
54544 *pSize = pCur->info.nData;
54545 return SQLITE_OK;
54549 ** Given the page number of an overflow page in the database (parameter
54550 ** ovfl), this function finds the page number of the next page in the
54551 ** linked list of overflow pages. If possible, it uses the auto-vacuum
54552 ** pointer-map data instead of reading the content of page ovfl to do so.
54554 ** If an error occurs an SQLite error code is returned. Otherwise:
54556 ** The page number of the next overflow page in the linked list is
54557 ** written to *pPgnoNext. If page ovfl is the last page in its linked
54558 ** list, *pPgnoNext is set to zero.
54560 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
54561 ** to page number pOvfl was obtained, then *ppPage is set to point to that
54562 ** reference. It is the responsibility of the caller to call releasePage()
54563 ** on *ppPage to free the reference. In no reference was obtained (because
54564 ** the pointer-map was used to obtain the value for *pPgnoNext), then
54565 ** *ppPage is set to zero.
54567 static int getOverflowPage(
54568 BtShared *pBt, /* The database file */
54569 Pgno ovfl, /* Current overflow page number */
54570 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
54571 Pgno *pPgnoNext /* OUT: Next overflow page number */
54573 Pgno next = 0;
54574 MemPage *pPage = 0;
54575 int rc = SQLITE_OK;
54577 assert( sqlite3_mutex_held(pBt->mutex) );
54578 assert(pPgnoNext);
54580 #ifndef SQLITE_OMIT_AUTOVACUUM
54581 /* Try to find the next page in the overflow list using the
54582 ** autovacuum pointer-map pages. Guess that the next page in
54583 ** the overflow list is page number (ovfl+1). If that guess turns
54584 ** out to be wrong, fall back to loading the data of page
54585 ** number ovfl to determine the next page number.
54587 if( pBt->autoVacuum ){
54588 Pgno pgno;
54589 Pgno iGuess = ovfl+1;
54590 u8 eType;
54592 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
54593 iGuess++;
54596 if( iGuess<=btreePagecount(pBt) ){
54597 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
54598 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
54599 next = iGuess;
54600 rc = SQLITE_DONE;
54604 #endif
54606 assert( next==0 || rc==SQLITE_DONE );
54607 if( rc==SQLITE_OK ){
54608 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
54609 assert( rc==SQLITE_OK || pPage==0 );
54610 if( rc==SQLITE_OK ){
54611 next = get4byte(pPage->aData);
54615 *pPgnoNext = next;
54616 if( ppPage ){
54617 *ppPage = pPage;
54618 }else{
54619 releasePage(pPage);
54621 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
54625 ** Copy data from a buffer to a page, or from a page to a buffer.
54627 ** pPayload is a pointer to data stored on database page pDbPage.
54628 ** If argument eOp is false, then nByte bytes of data are copied
54629 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
54630 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
54631 ** of data are copied from the buffer pBuf to pPayload.
54633 ** SQLITE_OK is returned on success, otherwise an error code.
54635 static int copyPayload(
54636 void *pPayload, /* Pointer to page data */
54637 void *pBuf, /* Pointer to buffer */
54638 int nByte, /* Number of bytes to copy */
54639 int eOp, /* 0 -> copy from page, 1 -> copy to page */
54640 DbPage *pDbPage /* Page containing pPayload */
54642 if( eOp ){
54643 /* Copy data from buffer to page (a write operation) */
54644 int rc = sqlite3PagerWrite(pDbPage);
54645 if( rc!=SQLITE_OK ){
54646 return rc;
54648 memcpy(pPayload, pBuf, nByte);
54649 }else{
54650 /* Copy data from page to buffer (a read operation) */
54651 memcpy(pBuf, pPayload, nByte);
54653 return SQLITE_OK;
54657 ** This function is used to read or overwrite payload information
54658 ** for the entry that the pCur cursor is pointing to. If the eOp
54659 ** parameter is 0, this is a read operation (data copied into
54660 ** buffer pBuf). If it is non-zero, a write (data copied from
54661 ** buffer pBuf).
54663 ** A total of "amt" bytes are read or written beginning at "offset".
54664 ** Data is read to or from the buffer pBuf.
54666 ** The content being read or written might appear on the main page
54667 ** or be scattered out on multiple overflow pages.
54669 ** If the BtCursor.isIncrblobHandle flag is set, and the current
54670 ** cursor entry uses one or more overflow pages, this function
54671 ** allocates space for and lazily popluates the overflow page-list
54672 ** cache array (BtCursor.aOverflow). Subsequent calls use this
54673 ** cache to make seeking to the supplied offset more efficient.
54675 ** Once an overflow page-list cache has been allocated, it may be
54676 ** invalidated if some other cursor writes to the same table, or if
54677 ** the cursor is moved to a different row. Additionally, in auto-vacuum
54678 ** mode, the following events may invalidate an overflow page-list cache.
54680 ** * An incremental vacuum,
54681 ** * A commit in auto_vacuum="full" mode,
54682 ** * Creating a table (may require moving an overflow page).
54684 static int accessPayload(
54685 BtCursor *pCur, /* Cursor pointing to entry to read from */
54686 u32 offset, /* Begin reading this far into payload */
54687 u32 amt, /* Read this many bytes */
54688 unsigned char *pBuf, /* Write the bytes into this buffer */
54689 int eOp /* zero to read. non-zero to write. */
54691 unsigned char *aPayload;
54692 int rc = SQLITE_OK;
54693 u32 nKey;
54694 int iIdx = 0;
54695 MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
54696 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
54698 assert( pPage );
54699 assert( pCur->eState==CURSOR_VALID );
54700 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54701 assert( cursorHoldsMutex(pCur) );
54703 getCellInfo(pCur);
54704 aPayload = pCur->info.pCell + pCur->info.nHeader;
54705 nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
54707 if( NEVER(offset+amt > nKey+pCur->info.nData)
54708 || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
54710 /* Trying to read or write past the end of the data is an error */
54711 return SQLITE_CORRUPT_BKPT;
54714 /* Check if data must be read/written to/from the btree page itself. */
54715 if( offset<pCur->info.nLocal ){
54716 int a = amt;
54717 if( a+offset>pCur->info.nLocal ){
54718 a = pCur->info.nLocal - offset;
54720 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
54721 offset = 0;
54722 pBuf += a;
54723 amt -= a;
54724 }else{
54725 offset -= pCur->info.nLocal;
54728 if( rc==SQLITE_OK && amt>0 ){
54729 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
54730 Pgno nextPage;
54732 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
54734 #ifndef SQLITE_OMIT_INCRBLOB
54735 /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
54736 ** has not been allocated, allocate it now. The array is sized at
54737 ** one entry for each overflow page in the overflow chain. The
54738 ** page number of the first overflow page is stored in aOverflow[0],
54739 ** etc. A value of 0 in the aOverflow[] array means "not yet known"
54740 ** (the cache is lazily populated).
54742 if( pCur->isIncrblobHandle && !pCur->aOverflow ){
54743 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
54744 pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
54745 /* nOvfl is always positive. If it were zero, fetchPayload would have
54746 ** been used instead of this routine. */
54747 if( ALWAYS(nOvfl) && !pCur->aOverflow ){
54748 rc = SQLITE_NOMEM;
54752 /* If the overflow page-list cache has been allocated and the
54753 ** entry for the first required overflow page is valid, skip
54754 ** directly to it.
54756 if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
54757 iIdx = (offset/ovflSize);
54758 nextPage = pCur->aOverflow[iIdx];
54759 offset = (offset%ovflSize);
54761 #endif
54763 for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
54765 #ifndef SQLITE_OMIT_INCRBLOB
54766 /* If required, populate the overflow page-list cache. */
54767 if( pCur->aOverflow ){
54768 assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
54769 pCur->aOverflow[iIdx] = nextPage;
54771 #endif
54773 if( offset>=ovflSize ){
54774 /* The only reason to read this page is to obtain the page
54775 ** number for the next page in the overflow chain. The page
54776 ** data is not required. So first try to lookup the overflow
54777 ** page-list cache, if any, then fall back to the getOverflowPage()
54778 ** function.
54780 #ifndef SQLITE_OMIT_INCRBLOB
54781 if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
54782 nextPage = pCur->aOverflow[iIdx+1];
54783 } else
54784 #endif
54785 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
54786 offset -= ovflSize;
54787 }else{
54788 /* Need to read this page properly. It contains some of the
54789 ** range of data that is being read (eOp==0) or written (eOp!=0).
54791 #ifdef SQLITE_DIRECT_OVERFLOW_READ
54792 sqlite3_file *fd;
54793 #endif
54794 int a = amt;
54795 if( a + offset > ovflSize ){
54796 a = ovflSize - offset;
54799 #ifdef SQLITE_DIRECT_OVERFLOW_READ
54800 /* If all the following are true:
54802 ** 1) this is a read operation, and
54803 ** 2) data is required from the start of this overflow page, and
54804 ** 3) the database is file-backed, and
54805 ** 4) there is no open write-transaction, and
54806 ** 5) the database is not a WAL database,
54808 ** then data can be read directly from the database file into the
54809 ** output buffer, bypassing the page-cache altogether. This speeds
54810 ** up loading large records that span many overflow pages.
54812 if( eOp==0 /* (1) */
54813 && offset==0 /* (2) */
54814 && pBt->inTransaction==TRANS_READ /* (4) */
54815 && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
54816 && pBt->pPage1->aData[19]==0x01 /* (5) */
54818 u8 aSave[4];
54819 u8 *aWrite = &pBuf[-4];
54820 memcpy(aSave, aWrite, 4);
54821 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
54822 nextPage = get4byte(aWrite);
54823 memcpy(aWrite, aSave, 4);
54824 }else
54825 #endif
54828 DbPage *pDbPage;
54829 rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
54830 (eOp==0 ? PAGER_GET_READONLY : 0)
54832 if( rc==SQLITE_OK ){
54833 aPayload = sqlite3PagerGetData(pDbPage);
54834 nextPage = get4byte(aPayload);
54835 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
54836 sqlite3PagerUnref(pDbPage);
54837 offset = 0;
54840 amt -= a;
54841 pBuf += a;
54846 if( rc==SQLITE_OK && amt>0 ){
54847 return SQLITE_CORRUPT_BKPT;
54849 return rc;
54853 ** Read part of the key associated with cursor pCur. Exactly
54854 ** "amt" bytes will be transfered into pBuf[]. The transfer
54855 ** begins at "offset".
54857 ** The caller must ensure that pCur is pointing to a valid row
54858 ** in the table.
54860 ** Return SQLITE_OK on success or an error code if anything goes
54861 ** wrong. An error is returned if "offset+amt" is larger than
54862 ** the available payload.
54864 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
54865 assert( cursorHoldsMutex(pCur) );
54866 assert( pCur->eState==CURSOR_VALID );
54867 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
54868 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54869 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
54873 ** Read part of the data associated with cursor pCur. Exactly
54874 ** "amt" bytes will be transfered into pBuf[]. The transfer
54875 ** begins at "offset".
54877 ** Return SQLITE_OK on success or an error code if anything goes
54878 ** wrong. An error is returned if "offset+amt" is larger than
54879 ** the available payload.
54881 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
54882 int rc;
54884 #ifndef SQLITE_OMIT_INCRBLOB
54885 if ( pCur->eState==CURSOR_INVALID ){
54886 return SQLITE_ABORT;
54888 #endif
54890 assert( cursorHoldsMutex(pCur) );
54891 rc = restoreCursorPosition(pCur);
54892 if( rc==SQLITE_OK ){
54893 assert( pCur->eState==CURSOR_VALID );
54894 assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
54895 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54896 rc = accessPayload(pCur, offset, amt, pBuf, 0);
54898 return rc;
54902 ** Return a pointer to payload information from the entry that the
54903 ** pCur cursor is pointing to. The pointer is to the beginning of
54904 ** the key if index btrees (pPage->intKey==0) and is the data for
54905 ** table btrees (pPage->intKey==1). The number of bytes of available
54906 ** key/data is written into *pAmt. If *pAmt==0, then the value
54907 ** returned will not be a valid pointer.
54909 ** This routine is an optimization. It is common for the entire key
54910 ** and data to fit on the local page and for there to be no overflow
54911 ** pages. When that is so, this routine can be used to access the
54912 ** key and data without making a copy. If the key and/or data spills
54913 ** onto overflow pages, then accessPayload() must be used to reassemble
54914 ** the key/data and copy it into a preallocated buffer.
54916 ** The pointer returned by this routine looks directly into the cached
54917 ** page of the database. The data might change or move the next time
54918 ** any btree routine is called.
54920 static const void *fetchPayload(
54921 BtCursor *pCur, /* Cursor pointing to entry to read from */
54922 u32 *pAmt /* Write the number of available bytes here */
54924 assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
54925 assert( pCur->eState==CURSOR_VALID );
54926 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54927 assert( cursorHoldsMutex(pCur) );
54928 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54929 if( pCur->info.nSize==0 ){
54930 btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
54931 &pCur->info);
54933 *pAmt = pCur->info.nLocal;
54934 return (void*)(pCur->info.pCell + pCur->info.nHeader);
54939 ** For the entry that cursor pCur is point to, return as
54940 ** many bytes of the key or data as are available on the local
54941 ** b-tree page. Write the number of available bytes into *pAmt.
54943 ** The pointer returned is ephemeral. The key/data may move
54944 ** or be destroyed on the next call to any Btree routine,
54945 ** including calls from other threads against the same cache.
54946 ** Hence, a mutex on the BtShared should be held prior to calling
54947 ** this routine.
54949 ** These routines is used to get quick access to key and data
54950 ** in the common case where no overflow pages are used.
54952 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
54953 return fetchPayload(pCur, pAmt);
54955 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
54956 return fetchPayload(pCur, pAmt);
54961 ** Move the cursor down to a new child page. The newPgno argument is the
54962 ** page number of the child page to move to.
54964 ** This function returns SQLITE_CORRUPT if the page-header flags field of
54965 ** the new child page does not match the flags field of the parent (i.e.
54966 ** if an intkey page appears to be the parent of a non-intkey page, or
54967 ** vice-versa).
54969 static int moveToChild(BtCursor *pCur, u32 newPgno){
54970 int rc;
54971 int i = pCur->iPage;
54972 MemPage *pNewPage;
54973 BtShared *pBt = pCur->pBt;
54975 assert( cursorHoldsMutex(pCur) );
54976 assert( pCur->eState==CURSOR_VALID );
54977 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
54978 assert( pCur->iPage>=0 );
54979 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
54980 return SQLITE_CORRUPT_BKPT;
54982 rc = getAndInitPage(pBt, newPgno, &pNewPage,
54983 pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
54984 if( rc ) return rc;
54985 pCur->apPage[i+1] = pNewPage;
54986 pCur->aiIdx[i+1] = 0;
54987 pCur->iPage++;
54989 pCur->info.nSize = 0;
54990 pCur->validNKey = 0;
54991 if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
54992 return SQLITE_CORRUPT_BKPT;
54994 return SQLITE_OK;
54997 #if 0
54999 ** Page pParent is an internal (non-leaf) tree page. This function
55000 ** asserts that page number iChild is the left-child if the iIdx'th
55001 ** cell in page pParent. Or, if iIdx is equal to the total number of
55002 ** cells in pParent, that page number iChild is the right-child of
55003 ** the page.
55005 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
55006 assert( iIdx<=pParent->nCell );
55007 if( iIdx==pParent->nCell ){
55008 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
55009 }else{
55010 assert( get4byte(findCell(pParent, iIdx))==iChild );
55013 #else
55014 # define assertParentIndex(x,y,z)
55015 #endif
55018 ** Move the cursor up to the parent page.
55020 ** pCur->idx is set to the cell index that contains the pointer
55021 ** to the page we are coming from. If we are coming from the
55022 ** right-most child page then pCur->idx is set to one more than
55023 ** the largest cell index.
55025 static void moveToParent(BtCursor *pCur){
55026 assert( cursorHoldsMutex(pCur) );
55027 assert( pCur->eState==CURSOR_VALID );
55028 assert( pCur->iPage>0 );
55029 assert( pCur->apPage[pCur->iPage] );
55031 /* UPDATE: It is actually possible for the condition tested by the assert
55032 ** below to be untrue if the database file is corrupt. This can occur if
55033 ** one cursor has modified page pParent while a reference to it is held
55034 ** by a second cursor. Which can only happen if a single page is linked
55035 ** into more than one b-tree structure in a corrupt database. */
55036 #if 0
55037 assertParentIndex(
55038 pCur->apPage[pCur->iPage-1],
55039 pCur->aiIdx[pCur->iPage-1],
55040 pCur->apPage[pCur->iPage]->pgno
55042 #endif
55043 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
55045 releasePage(pCur->apPage[pCur->iPage]);
55046 pCur->iPage--;
55047 pCur->info.nSize = 0;
55048 pCur->validNKey = 0;
55052 ** Move the cursor to point to the root page of its b-tree structure.
55054 ** If the table has a virtual root page, then the cursor is moved to point
55055 ** to the virtual root page instead of the actual root page. A table has a
55056 ** virtual root page when the actual root page contains no cells and a
55057 ** single child page. This can only happen with the table rooted at page 1.
55059 ** If the b-tree structure is empty, the cursor state is set to
55060 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
55061 ** cell located on the root (or virtual root) page and the cursor state
55062 ** is set to CURSOR_VALID.
55064 ** If this function returns successfully, it may be assumed that the
55065 ** page-header flags indicate that the [virtual] root-page is the expected
55066 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
55067 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
55068 ** indicating a table b-tree, or if the caller did specify a KeyInfo
55069 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
55070 ** b-tree).
55072 static int moveToRoot(BtCursor *pCur){
55073 MemPage *pRoot;
55074 int rc = SQLITE_OK;
55076 assert( cursorHoldsMutex(pCur) );
55077 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
55078 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
55079 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
55080 if( pCur->eState>=CURSOR_REQUIRESEEK ){
55081 if( pCur->eState==CURSOR_FAULT ){
55082 assert( pCur->skipNext!=SQLITE_OK );
55083 return pCur->skipNext;
55085 sqlite3BtreeClearCursor(pCur);
55088 if( pCur->iPage>=0 ){
55089 while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
55090 }else if( pCur->pgnoRoot==0 ){
55091 pCur->eState = CURSOR_INVALID;
55092 return SQLITE_OK;
55093 }else{
55094 rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
55095 pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
55096 if( rc!=SQLITE_OK ){
55097 pCur->eState = CURSOR_INVALID;
55098 return rc;
55100 pCur->iPage = 0;
55102 pRoot = pCur->apPage[0];
55103 assert( pRoot->pgno==pCur->pgnoRoot );
55105 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
55106 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
55107 ** NULL, the caller expects a table b-tree. If this is not the case,
55108 ** return an SQLITE_CORRUPT error.
55110 ** Earlier versions of SQLite assumed that this test could not fail
55111 ** if the root page was already loaded when this function was called (i.e.
55112 ** if pCur->iPage>=0). But this is not so if the database is corrupted
55113 ** in such a way that page pRoot is linked into a second b-tree table
55114 ** (or the freelist). */
55115 assert( pRoot->intKey==1 || pRoot->intKey==0 );
55116 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
55117 return SQLITE_CORRUPT_BKPT;
55120 pCur->aiIdx[0] = 0;
55121 pCur->info.nSize = 0;
55122 pCur->atLast = 0;
55123 pCur->validNKey = 0;
55125 if( pRoot->nCell>0 ){
55126 pCur->eState = CURSOR_VALID;
55127 }else if( !pRoot->leaf ){
55128 Pgno subpage;
55129 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
55130 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
55131 pCur->eState = CURSOR_VALID;
55132 rc = moveToChild(pCur, subpage);
55133 }else{
55134 pCur->eState = CURSOR_INVALID;
55136 return rc;
55140 ** Move the cursor down to the left-most leaf entry beneath the
55141 ** entry to which it is currently pointing.
55143 ** The left-most leaf is the one with the smallest key - the first
55144 ** in ascending order.
55146 static int moveToLeftmost(BtCursor *pCur){
55147 Pgno pgno;
55148 int rc = SQLITE_OK;
55149 MemPage *pPage;
55151 assert( cursorHoldsMutex(pCur) );
55152 assert( pCur->eState==CURSOR_VALID );
55153 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
55154 assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
55155 pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
55156 rc = moveToChild(pCur, pgno);
55158 return rc;
55162 ** Move the cursor down to the right-most leaf entry beneath the
55163 ** page to which it is currently pointing. Notice the difference
55164 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
55165 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
55166 ** finds the right-most entry beneath the *page*.
55168 ** The right-most entry is the one with the largest key - the last
55169 ** key in ascending order.
55171 static int moveToRightmost(BtCursor *pCur){
55172 Pgno pgno;
55173 int rc = SQLITE_OK;
55174 MemPage *pPage = 0;
55176 assert( cursorHoldsMutex(pCur) );
55177 assert( pCur->eState==CURSOR_VALID );
55178 while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
55179 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55180 pCur->aiIdx[pCur->iPage] = pPage->nCell;
55181 rc = moveToChild(pCur, pgno);
55183 if( rc==SQLITE_OK ){
55184 pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
55185 pCur->info.nSize = 0;
55186 pCur->validNKey = 0;
55188 return rc;
55191 /* Move the cursor to the first entry in the table. Return SQLITE_OK
55192 ** on success. Set *pRes to 0 if the cursor actually points to something
55193 ** or set *pRes to 1 if the table is empty.
55195 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
55196 int rc;
55198 assert( cursorHoldsMutex(pCur) );
55199 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55200 rc = moveToRoot(pCur);
55201 if( rc==SQLITE_OK ){
55202 if( pCur->eState==CURSOR_INVALID ){
55203 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
55204 *pRes = 1;
55205 }else{
55206 assert( pCur->apPage[pCur->iPage]->nCell>0 );
55207 *pRes = 0;
55208 rc = moveToLeftmost(pCur);
55211 return rc;
55214 /* Move the cursor to the last entry in the table. Return SQLITE_OK
55215 ** on success. Set *pRes to 0 if the cursor actually points to something
55216 ** or set *pRes to 1 if the table is empty.
55218 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
55219 int rc;
55221 assert( cursorHoldsMutex(pCur) );
55222 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55224 /* If the cursor already points to the last entry, this is a no-op. */
55225 if( CURSOR_VALID==pCur->eState && pCur->atLast ){
55226 #ifdef SQLITE_DEBUG
55227 /* This block serves to assert() that the cursor really does point
55228 ** to the last entry in the b-tree. */
55229 int ii;
55230 for(ii=0; ii<pCur->iPage; ii++){
55231 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
55233 assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
55234 assert( pCur->apPage[pCur->iPage]->leaf );
55235 #endif
55236 return SQLITE_OK;
55239 rc = moveToRoot(pCur);
55240 if( rc==SQLITE_OK ){
55241 if( CURSOR_INVALID==pCur->eState ){
55242 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
55243 *pRes = 1;
55244 }else{
55245 assert( pCur->eState==CURSOR_VALID );
55246 *pRes = 0;
55247 rc = moveToRightmost(pCur);
55248 pCur->atLast = rc==SQLITE_OK ?1:0;
55251 return rc;
55254 /* Move the cursor so that it points to an entry near the key
55255 ** specified by pIdxKey or intKey. Return a success code.
55257 ** For INTKEY tables, the intKey parameter is used. pIdxKey
55258 ** must be NULL. For index tables, pIdxKey is used and intKey
55259 ** is ignored.
55261 ** If an exact match is not found, then the cursor is always
55262 ** left pointing at a leaf page which would hold the entry if it
55263 ** were present. The cursor might point to an entry that comes
55264 ** before or after the key.
55266 ** An integer is written into *pRes which is the result of
55267 ** comparing the key with the entry to which the cursor is
55268 ** pointing. The meaning of the integer written into
55269 ** *pRes is as follows:
55271 ** *pRes<0 The cursor is left pointing at an entry that
55272 ** is smaller than intKey/pIdxKey or if the table is empty
55273 ** and the cursor is therefore left point to nothing.
55275 ** *pRes==0 The cursor is left pointing at an entry that
55276 ** exactly matches intKey/pIdxKey.
55278 ** *pRes>0 The cursor is left pointing at an entry that
55279 ** is larger than intKey/pIdxKey.
55282 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
55283 BtCursor *pCur, /* The cursor to be moved */
55284 UnpackedRecord *pIdxKey, /* Unpacked index key */
55285 i64 intKey, /* The table key */
55286 int biasRight, /* If true, bias the search to the high end */
55287 int *pRes /* Write search results here */
55289 int rc;
55291 assert( cursorHoldsMutex(pCur) );
55292 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
55293 assert( pRes );
55294 assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
55296 /* If the cursor is already positioned at the point we are trying
55297 ** to move to, then just return without doing any work */
55298 if( pCur->eState==CURSOR_VALID && pCur->validNKey
55299 && pCur->apPage[0]->intKey
55301 if( pCur->info.nKey==intKey ){
55302 *pRes = 0;
55303 return SQLITE_OK;
55305 if( pCur->atLast && pCur->info.nKey<intKey ){
55306 *pRes = -1;
55307 return SQLITE_OK;
55311 rc = moveToRoot(pCur);
55312 if( rc ){
55313 return rc;
55315 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
55316 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
55317 assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
55318 if( pCur->eState==CURSOR_INVALID ){
55319 *pRes = -1;
55320 assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
55321 return SQLITE_OK;
55323 assert( pCur->apPage[0]->intKey || pIdxKey );
55324 for(;;){
55325 int lwr, upr, idx, c;
55326 Pgno chldPg;
55327 MemPage *pPage = pCur->apPage[pCur->iPage];
55328 u8 *pCell; /* Pointer to current cell in pPage */
55330 /* pPage->nCell must be greater than zero. If this is the root-page
55331 ** the cursor would have been INVALID above and this for(;;) loop
55332 ** not run. If this is not the root-page, then the moveToChild() routine
55333 ** would have already detected db corruption. Similarly, pPage must
55334 ** be the right kind (index or table) of b-tree page. Otherwise
55335 ** a moveToChild() or moveToRoot() call would have detected corruption. */
55336 assert( pPage->nCell>0 );
55337 assert( pPage->intKey==(pIdxKey==0) );
55338 lwr = 0;
55339 upr = pPage->nCell-1;
55340 assert( biasRight==0 || biasRight==1 );
55341 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
55342 pCur->aiIdx[pCur->iPage] = (u16)idx;
55343 if( pPage->intKey ){
55344 for(;;){
55345 i64 nCellKey;
55346 pCell = findCell(pPage, idx) + pPage->childPtrSize;
55347 if( pPage->hasData ){
55348 while( 0x80 <= *(pCell++) ){
55349 if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
55352 getVarint(pCell, (u64*)&nCellKey);
55353 if( nCellKey<intKey ){
55354 lwr = idx+1;
55355 if( lwr>upr ){ c = -1; break; }
55356 }else if( nCellKey>intKey ){
55357 upr = idx-1;
55358 if( lwr>upr ){ c = +1; break; }
55359 }else{
55360 assert( nCellKey==intKey );
55361 pCur->validNKey = 1;
55362 pCur->info.nKey = nCellKey;
55363 pCur->aiIdx[pCur->iPage] = (u16)idx;
55364 if( !pPage->leaf ){
55365 lwr = idx;
55366 goto moveto_next_layer;
55367 }else{
55368 *pRes = 0;
55369 rc = SQLITE_OK;
55370 goto moveto_finish;
55373 assert( lwr+upr>=0 );
55374 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
55376 }else{
55377 for(;;){
55378 int nCell;
55379 pCell = findCell(pPage, idx) + pPage->childPtrSize;
55381 /* The maximum supported page-size is 65536 bytes. This means that
55382 ** the maximum number of record bytes stored on an index B-Tree
55383 ** page is less than 16384 bytes and may be stored as a 2-byte
55384 ** varint. This information is used to attempt to avoid parsing
55385 ** the entire cell by checking for the cases where the record is
55386 ** stored entirely within the b-tree page by inspecting the first
55387 ** 2 bytes of the cell.
55389 nCell = pCell[0];
55390 if( nCell<=pPage->max1bytePayload ){
55391 /* This branch runs if the record-size field of the cell is a
55392 ** single byte varint and the record fits entirely on the main
55393 ** b-tree page. */
55394 testcase( pCell+nCell+1==pPage->aDataEnd );
55395 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
55396 }else if( !(pCell[1] & 0x80)
55397 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
55399 /* The record-size field is a 2 byte varint and the record
55400 ** fits entirely on the main b-tree page. */
55401 testcase( pCell+nCell+2==pPage->aDataEnd );
55402 c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
55403 }else{
55404 /* The record flows over onto one or more overflow pages. In
55405 ** this case the whole cell needs to be parsed, a buffer allocated
55406 ** and accessPayload() used to retrieve the record into the
55407 ** buffer before VdbeRecordCompare() can be called. */
55408 void *pCellKey;
55409 u8 * const pCellBody = pCell - pPage->childPtrSize;
55410 btreeParseCellPtr(pPage, pCellBody, &pCur->info);
55411 nCell = (int)pCur->info.nKey;
55412 pCellKey = sqlite3Malloc( nCell );
55413 if( pCellKey==0 ){
55414 rc = SQLITE_NOMEM;
55415 goto moveto_finish;
55417 pCur->aiIdx[pCur->iPage] = (u16)idx;
55418 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
55419 if( rc ){
55420 sqlite3_free(pCellKey);
55421 goto moveto_finish;
55423 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
55424 sqlite3_free(pCellKey);
55426 if( c<0 ){
55427 lwr = idx+1;
55428 }else if( c>0 ){
55429 upr = idx-1;
55430 }else{
55431 assert( c==0 );
55432 *pRes = 0;
55433 rc = SQLITE_OK;
55434 pCur->aiIdx[pCur->iPage] = (u16)idx;
55435 goto moveto_finish;
55437 if( lwr>upr ) break;
55438 assert( lwr+upr>=0 );
55439 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
55442 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
55443 assert( pPage->isInit );
55444 if( pPage->leaf ){
55445 assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
55446 pCur->aiIdx[pCur->iPage] = (u16)idx;
55447 *pRes = c;
55448 rc = SQLITE_OK;
55449 goto moveto_finish;
55451 moveto_next_layer:
55452 if( lwr>=pPage->nCell ){
55453 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55454 }else{
55455 chldPg = get4byte(findCell(pPage, lwr));
55457 pCur->aiIdx[pCur->iPage] = (u16)lwr;
55458 rc = moveToChild(pCur, chldPg);
55459 if( rc ) break;
55461 moveto_finish:
55462 pCur->info.nSize = 0;
55463 pCur->validNKey = 0;
55464 return rc;
55469 ** Return TRUE if the cursor is not pointing at an entry of the table.
55471 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
55472 ** past the last entry in the table or sqlite3BtreePrev() moves past
55473 ** the first entry. TRUE is also returned if the table is empty.
55475 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
55476 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
55477 ** have been deleted? This API will need to change to return an error code
55478 ** as well as the boolean result value.
55480 return (CURSOR_VALID!=pCur->eState);
55484 ** Advance the cursor to the next entry in the database. If
55485 ** successful then set *pRes=0. If the cursor
55486 ** was already pointing to the last entry in the database before
55487 ** this routine was called, then set *pRes=1.
55489 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
55490 int rc;
55491 int idx;
55492 MemPage *pPage;
55494 assert( cursorHoldsMutex(pCur) );
55495 assert( pRes!=0 );
55496 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
55497 if( pCur->eState!=CURSOR_VALID ){
55498 rc = restoreCursorPosition(pCur);
55499 if( rc!=SQLITE_OK ){
55500 *pRes = 0;
55501 return rc;
55503 if( CURSOR_INVALID==pCur->eState ){
55504 *pRes = 1;
55505 return SQLITE_OK;
55507 if( pCur->skipNext ){
55508 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
55509 pCur->eState = CURSOR_VALID;
55510 if( pCur->skipNext>0 ){
55511 pCur->skipNext = 0;
55512 *pRes = 0;
55513 return SQLITE_OK;
55515 pCur->skipNext = 0;
55519 pPage = pCur->apPage[pCur->iPage];
55520 idx = ++pCur->aiIdx[pCur->iPage];
55521 assert( pPage->isInit );
55523 /* If the database file is corrupt, it is possible for the value of idx
55524 ** to be invalid here. This can only occur if a second cursor modifies
55525 ** the page while cursor pCur is holding a reference to it. Which can
55526 ** only happen if the database is corrupt in such a way as to link the
55527 ** page into more than one b-tree structure. */
55528 testcase( idx>pPage->nCell );
55530 pCur->info.nSize = 0;
55531 pCur->validNKey = 0;
55532 if( idx>=pPage->nCell ){
55533 if( !pPage->leaf ){
55534 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
55535 if( rc ){
55536 *pRes = 0;
55537 return rc;
55539 rc = moveToLeftmost(pCur);
55540 *pRes = 0;
55541 return rc;
55544 if( pCur->iPage==0 ){
55545 *pRes = 1;
55546 pCur->eState = CURSOR_INVALID;
55547 return SQLITE_OK;
55549 moveToParent(pCur);
55550 pPage = pCur->apPage[pCur->iPage];
55551 }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
55552 *pRes = 0;
55553 if( pPage->intKey ){
55554 rc = sqlite3BtreeNext(pCur, pRes);
55555 }else{
55556 rc = SQLITE_OK;
55558 return rc;
55560 *pRes = 0;
55561 if( pPage->leaf ){
55562 return SQLITE_OK;
55564 rc = moveToLeftmost(pCur);
55565 return rc;
55570 ** Step the cursor to the back to the previous entry in the database. If
55571 ** successful then set *pRes=0. If the cursor
55572 ** was already pointing to the first entry in the database before
55573 ** this routine was called, then set *pRes=1.
55575 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
55576 int rc;
55577 MemPage *pPage;
55579 assert( cursorHoldsMutex(pCur) );
55580 assert( pRes!=0 );
55581 assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
55582 pCur->atLast = 0;
55583 if( pCur->eState!=CURSOR_VALID ){
55584 if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
55585 rc = btreeRestoreCursorPosition(pCur);
55586 if( rc!=SQLITE_OK ){
55587 *pRes = 0;
55588 return rc;
55591 if( CURSOR_INVALID==pCur->eState ){
55592 *pRes = 1;
55593 return SQLITE_OK;
55595 if( pCur->skipNext ){
55596 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
55597 pCur->eState = CURSOR_VALID;
55598 if( pCur->skipNext<0 ){
55599 pCur->skipNext = 0;
55600 *pRes = 0;
55601 return SQLITE_OK;
55603 pCur->skipNext = 0;
55607 pPage = pCur->apPage[pCur->iPage];
55608 assert( pPage->isInit );
55609 if( !pPage->leaf ){
55610 int idx = pCur->aiIdx[pCur->iPage];
55611 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
55612 if( rc ){
55613 *pRes = 0;
55614 return rc;
55616 rc = moveToRightmost(pCur);
55617 }else{
55618 while( pCur->aiIdx[pCur->iPage]==0 ){
55619 if( pCur->iPage==0 ){
55620 pCur->eState = CURSOR_INVALID;
55621 *pRes = 1;
55622 return SQLITE_OK;
55624 moveToParent(pCur);
55626 pCur->info.nSize = 0;
55627 pCur->validNKey = 0;
55629 pCur->aiIdx[pCur->iPage]--;
55630 pPage = pCur->apPage[pCur->iPage];
55631 if( pPage->intKey && !pPage->leaf ){
55632 rc = sqlite3BtreePrevious(pCur, pRes);
55633 }else{
55634 rc = SQLITE_OK;
55637 *pRes = 0;
55638 return rc;
55642 ** Allocate a new page from the database file.
55644 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
55645 ** has already been called on the new page.) The new page has also
55646 ** been referenced and the calling routine is responsible for calling
55647 ** sqlite3PagerUnref() on the new page when it is done.
55649 ** SQLITE_OK is returned on success. Any other return value indicates
55650 ** an error. *ppPage and *pPgno are undefined in the event of an error.
55651 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
55653 ** If the "nearby" parameter is not 0, then an effort is made to
55654 ** locate a page close to the page number "nearby". This can be used in an
55655 ** attempt to keep related pages close to each other in the database file,
55656 ** which in turn can make database access faster.
55658 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
55659 ** anywhere on the free-list, then it is guaranteed to be returned. If
55660 ** eMode is BTALLOC_LT then the page returned will be less than or equal
55661 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
55662 ** are no restrictions on which page is returned.
55664 static int allocateBtreePage(
55665 BtShared *pBt, /* The btree */
55666 MemPage **ppPage, /* Store pointer to the allocated page here */
55667 Pgno *pPgno, /* Store the page number here */
55668 Pgno nearby, /* Search for a page near this one */
55669 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
55671 MemPage *pPage1;
55672 int rc;
55673 u32 n; /* Number of pages on the freelist */
55674 u32 k; /* Number of leaves on the trunk of the freelist */
55675 MemPage *pTrunk = 0;
55676 MemPage *pPrevTrunk = 0;
55677 Pgno mxPage; /* Total size of the database file */
55679 assert( sqlite3_mutex_held(pBt->mutex) );
55680 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
55681 pPage1 = pBt->pPage1;
55682 mxPage = btreePagecount(pBt);
55683 n = get4byte(&pPage1->aData[36]);
55684 testcase( n==mxPage-1 );
55685 if( n>=mxPage ){
55686 return SQLITE_CORRUPT_BKPT;
55688 if( n>0 ){
55689 /* There are pages on the freelist. Reuse one of those pages. */
55690 Pgno iTrunk;
55691 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
55693 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
55694 ** shows that the page 'nearby' is somewhere on the free-list, then
55695 ** the entire-list will be searched for that page.
55697 #ifndef SQLITE_OMIT_AUTOVACUUM
55698 if( eMode==BTALLOC_EXACT ){
55699 if( nearby<=mxPage ){
55700 u8 eType;
55701 assert( nearby>0 );
55702 assert( pBt->autoVacuum );
55703 rc = ptrmapGet(pBt, nearby, &eType, 0);
55704 if( rc ) return rc;
55705 if( eType==PTRMAP_FREEPAGE ){
55706 searchList = 1;
55709 }else if( eMode==BTALLOC_LE ){
55710 searchList = 1;
55712 #endif
55714 /* Decrement the free-list count by 1. Set iTrunk to the index of the
55715 ** first free-list trunk page. iPrevTrunk is initially 1.
55717 rc = sqlite3PagerWrite(pPage1->pDbPage);
55718 if( rc ) return rc;
55719 put4byte(&pPage1->aData[36], n-1);
55721 /* The code within this loop is run only once if the 'searchList' variable
55722 ** is not true. Otherwise, it runs once for each trunk-page on the
55723 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
55724 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
55726 do {
55727 pPrevTrunk = pTrunk;
55728 if( pPrevTrunk ){
55729 iTrunk = get4byte(&pPrevTrunk->aData[0]);
55730 }else{
55731 iTrunk = get4byte(&pPage1->aData[32]);
55733 testcase( iTrunk==mxPage );
55734 if( iTrunk>mxPage ){
55735 rc = SQLITE_CORRUPT_BKPT;
55736 }else{
55737 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
55739 if( rc ){
55740 pTrunk = 0;
55741 goto end_allocate_page;
55743 assert( pTrunk!=0 );
55744 assert( pTrunk->aData!=0 );
55746 k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
55747 if( k==0 && !searchList ){
55748 /* The trunk has no leaves and the list is not being searched.
55749 ** So extract the trunk page itself and use it as the newly
55750 ** allocated page */
55751 assert( pPrevTrunk==0 );
55752 rc = sqlite3PagerWrite(pTrunk->pDbPage);
55753 if( rc ){
55754 goto end_allocate_page;
55756 *pPgno = iTrunk;
55757 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
55758 *ppPage = pTrunk;
55759 pTrunk = 0;
55760 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
55761 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
55762 /* Value of k is out of range. Database corruption */
55763 rc = SQLITE_CORRUPT_BKPT;
55764 goto end_allocate_page;
55765 #ifndef SQLITE_OMIT_AUTOVACUUM
55766 }else if( searchList
55767 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
55769 /* The list is being searched and this trunk page is the page
55770 ** to allocate, regardless of whether it has leaves.
55772 *pPgno = iTrunk;
55773 *ppPage = pTrunk;
55774 searchList = 0;
55775 rc = sqlite3PagerWrite(pTrunk->pDbPage);
55776 if( rc ){
55777 goto end_allocate_page;
55779 if( k==0 ){
55780 if( !pPrevTrunk ){
55781 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
55782 }else{
55783 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
55784 if( rc!=SQLITE_OK ){
55785 goto end_allocate_page;
55787 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
55789 }else{
55790 /* The trunk page is required by the caller but it contains
55791 ** pointers to free-list leaves. The first leaf becomes a trunk
55792 ** page in this case.
55794 MemPage *pNewTrunk;
55795 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
55796 if( iNewTrunk>mxPage ){
55797 rc = SQLITE_CORRUPT_BKPT;
55798 goto end_allocate_page;
55800 testcase( iNewTrunk==mxPage );
55801 rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
55802 if( rc!=SQLITE_OK ){
55803 goto end_allocate_page;
55805 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
55806 if( rc!=SQLITE_OK ){
55807 releasePage(pNewTrunk);
55808 goto end_allocate_page;
55810 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
55811 put4byte(&pNewTrunk->aData[4], k-1);
55812 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
55813 releasePage(pNewTrunk);
55814 if( !pPrevTrunk ){
55815 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
55816 put4byte(&pPage1->aData[32], iNewTrunk);
55817 }else{
55818 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
55819 if( rc ){
55820 goto end_allocate_page;
55822 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
55825 pTrunk = 0;
55826 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
55827 #endif
55828 }else if( k>0 ){
55829 /* Extract a leaf from the trunk */
55830 u32 closest;
55831 Pgno iPage;
55832 unsigned char *aData = pTrunk->aData;
55833 if( nearby>0 ){
55834 u32 i;
55835 closest = 0;
55836 if( eMode==BTALLOC_LE ){
55837 for(i=0; i<k; i++){
55838 iPage = get4byte(&aData[8+i*4]);
55839 if( iPage<=nearby ){
55840 closest = i;
55841 break;
55844 }else{
55845 int dist;
55846 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
55847 for(i=1; i<k; i++){
55848 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
55849 if( d2<dist ){
55850 closest = i;
55851 dist = d2;
55855 }else{
55856 closest = 0;
55859 iPage = get4byte(&aData[8+closest*4]);
55860 testcase( iPage==mxPage );
55861 if( iPage>mxPage ){
55862 rc = SQLITE_CORRUPT_BKPT;
55863 goto end_allocate_page;
55865 testcase( iPage==mxPage );
55866 if( !searchList
55867 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
55869 int noContent;
55870 *pPgno = iPage;
55871 TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
55872 ": %d more free pages\n",
55873 *pPgno, closest+1, k, pTrunk->pgno, n-1));
55874 rc = sqlite3PagerWrite(pTrunk->pDbPage);
55875 if( rc ) goto end_allocate_page;
55876 if( closest<k-1 ){
55877 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
55879 put4byte(&aData[4], k-1);
55880 noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
55881 rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
55882 if( rc==SQLITE_OK ){
55883 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
55884 if( rc!=SQLITE_OK ){
55885 releasePage(*ppPage);
55888 searchList = 0;
55891 releasePage(pPrevTrunk);
55892 pPrevTrunk = 0;
55893 }while( searchList );
55894 }else{
55895 /* There are no pages on the freelist, so append a new page to the
55896 ** database image.
55898 ** Normally, new pages allocated by this block can be requested from the
55899 ** pager layer with the 'no-content' flag set. This prevents the pager
55900 ** from trying to read the pages content from disk. However, if the
55901 ** current transaction has already run one or more incremental-vacuum
55902 ** steps, then the page we are about to allocate may contain content
55903 ** that is required in the event of a rollback. In this case, do
55904 ** not set the no-content flag. This causes the pager to load and journal
55905 ** the current page content before overwriting it.
55907 ** Note that the pager will not actually attempt to load or journal
55908 ** content for any page that really does lie past the end of the database
55909 ** file on disk. So the effects of disabling the no-content optimization
55910 ** here are confined to those pages that lie between the end of the
55911 ** database image and the end of the database file.
55913 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
55915 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55916 if( rc ) return rc;
55917 pBt->nPage++;
55918 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
55920 #ifndef SQLITE_OMIT_AUTOVACUUM
55921 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
55922 /* If *pPgno refers to a pointer-map page, allocate two new pages
55923 ** at the end of the file instead of one. The first allocated page
55924 ** becomes a new pointer-map page, the second is used by the caller.
55926 MemPage *pPg = 0;
55927 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
55928 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
55929 rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
55930 if( rc==SQLITE_OK ){
55931 rc = sqlite3PagerWrite(pPg->pDbPage);
55932 releasePage(pPg);
55934 if( rc ) return rc;
55935 pBt->nPage++;
55936 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
55938 #endif
55939 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
55940 *pPgno = pBt->nPage;
55942 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
55943 rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
55944 if( rc ) return rc;
55945 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
55946 if( rc!=SQLITE_OK ){
55947 releasePage(*ppPage);
55949 TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
55952 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
55954 end_allocate_page:
55955 releasePage(pTrunk);
55956 releasePage(pPrevTrunk);
55957 if( rc==SQLITE_OK ){
55958 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
55959 releasePage(*ppPage);
55960 *ppPage = 0;
55961 return SQLITE_CORRUPT_BKPT;
55963 (*ppPage)->isInit = 0;
55964 }else{
55965 *ppPage = 0;
55967 assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
55968 return rc;
55972 ** This function is used to add page iPage to the database file free-list.
55973 ** It is assumed that the page is not already a part of the free-list.
55975 ** The value passed as the second argument to this function is optional.
55976 ** If the caller happens to have a pointer to the MemPage object
55977 ** corresponding to page iPage handy, it may pass it as the second value.
55978 ** Otherwise, it may pass NULL.
55980 ** If a pointer to a MemPage object is passed as the second argument,
55981 ** its reference count is not altered by this function.
55983 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
55984 MemPage *pTrunk = 0; /* Free-list trunk page */
55985 Pgno iTrunk = 0; /* Page number of free-list trunk page */
55986 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
55987 MemPage *pPage; /* Page being freed. May be NULL. */
55988 int rc; /* Return Code */
55989 int nFree; /* Initial number of pages on free-list */
55991 assert( sqlite3_mutex_held(pBt->mutex) );
55992 assert( iPage>1 );
55993 assert( !pMemPage || pMemPage->pgno==iPage );
55995 if( pMemPage ){
55996 pPage = pMemPage;
55997 sqlite3PagerRef(pPage->pDbPage);
55998 }else{
55999 pPage = btreePageLookup(pBt, iPage);
56002 /* Increment the free page count on pPage1 */
56003 rc = sqlite3PagerWrite(pPage1->pDbPage);
56004 if( rc ) goto freepage_out;
56005 nFree = get4byte(&pPage1->aData[36]);
56006 put4byte(&pPage1->aData[36], nFree+1);
56008 if( pBt->btsFlags & BTS_SECURE_DELETE ){
56009 /* If the secure_delete option is enabled, then
56010 ** always fully overwrite deleted information with zeros.
56012 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
56013 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
56015 goto freepage_out;
56017 memset(pPage->aData, 0, pPage->pBt->pageSize);
56020 /* If the database supports auto-vacuum, write an entry in the pointer-map
56021 ** to indicate that the page is free.
56023 if( ISAUTOVACUUM ){
56024 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
56025 if( rc ) goto freepage_out;
56028 /* Now manipulate the actual database free-list structure. There are two
56029 ** possibilities. If the free-list is currently empty, or if the first
56030 ** trunk page in the free-list is full, then this page will become a
56031 ** new free-list trunk page. Otherwise, it will become a leaf of the
56032 ** first trunk page in the current free-list. This block tests if it
56033 ** is possible to add the page as a new free-list leaf.
56035 if( nFree!=0 ){
56036 u32 nLeaf; /* Initial number of leaf cells on trunk page */
56038 iTrunk = get4byte(&pPage1->aData[32]);
56039 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
56040 if( rc!=SQLITE_OK ){
56041 goto freepage_out;
56044 nLeaf = get4byte(&pTrunk->aData[4]);
56045 assert( pBt->usableSize>32 );
56046 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
56047 rc = SQLITE_CORRUPT_BKPT;
56048 goto freepage_out;
56050 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
56051 /* In this case there is room on the trunk page to insert the page
56052 ** being freed as a new leaf.
56054 ** Note that the trunk page is not really full until it contains
56055 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
56056 ** coded. But due to a coding error in versions of SQLite prior to
56057 ** 3.6.0, databases with freelist trunk pages holding more than
56058 ** usableSize/4 - 8 entries will be reported as corrupt. In order
56059 ** to maintain backwards compatibility with older versions of SQLite,
56060 ** we will continue to restrict the number of entries to usableSize/4 - 8
56061 ** for now. At some point in the future (once everyone has upgraded
56062 ** to 3.6.0 or later) we should consider fixing the conditional above
56063 ** to read "usableSize/4-2" instead of "usableSize/4-8".
56065 rc = sqlite3PagerWrite(pTrunk->pDbPage);
56066 if( rc==SQLITE_OK ){
56067 put4byte(&pTrunk->aData[4], nLeaf+1);
56068 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
56069 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
56070 sqlite3PagerDontWrite(pPage->pDbPage);
56072 rc = btreeSetHasContent(pBt, iPage);
56074 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
56075 goto freepage_out;
56079 /* If control flows to this point, then it was not possible to add the
56080 ** the page being freed as a leaf page of the first trunk in the free-list.
56081 ** Possibly because the free-list is empty, or possibly because the
56082 ** first trunk in the free-list is full. Either way, the page being freed
56083 ** will become the new first trunk page in the free-list.
56085 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
56086 goto freepage_out;
56088 rc = sqlite3PagerWrite(pPage->pDbPage);
56089 if( rc!=SQLITE_OK ){
56090 goto freepage_out;
56092 put4byte(pPage->aData, iTrunk);
56093 put4byte(&pPage->aData[4], 0);
56094 put4byte(&pPage1->aData[32], iPage);
56095 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
56097 freepage_out:
56098 if( pPage ){
56099 pPage->isInit = 0;
56101 releasePage(pPage);
56102 releasePage(pTrunk);
56103 return rc;
56105 static void freePage(MemPage *pPage, int *pRC){
56106 if( (*pRC)==SQLITE_OK ){
56107 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
56112 ** Free any overflow pages associated with the given Cell.
56114 static int clearCell(MemPage *pPage, unsigned char *pCell){
56115 BtShared *pBt = pPage->pBt;
56116 CellInfo info;
56117 Pgno ovflPgno;
56118 int rc;
56119 int nOvfl;
56120 u32 ovflPageSize;
56122 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56123 btreeParseCellPtr(pPage, pCell, &info);
56124 if( info.iOverflow==0 ){
56125 return SQLITE_OK; /* No overflow pages. Return without doing anything */
56127 if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
56128 return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
56130 ovflPgno = get4byte(&pCell[info.iOverflow]);
56131 assert( pBt->usableSize > 4 );
56132 ovflPageSize = pBt->usableSize - 4;
56133 nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
56134 assert( ovflPgno==0 || nOvfl>0 );
56135 while( nOvfl-- ){
56136 Pgno iNext = 0;
56137 MemPage *pOvfl = 0;
56138 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
56139 /* 0 is not a legal page number and page 1 cannot be an
56140 ** overflow page. Therefore if ovflPgno<2 or past the end of the
56141 ** file the database must be corrupt. */
56142 return SQLITE_CORRUPT_BKPT;
56144 if( nOvfl ){
56145 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
56146 if( rc ) return rc;
56149 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
56150 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
56152 /* There is no reason any cursor should have an outstanding reference
56153 ** to an overflow page belonging to a cell that is being deleted/updated.
56154 ** So if there exists more than one reference to this page, then it
56155 ** must not really be an overflow page and the database must be corrupt.
56156 ** It is helpful to detect this before calling freePage2(), as
56157 ** freePage2() may zero the page contents if secure-delete mode is
56158 ** enabled. If this 'overflow' page happens to be a page that the
56159 ** caller is iterating through or using in some other way, this
56160 ** can be problematic.
56162 rc = SQLITE_CORRUPT_BKPT;
56163 }else{
56164 rc = freePage2(pBt, pOvfl, ovflPgno);
56167 if( pOvfl ){
56168 sqlite3PagerUnref(pOvfl->pDbPage);
56170 if( rc ) return rc;
56171 ovflPgno = iNext;
56173 return SQLITE_OK;
56177 ** Create the byte sequence used to represent a cell on page pPage
56178 ** and write that byte sequence into pCell[]. Overflow pages are
56179 ** allocated and filled in as necessary. The calling procedure
56180 ** is responsible for making sure sufficient space has been allocated
56181 ** for pCell[].
56183 ** Note that pCell does not necessary need to point to the pPage->aData
56184 ** area. pCell might point to some temporary storage. The cell will
56185 ** be constructed in this temporary area then copied into pPage->aData
56186 ** later.
56188 static int fillInCell(
56189 MemPage *pPage, /* The page that contains the cell */
56190 unsigned char *pCell, /* Complete text of the cell */
56191 const void *pKey, i64 nKey, /* The key */
56192 const void *pData,int nData, /* The data */
56193 int nZero, /* Extra zero bytes to append to pData */
56194 int *pnSize /* Write cell size here */
56196 int nPayload;
56197 const u8 *pSrc;
56198 int nSrc, n, rc;
56199 int spaceLeft;
56200 MemPage *pOvfl = 0;
56201 MemPage *pToRelease = 0;
56202 unsigned char *pPrior;
56203 unsigned char *pPayload;
56204 BtShared *pBt = pPage->pBt;
56205 Pgno pgnoOvfl = 0;
56206 int nHeader;
56207 CellInfo info;
56209 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56211 /* pPage is not necessarily writeable since pCell might be auxiliary
56212 ** buffer space that is separate from the pPage buffer area */
56213 assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
56214 || sqlite3PagerIswriteable(pPage->pDbPage) );
56216 /* Fill in the header. */
56217 nHeader = 0;
56218 if( !pPage->leaf ){
56219 nHeader += 4;
56221 if( pPage->hasData ){
56222 nHeader += putVarint32(&pCell[nHeader], nData+nZero);
56223 }else{
56224 nData = nZero = 0;
56226 nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
56227 btreeParseCellPtr(pPage, pCell, &info);
56228 assert( info.nHeader==nHeader );
56229 assert( info.nKey==nKey );
56230 assert( info.nData==(u32)(nData+nZero) );
56232 /* Fill in the payload */
56233 nPayload = nData + nZero;
56234 if( pPage->intKey ){
56235 pSrc = pData;
56236 nSrc = nData;
56237 nData = 0;
56238 }else{
56239 if( NEVER(nKey>0x7fffffff || pKey==0) ){
56240 return SQLITE_CORRUPT_BKPT;
56242 nPayload += (int)nKey;
56243 pSrc = pKey;
56244 nSrc = (int)nKey;
56246 *pnSize = info.nSize;
56247 spaceLeft = info.nLocal;
56248 pPayload = &pCell[nHeader];
56249 pPrior = &pCell[info.iOverflow];
56251 while( nPayload>0 ){
56252 if( spaceLeft==0 ){
56253 #ifndef SQLITE_OMIT_AUTOVACUUM
56254 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
56255 if( pBt->autoVacuum ){
56257 pgnoOvfl++;
56258 } while(
56259 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
56262 #endif
56263 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
56264 #ifndef SQLITE_OMIT_AUTOVACUUM
56265 /* If the database supports auto-vacuum, and the second or subsequent
56266 ** overflow page is being allocated, add an entry to the pointer-map
56267 ** for that page now.
56269 ** If this is the first overflow page, then write a partial entry
56270 ** to the pointer-map. If we write nothing to this pointer-map slot,
56271 ** then the optimistic overflow chain processing in clearCell()
56272 ** may misinterpret the uninitialized values and delete the
56273 ** wrong pages from the database.
56275 if( pBt->autoVacuum && rc==SQLITE_OK ){
56276 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
56277 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
56278 if( rc ){
56279 releasePage(pOvfl);
56282 #endif
56283 if( rc ){
56284 releasePage(pToRelease);
56285 return rc;
56288 /* If pToRelease is not zero than pPrior points into the data area
56289 ** of pToRelease. Make sure pToRelease is still writeable. */
56290 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
56292 /* If pPrior is part of the data area of pPage, then make sure pPage
56293 ** is still writeable */
56294 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
56295 || sqlite3PagerIswriteable(pPage->pDbPage) );
56297 put4byte(pPrior, pgnoOvfl);
56298 releasePage(pToRelease);
56299 pToRelease = pOvfl;
56300 pPrior = pOvfl->aData;
56301 put4byte(pPrior, 0);
56302 pPayload = &pOvfl->aData[4];
56303 spaceLeft = pBt->usableSize - 4;
56305 n = nPayload;
56306 if( n>spaceLeft ) n = spaceLeft;
56308 /* If pToRelease is not zero than pPayload points into the data area
56309 ** of pToRelease. Make sure pToRelease is still writeable. */
56310 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
56312 /* If pPayload is part of the data area of pPage, then make sure pPage
56313 ** is still writeable */
56314 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
56315 || sqlite3PagerIswriteable(pPage->pDbPage) );
56317 if( nSrc>0 ){
56318 if( n>nSrc ) n = nSrc;
56319 assert( pSrc );
56320 memcpy(pPayload, pSrc, n);
56321 }else{
56322 memset(pPayload, 0, n);
56324 nPayload -= n;
56325 pPayload += n;
56326 pSrc += n;
56327 nSrc -= n;
56328 spaceLeft -= n;
56329 if( nSrc==0 ){
56330 nSrc = nData;
56331 pSrc = pData;
56334 releasePage(pToRelease);
56335 return SQLITE_OK;
56339 ** Remove the i-th cell from pPage. This routine effects pPage only.
56340 ** The cell content is not freed or deallocated. It is assumed that
56341 ** the cell content has been copied someplace else. This routine just
56342 ** removes the reference to the cell from pPage.
56344 ** "sz" must be the number of bytes in the cell.
56346 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
56347 u32 pc; /* Offset to cell content of cell being deleted */
56348 u8 *data; /* pPage->aData */
56349 u8 *ptr; /* Used to move bytes around within data[] */
56350 int rc; /* The return code */
56351 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
56353 if( *pRC ) return;
56355 assert( idx>=0 && idx<pPage->nCell );
56356 assert( sz==cellSize(pPage, idx) );
56357 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56358 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56359 data = pPage->aData;
56360 ptr = &pPage->aCellIdx[2*idx];
56361 pc = get2byte(ptr);
56362 hdr = pPage->hdrOffset;
56363 testcase( pc==get2byte(&data[hdr+5]) );
56364 testcase( pc+sz==pPage->pBt->usableSize );
56365 if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
56366 *pRC = SQLITE_CORRUPT_BKPT;
56367 return;
56369 rc = freeSpace(pPage, pc, sz);
56370 if( rc ){
56371 *pRC = rc;
56372 return;
56374 pPage->nCell--;
56375 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
56376 put2byte(&data[hdr+3], pPage->nCell);
56377 pPage->nFree += 2;
56381 ** Insert a new cell on pPage at cell index "i". pCell points to the
56382 ** content of the cell.
56384 ** If the cell content will fit on the page, then put it there. If it
56385 ** will not fit, then make a copy of the cell content into pTemp if
56386 ** pTemp is not null. Regardless of pTemp, allocate a new entry
56387 ** in pPage->apOvfl[] and make it point to the cell content (either
56388 ** in pTemp or the original pCell) and also record its index.
56389 ** Allocating a new entry in pPage->aCell[] implies that
56390 ** pPage->nOverflow is incremented.
56392 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
56393 ** cell. The caller will overwrite them after this function returns. If
56394 ** nSkip is non-zero, then pCell may not point to an invalid memory location
56395 ** (but pCell+nSkip is always valid).
56397 static void insertCell(
56398 MemPage *pPage, /* Page into which we are copying */
56399 int i, /* New cell becomes the i-th cell of the page */
56400 u8 *pCell, /* Content of the new cell */
56401 int sz, /* Bytes of content in pCell */
56402 u8 *pTemp, /* Temp storage space for pCell, if needed */
56403 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
56404 int *pRC /* Read and write return code from here */
56406 int idx = 0; /* Where to write new cell content in data[] */
56407 int j; /* Loop counter */
56408 int end; /* First byte past the last cell pointer in data[] */
56409 int ins; /* Index in data[] where new cell pointer is inserted */
56410 int cellOffset; /* Address of first cell pointer in data[] */
56411 u8 *data; /* The content of the whole page */
56412 int nSkip = (iChild ? 4 : 0);
56414 if( *pRC ) return;
56416 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
56417 assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
56418 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
56419 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
56420 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56421 /* The cell should normally be sized correctly. However, when moving a
56422 ** malformed cell from a leaf page to an interior page, if the cell size
56423 ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
56424 ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
56425 ** the term after the || in the following assert(). */
56426 assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
56427 if( pPage->nOverflow || sz+2>pPage->nFree ){
56428 if( pTemp ){
56429 memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
56430 pCell = pTemp;
56432 if( iChild ){
56433 put4byte(pCell, iChild);
56435 j = pPage->nOverflow++;
56436 assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
56437 pPage->apOvfl[j] = pCell;
56438 pPage->aiOvfl[j] = (u16)i;
56439 }else{
56440 int rc = sqlite3PagerWrite(pPage->pDbPage);
56441 if( rc!=SQLITE_OK ){
56442 *pRC = rc;
56443 return;
56445 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56446 data = pPage->aData;
56447 cellOffset = pPage->cellOffset;
56448 end = cellOffset + 2*pPage->nCell;
56449 ins = cellOffset + 2*i;
56450 rc = allocateSpace(pPage, sz, &idx);
56451 if( rc ){ *pRC = rc; return; }
56452 /* The allocateSpace() routine guarantees the following two properties
56453 ** if it returns success */
56454 assert( idx >= end+2 );
56455 assert( idx+sz <= (int)pPage->pBt->usableSize );
56456 pPage->nCell++;
56457 pPage->nFree -= (u16)(2 + sz);
56458 memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
56459 if( iChild ){
56460 put4byte(&data[idx], iChild);
56462 memmove(&data[ins+2], &data[ins], end-ins);
56463 put2byte(&data[ins], idx);
56464 put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
56465 #ifndef SQLITE_OMIT_AUTOVACUUM
56466 if( pPage->pBt->autoVacuum ){
56467 /* The cell may contain a pointer to an overflow page. If so, write
56468 ** the entry for the overflow page into the pointer map.
56470 ptrmapPutOvflPtr(pPage, pCell, pRC);
56472 #endif
56477 ** Add a list of cells to a page. The page should be initially empty.
56478 ** The cells are guaranteed to fit on the page.
56480 static void assemblePage(
56481 MemPage *pPage, /* The page to be assemblied */
56482 int nCell, /* The number of cells to add to this page */
56483 u8 **apCell, /* Pointers to cell bodies */
56484 u16 *aSize /* Sizes of the cells */
56486 int i; /* Loop counter */
56487 u8 *pCellptr; /* Address of next cell pointer */
56488 int cellbody; /* Address of next cell body */
56489 u8 * const data = pPage->aData; /* Pointer to data for pPage */
56490 const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
56491 const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
56493 assert( pPage->nOverflow==0 );
56494 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56495 assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
56496 && (int)MX_CELL(pPage->pBt)<=10921);
56497 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56499 /* Check that the page has just been zeroed by zeroPage() */
56500 assert( pPage->nCell==0 );
56501 assert( get2byteNotZero(&data[hdr+5])==nUsable );
56503 pCellptr = &pPage->aCellIdx[nCell*2];
56504 cellbody = nUsable;
56505 for(i=nCell-1; i>=0; i--){
56506 u16 sz = aSize[i];
56507 pCellptr -= 2;
56508 cellbody -= sz;
56509 put2byte(pCellptr, cellbody);
56510 memcpy(&data[cellbody], apCell[i], sz);
56512 put2byte(&data[hdr+3], nCell);
56513 put2byte(&data[hdr+5], cellbody);
56514 pPage->nFree -= (nCell*2 + nUsable - cellbody);
56515 pPage->nCell = (u16)nCell;
56519 ** The following parameters determine how many adjacent pages get involved
56520 ** in a balancing operation. NN is the number of neighbors on either side
56521 ** of the page that participate in the balancing operation. NB is the
56522 ** total number of pages that participate, including the target page and
56523 ** NN neighbors on either side.
56525 ** The minimum value of NN is 1 (of course). Increasing NN above 1
56526 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
56527 ** in exchange for a larger degradation in INSERT and UPDATE performance.
56528 ** The value of NN appears to give the best results overall.
56530 #define NN 1 /* Number of neighbors on either side of pPage */
56531 #define NB (NN*2+1) /* Total pages involved in the balance */
56534 #ifndef SQLITE_OMIT_QUICKBALANCE
56536 ** This version of balance() handles the common special case where
56537 ** a new entry is being inserted on the extreme right-end of the
56538 ** tree, in other words, when the new entry will become the largest
56539 ** entry in the tree.
56541 ** Instead of trying to balance the 3 right-most leaf pages, just add
56542 ** a new page to the right-hand side and put the one new entry in
56543 ** that page. This leaves the right side of the tree somewhat
56544 ** unbalanced. But odds are that we will be inserting new entries
56545 ** at the end soon afterwards so the nearly empty page will quickly
56546 ** fill up. On average.
56548 ** pPage is the leaf page which is the right-most page in the tree.
56549 ** pParent is its parent. pPage must have a single overflow entry
56550 ** which is also the right-most entry on the page.
56552 ** The pSpace buffer is used to store a temporary copy of the divider
56553 ** cell that will be inserted into pParent. Such a cell consists of a 4
56554 ** byte page number followed by a variable length integer. In other
56555 ** words, at most 13 bytes. Hence the pSpace buffer must be at
56556 ** least 13 bytes in size.
56558 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
56559 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
56560 MemPage *pNew; /* Newly allocated page */
56561 int rc; /* Return Code */
56562 Pgno pgnoNew; /* Page number of pNew */
56564 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56565 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56566 assert( pPage->nOverflow==1 );
56568 /* This error condition is now caught prior to reaching this function */
56569 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
56571 /* Allocate a new page. This page will become the right-sibling of
56572 ** pPage. Make the parent page writable, so that the new divider cell
56573 ** may be inserted. If both these operations are successful, proceed.
56575 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
56577 if( rc==SQLITE_OK ){
56579 u8 *pOut = &pSpace[4];
56580 u8 *pCell = pPage->apOvfl[0];
56581 u16 szCell = cellSizePtr(pPage, pCell);
56582 u8 *pStop;
56584 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
56585 assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
56586 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
56587 assemblePage(pNew, 1, &pCell, &szCell);
56589 /* If this is an auto-vacuum database, update the pointer map
56590 ** with entries for the new page, and any pointer from the
56591 ** cell on the page to an overflow page. If either of these
56592 ** operations fails, the return code is set, but the contents
56593 ** of the parent page are still manipulated by thh code below.
56594 ** That is Ok, at this point the parent page is guaranteed to
56595 ** be marked as dirty. Returning an error code will cause a
56596 ** rollback, undoing any changes made to the parent page.
56598 if( ISAUTOVACUUM ){
56599 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
56600 if( szCell>pNew->minLocal ){
56601 ptrmapPutOvflPtr(pNew, pCell, &rc);
56605 /* Create a divider cell to insert into pParent. The divider cell
56606 ** consists of a 4-byte page number (the page number of pPage) and
56607 ** a variable length key value (which must be the same value as the
56608 ** largest key on pPage).
56610 ** To find the largest key value on pPage, first find the right-most
56611 ** cell on pPage. The first two fields of this cell are the
56612 ** record-length (a variable length integer at most 32-bits in size)
56613 ** and the key value (a variable length integer, may have any value).
56614 ** The first of the while(...) loops below skips over the record-length
56615 ** field. The second while(...) loop copies the key value from the
56616 ** cell on pPage into the pSpace buffer.
56618 pCell = findCell(pPage, pPage->nCell-1);
56619 pStop = &pCell[9];
56620 while( (*(pCell++)&0x80) && pCell<pStop );
56621 pStop = &pCell[9];
56622 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
56624 /* Insert the new divider cell into pParent. */
56625 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
56626 0, pPage->pgno, &rc);
56628 /* Set the right-child pointer of pParent to point to the new page. */
56629 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
56631 /* Release the reference to the new page. */
56632 releasePage(pNew);
56635 return rc;
56637 #endif /* SQLITE_OMIT_QUICKBALANCE */
56639 #if 0
56641 ** This function does not contribute anything to the operation of SQLite.
56642 ** it is sometimes activated temporarily while debugging code responsible
56643 ** for setting pointer-map entries.
56645 static int ptrmapCheckPages(MemPage **apPage, int nPage){
56646 int i, j;
56647 for(i=0; i<nPage; i++){
56648 Pgno n;
56649 u8 e;
56650 MemPage *pPage = apPage[i];
56651 BtShared *pBt = pPage->pBt;
56652 assert( pPage->isInit );
56654 for(j=0; j<pPage->nCell; j++){
56655 CellInfo info;
56656 u8 *z;
56658 z = findCell(pPage, j);
56659 btreeParseCellPtr(pPage, z, &info);
56660 if( info.iOverflow ){
56661 Pgno ovfl = get4byte(&z[info.iOverflow]);
56662 ptrmapGet(pBt, ovfl, &e, &n);
56663 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
56665 if( !pPage->leaf ){
56666 Pgno child = get4byte(z);
56667 ptrmapGet(pBt, child, &e, &n);
56668 assert( n==pPage->pgno && e==PTRMAP_BTREE );
56671 if( !pPage->leaf ){
56672 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56673 ptrmapGet(pBt, child, &e, &n);
56674 assert( n==pPage->pgno && e==PTRMAP_BTREE );
56677 return 1;
56679 #endif
56682 ** This function is used to copy the contents of the b-tree node stored
56683 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
56684 ** the pointer-map entries for each child page are updated so that the
56685 ** parent page stored in the pointer map is page pTo. If pFrom contained
56686 ** any cells with overflow page pointers, then the corresponding pointer
56687 ** map entries are also updated so that the parent page is page pTo.
56689 ** If pFrom is currently carrying any overflow cells (entries in the
56690 ** MemPage.apOvfl[] array), they are not copied to pTo.
56692 ** Before returning, page pTo is reinitialized using btreeInitPage().
56694 ** The performance of this function is not critical. It is only used by
56695 ** the balance_shallower() and balance_deeper() procedures, neither of
56696 ** which are called often under normal circumstances.
56698 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
56699 if( (*pRC)==SQLITE_OK ){
56700 BtShared * const pBt = pFrom->pBt;
56701 u8 * const aFrom = pFrom->aData;
56702 u8 * const aTo = pTo->aData;
56703 int const iFromHdr = pFrom->hdrOffset;
56704 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
56705 int rc;
56706 int iData;
56709 assert( pFrom->isInit );
56710 assert( pFrom->nFree>=iToHdr );
56711 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
56713 /* Copy the b-tree node content from page pFrom to page pTo. */
56714 iData = get2byte(&aFrom[iFromHdr+5]);
56715 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
56716 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
56718 /* Reinitialize page pTo so that the contents of the MemPage structure
56719 ** match the new data. The initialization of pTo can actually fail under
56720 ** fairly obscure circumstances, even though it is a copy of initialized
56721 ** page pFrom.
56723 pTo->isInit = 0;
56724 rc = btreeInitPage(pTo);
56725 if( rc!=SQLITE_OK ){
56726 *pRC = rc;
56727 return;
56730 /* If this is an auto-vacuum database, update the pointer-map entries
56731 ** for any b-tree or overflow pages that pTo now contains the pointers to.
56733 if( ISAUTOVACUUM ){
56734 *pRC = setChildPtrmaps(pTo);
56740 ** This routine redistributes cells on the iParentIdx'th child of pParent
56741 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
56742 ** same amount of free space. Usually a single sibling on either side of the
56743 ** page are used in the balancing, though both siblings might come from one
56744 ** side if the page is the first or last child of its parent. If the page
56745 ** has fewer than 2 siblings (something which can only happen if the page
56746 ** is a root page or a child of a root page) then all available siblings
56747 ** participate in the balancing.
56749 ** The number of siblings of the page might be increased or decreased by
56750 ** one or two in an effort to keep pages nearly full but not over full.
56752 ** Note that when this routine is called, some of the cells on the page
56753 ** might not actually be stored in MemPage.aData[]. This can happen
56754 ** if the page is overfull. This routine ensures that all cells allocated
56755 ** to the page and its siblings fit into MemPage.aData[] before returning.
56757 ** In the course of balancing the page and its siblings, cells may be
56758 ** inserted into or removed from the parent page (pParent). Doing so
56759 ** may cause the parent page to become overfull or underfull. If this
56760 ** happens, it is the responsibility of the caller to invoke the correct
56761 ** balancing routine to fix this problem (see the balance() routine).
56763 ** If this routine fails for any reason, it might leave the database
56764 ** in a corrupted state. So if this routine fails, the database should
56765 ** be rolled back.
56767 ** The third argument to this function, aOvflSpace, is a pointer to a
56768 ** buffer big enough to hold one page. If while inserting cells into the parent
56769 ** page (pParent) the parent page becomes overfull, this buffer is
56770 ** used to store the parent's overflow cells. Because this function inserts
56771 ** a maximum of four divider cells into the parent page, and the maximum
56772 ** size of a cell stored within an internal node is always less than 1/4
56773 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
56774 ** enough for all overflow cells.
56776 ** If aOvflSpace is set to a null pointer, this function returns
56777 ** SQLITE_NOMEM.
56779 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
56780 #pragma optimize("", off)
56781 #endif
56782 static int balance_nonroot(
56783 MemPage *pParent, /* Parent page of siblings being balanced */
56784 int iParentIdx, /* Index of "the page" in pParent */
56785 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
56786 int isRoot, /* True if pParent is a root-page */
56787 int bBulk /* True if this call is part of a bulk load */
56789 BtShared *pBt; /* The whole database */
56790 int nCell = 0; /* Number of cells in apCell[] */
56791 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
56792 int nNew = 0; /* Number of pages in apNew[] */
56793 int nOld; /* Number of pages in apOld[] */
56794 int i, j, k; /* Loop counters */
56795 int nxDiv; /* Next divider slot in pParent->aCell[] */
56796 int rc = SQLITE_OK; /* The return code */
56797 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
56798 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
56799 int usableSpace; /* Bytes in pPage beyond the header */
56800 int pageFlags; /* Value of pPage->aData[0] */
56801 int subtotal; /* Subtotal of bytes in cells on one page */
56802 int iSpace1 = 0; /* First unused byte of aSpace1[] */
56803 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
56804 int szScratch; /* Size of scratch memory requested */
56805 MemPage *apOld[NB]; /* pPage and up to two siblings */
56806 MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
56807 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
56808 u8 *pRight; /* Location in parent of right-sibling pointer */
56809 u8 *apDiv[NB-1]; /* Divider cells in pParent */
56810 int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
56811 int szNew[NB+2]; /* Combined size of cells place on i-th page */
56812 u8 **apCell = 0; /* All cells begin balanced */
56813 u16 *szCell; /* Local size of all cells in apCell[] */
56814 u8 *aSpace1; /* Space for copies of dividers cells */
56815 Pgno pgno; /* Temp var to store a page number in */
56817 pBt = pParent->pBt;
56818 assert( sqlite3_mutex_held(pBt->mutex) );
56819 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56821 #if 0
56822 TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
56823 #endif
56825 /* At this point pParent may have at most one overflow cell. And if
56826 ** this overflow cell is present, it must be the cell with
56827 ** index iParentIdx. This scenario comes about when this function
56828 ** is called (indirectly) from sqlite3BtreeDelete().
56830 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
56831 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
56833 if( !aOvflSpace ){
56834 return SQLITE_NOMEM;
56837 /* Find the sibling pages to balance. Also locate the cells in pParent
56838 ** that divide the siblings. An attempt is made to find NN siblings on
56839 ** either side of pPage. More siblings are taken from one side, however,
56840 ** if there are fewer than NN siblings on the other side. If pParent
56841 ** has NB or fewer children then all children of pParent are taken.
56843 ** This loop also drops the divider cells from the parent page. This
56844 ** way, the remainder of the function does not have to deal with any
56845 ** overflow cells in the parent page, since if any existed they will
56846 ** have already been removed.
56848 i = pParent->nOverflow + pParent->nCell;
56849 if( i<2 ){
56850 nxDiv = 0;
56851 }else{
56852 assert( bBulk==0 || bBulk==1 );
56853 if( iParentIdx==0 ){
56854 nxDiv = 0;
56855 }else if( iParentIdx==i ){
56856 nxDiv = i-2+bBulk;
56857 }else{
56858 assert( bBulk==0 );
56859 nxDiv = iParentIdx-1;
56861 i = 2-bBulk;
56863 nOld = i+1;
56864 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
56865 pRight = &pParent->aData[pParent->hdrOffset+8];
56866 }else{
56867 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
56869 pgno = get4byte(pRight);
56870 while( 1 ){
56871 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
56872 if( rc ){
56873 memset(apOld, 0, (i+1)*sizeof(MemPage*));
56874 goto balance_cleanup;
56876 nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
56877 if( (i--)==0 ) break;
56879 if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
56880 apDiv[i] = pParent->apOvfl[0];
56881 pgno = get4byte(apDiv[i]);
56882 szNew[i] = cellSizePtr(pParent, apDiv[i]);
56883 pParent->nOverflow = 0;
56884 }else{
56885 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
56886 pgno = get4byte(apDiv[i]);
56887 szNew[i] = cellSizePtr(pParent, apDiv[i]);
56889 /* Drop the cell from the parent page. apDiv[i] still points to
56890 ** the cell within the parent, even though it has been dropped.
56891 ** This is safe because dropping a cell only overwrites the first
56892 ** four bytes of it, and this function does not need the first
56893 ** four bytes of the divider cell. So the pointer is safe to use
56894 ** later on.
56896 ** But not if we are in secure-delete mode. In secure-delete mode,
56897 ** the dropCell() routine will overwrite the entire cell with zeroes.
56898 ** In this case, temporarily copy the cell into the aOvflSpace[]
56899 ** buffer. It will be copied out again as soon as the aSpace[] buffer
56900 ** is allocated. */
56901 if( pBt->btsFlags & BTS_SECURE_DELETE ){
56902 int iOff;
56904 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
56905 if( (iOff+szNew[i])>(int)pBt->usableSize ){
56906 rc = SQLITE_CORRUPT_BKPT;
56907 memset(apOld, 0, (i+1)*sizeof(MemPage*));
56908 goto balance_cleanup;
56909 }else{
56910 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
56911 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
56914 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
56918 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
56919 ** alignment */
56920 nMaxCells = (nMaxCells + 3)&~3;
56923 ** Allocate space for memory structures
56925 k = pBt->pageSize + ROUND8(sizeof(MemPage));
56926 szScratch =
56927 nMaxCells*sizeof(u8*) /* apCell */
56928 + nMaxCells*sizeof(u16) /* szCell */
56929 + pBt->pageSize /* aSpace1 */
56930 + k*nOld; /* Page copies (apCopy) */
56931 apCell = sqlite3ScratchMalloc( szScratch );
56932 if( apCell==0 ){
56933 rc = SQLITE_NOMEM;
56934 goto balance_cleanup;
56936 szCell = (u16*)&apCell[nMaxCells];
56937 aSpace1 = (u8*)&szCell[nMaxCells];
56938 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
56941 ** Load pointers to all cells on sibling pages and the divider cells
56942 ** into the local apCell[] array. Make copies of the divider cells
56943 ** into space obtained from aSpace1[] and remove the divider cells
56944 ** from pParent.
56946 ** If the siblings are on leaf pages, then the child pointers of the
56947 ** divider cells are stripped from the cells before they are copied
56948 ** into aSpace1[]. In this way, all cells in apCell[] are without
56949 ** child pointers. If siblings are not leaves, then all cell in
56950 ** apCell[] include child pointers. Either way, all cells in apCell[]
56951 ** are alike.
56953 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
56954 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
56956 leafCorrection = apOld[0]->leaf*4;
56957 leafData = apOld[0]->hasData;
56958 for(i=0; i<nOld; i++){
56959 int limit;
56961 /* Before doing anything else, take a copy of the i'th original sibling
56962 ** The rest of this function will use data from the copies rather
56963 ** that the original pages since the original pages will be in the
56964 ** process of being overwritten. */
56965 MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
56966 memcpy(pOld, apOld[i], sizeof(MemPage));
56967 pOld->aData = (void*)&pOld[1];
56968 memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
56970 limit = pOld->nCell+pOld->nOverflow;
56971 if( pOld->nOverflow>0 ){
56972 for(j=0; j<limit; j++){
56973 assert( nCell<nMaxCells );
56974 apCell[nCell] = findOverflowCell(pOld, j);
56975 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
56976 nCell++;
56978 }else{
56979 u8 *aData = pOld->aData;
56980 u16 maskPage = pOld->maskPage;
56981 u16 cellOffset = pOld->cellOffset;
56982 for(j=0; j<limit; j++){
56983 assert( nCell<nMaxCells );
56984 apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
56985 szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
56986 nCell++;
56989 if( i<nOld-1 && !leafData){
56990 u16 sz = (u16)szNew[i];
56991 u8 *pTemp;
56992 assert( nCell<nMaxCells );
56993 szCell[nCell] = sz;
56994 pTemp = &aSpace1[iSpace1];
56995 iSpace1 += sz;
56996 assert( sz<=pBt->maxLocal+23 );
56997 assert( iSpace1 <= (int)pBt->pageSize );
56998 memcpy(pTemp, apDiv[i], sz);
56999 apCell[nCell] = pTemp+leafCorrection;
57000 assert( leafCorrection==0 || leafCorrection==4 );
57001 szCell[nCell] = szCell[nCell] - leafCorrection;
57002 if( !pOld->leaf ){
57003 assert( leafCorrection==0 );
57004 assert( pOld->hdrOffset==0 );
57005 /* The right pointer of the child page pOld becomes the left
57006 ** pointer of the divider cell */
57007 memcpy(apCell[nCell], &pOld->aData[8], 4);
57008 }else{
57009 assert( leafCorrection==4 );
57010 if( szCell[nCell]<4 ){
57011 /* Do not allow any cells smaller than 4 bytes. */
57012 szCell[nCell] = 4;
57015 nCell++;
57020 ** Figure out the number of pages needed to hold all nCell cells.
57021 ** Store this number in "k". Also compute szNew[] which is the total
57022 ** size of all cells on the i-th page and cntNew[] which is the index
57023 ** in apCell[] of the cell that divides page i from page i+1.
57024 ** cntNew[k] should equal nCell.
57026 ** Values computed by this block:
57028 ** k: The total number of sibling pages
57029 ** szNew[i]: Spaced used on the i-th sibling page.
57030 ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
57031 ** the right of the i-th sibling page.
57032 ** usableSpace: Number of bytes of space available on each sibling.
57035 usableSpace = pBt->usableSize - 12 + leafCorrection;
57036 for(subtotal=k=i=0; i<nCell; i++){
57037 assert( i<nMaxCells );
57038 subtotal += szCell[i] + 2;
57039 if( subtotal > usableSpace ){
57040 szNew[k] = subtotal - szCell[i];
57041 cntNew[k] = i;
57042 if( leafData ){ i--; }
57043 subtotal = 0;
57044 k++;
57045 if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
57048 szNew[k] = subtotal;
57049 cntNew[k] = nCell;
57050 k++;
57053 ** The packing computed by the previous block is biased toward the siblings
57054 ** on the left side. The left siblings are always nearly full, while the
57055 ** right-most sibling might be nearly empty. This block of code attempts
57056 ** to adjust the packing of siblings to get a better balance.
57058 ** This adjustment is more than an optimization. The packing above might
57059 ** be so out of balance as to be illegal. For example, the right-most
57060 ** sibling might be completely empty. This adjustment is not optional.
57062 for(i=k-1; i>0; i--){
57063 int szRight = szNew[i]; /* Size of sibling on the right */
57064 int szLeft = szNew[i-1]; /* Size of sibling on the left */
57065 int r; /* Index of right-most cell in left sibling */
57066 int d; /* Index of first cell to the left of right sibling */
57068 r = cntNew[i-1] - 1;
57069 d = r + 1 - leafData;
57070 assert( d<nMaxCells );
57071 assert( r<nMaxCells );
57072 while( szRight==0
57073 || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
57075 szRight += szCell[d] + 2;
57076 szLeft -= szCell[r] + 2;
57077 cntNew[i-1]--;
57078 r = cntNew[i-1] - 1;
57079 d = r + 1 - leafData;
57081 szNew[i] = szRight;
57082 szNew[i-1] = szLeft;
57085 /* Either we found one or more cells (cntnew[0])>0) or pPage is
57086 ** a virtual root page. A virtual root page is when the real root
57087 ** page is page 1 and we are the only child of that page.
57089 ** UPDATE: The assert() below is not necessarily true if the database
57090 ** file is corrupt. The corruption will be detected and reported later
57091 ** in this procedure so there is no need to act upon it now.
57093 #if 0
57094 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
57095 #endif
57097 TRACE(("BALANCE: old: %d %d %d ",
57098 apOld[0]->pgno,
57099 nOld>=2 ? apOld[1]->pgno : 0,
57100 nOld>=3 ? apOld[2]->pgno : 0
57104 ** Allocate k new pages. Reuse old pages where possible.
57106 if( apOld[0]->pgno<=1 ){
57107 rc = SQLITE_CORRUPT_BKPT;
57108 goto balance_cleanup;
57110 pageFlags = apOld[0]->aData[0];
57111 for(i=0; i<k; i++){
57112 MemPage *pNew;
57113 if( i<nOld ){
57114 pNew = apNew[i] = apOld[i];
57115 apOld[i] = 0;
57116 rc = sqlite3PagerWrite(pNew->pDbPage);
57117 nNew++;
57118 if( rc ) goto balance_cleanup;
57119 }else{
57120 assert( i>0 );
57121 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
57122 if( rc ) goto balance_cleanup;
57123 apNew[i] = pNew;
57124 nNew++;
57126 /* Set the pointer-map entry for the new sibling page. */
57127 if( ISAUTOVACUUM ){
57128 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
57129 if( rc!=SQLITE_OK ){
57130 goto balance_cleanup;
57136 /* Free any old pages that were not reused as new pages.
57138 while( i<nOld ){
57139 freePage(apOld[i], &rc);
57140 if( rc ) goto balance_cleanup;
57141 releasePage(apOld[i]);
57142 apOld[i] = 0;
57143 i++;
57147 ** Put the new pages in accending order. This helps to
57148 ** keep entries in the disk file in order so that a scan
57149 ** of the table is a linear scan through the file. That
57150 ** in turn helps the operating system to deliver pages
57151 ** from the disk more rapidly.
57153 ** An O(n^2) insertion sort algorithm is used, but since
57154 ** n is never more than NB (a small constant), that should
57155 ** not be a problem.
57157 ** When NB==3, this one optimization makes the database
57158 ** about 25% faster for large insertions and deletions.
57160 for(i=0; i<k-1; i++){
57161 int minV = apNew[i]->pgno;
57162 int minI = i;
57163 for(j=i+1; j<k; j++){
57164 if( apNew[j]->pgno<(unsigned)minV ){
57165 minI = j;
57166 minV = apNew[j]->pgno;
57169 if( minI>i ){
57170 MemPage *pT;
57171 pT = apNew[i];
57172 apNew[i] = apNew[minI];
57173 apNew[minI] = pT;
57176 TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
57177 apNew[0]->pgno, szNew[0],
57178 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
57179 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
57180 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
57181 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
57183 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
57184 put4byte(pRight, apNew[nNew-1]->pgno);
57187 ** Evenly distribute the data in apCell[] across the new pages.
57188 ** Insert divider cells into pParent as necessary.
57190 j = 0;
57191 for(i=0; i<nNew; i++){
57192 /* Assemble the new sibling page. */
57193 MemPage *pNew = apNew[i];
57194 assert( j<nMaxCells );
57195 zeroPage(pNew, pageFlags);
57196 assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
57197 assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
57198 assert( pNew->nOverflow==0 );
57200 j = cntNew[i];
57202 /* If the sibling page assembled above was not the right-most sibling,
57203 ** insert a divider cell into the parent page.
57205 assert( i<nNew-1 || j==nCell );
57206 if( j<nCell ){
57207 u8 *pCell;
57208 u8 *pTemp;
57209 int sz;
57211 assert( j<nMaxCells );
57212 pCell = apCell[j];
57213 sz = szCell[j] + leafCorrection;
57214 pTemp = &aOvflSpace[iOvflSpace];
57215 if( !pNew->leaf ){
57216 memcpy(&pNew->aData[8], pCell, 4);
57217 }else if( leafData ){
57218 /* If the tree is a leaf-data tree, and the siblings are leaves,
57219 ** then there is no divider cell in apCell[]. Instead, the divider
57220 ** cell consists of the integer key for the right-most cell of
57221 ** the sibling-page assembled above only.
57223 CellInfo info;
57224 j--;
57225 btreeParseCellPtr(pNew, apCell[j], &info);
57226 pCell = pTemp;
57227 sz = 4 + putVarint(&pCell[4], info.nKey);
57228 pTemp = 0;
57229 }else{
57230 pCell -= 4;
57231 /* Obscure case for non-leaf-data trees: If the cell at pCell was
57232 ** previously stored on a leaf node, and its reported size was 4
57233 ** bytes, then it may actually be smaller than this
57234 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
57235 ** any cell). But it is important to pass the correct size to
57236 ** insertCell(), so reparse the cell now.
57238 ** Note that this can never happen in an SQLite data file, as all
57239 ** cells are at least 4 bytes. It only happens in b-trees used
57240 ** to evaluate "IN (SELECT ...)" and similar clauses.
57242 if( szCell[j]==4 ){
57243 assert(leafCorrection==4);
57244 sz = cellSizePtr(pParent, pCell);
57247 iOvflSpace += sz;
57248 assert( sz<=pBt->maxLocal+23 );
57249 assert( iOvflSpace <= (int)pBt->pageSize );
57250 insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
57251 if( rc!=SQLITE_OK ) goto balance_cleanup;
57252 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
57254 j++;
57255 nxDiv++;
57258 assert( j==nCell );
57259 assert( nOld>0 );
57260 assert( nNew>0 );
57261 if( (pageFlags & PTF_LEAF)==0 ){
57262 u8 *zChild = &apCopy[nOld-1]->aData[8];
57263 memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
57266 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
57267 /* The root page of the b-tree now contains no cells. The only sibling
57268 ** page is the right-child of the parent. Copy the contents of the
57269 ** child page into the parent, decreasing the overall height of the
57270 ** b-tree structure by one. This is described as the "balance-shallower"
57271 ** sub-algorithm in some documentation.
57273 ** If this is an auto-vacuum database, the call to copyNodeContent()
57274 ** sets all pointer-map entries corresponding to database image pages
57275 ** for which the pointer is stored within the content being copied.
57277 ** The second assert below verifies that the child page is defragmented
57278 ** (it must be, as it was just reconstructed using assemblePage()). This
57279 ** is important if the parent page happens to be page 1 of the database
57280 ** image. */
57281 assert( nNew==1 );
57282 assert( apNew[0]->nFree ==
57283 (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
57285 copyNodeContent(apNew[0], pParent, &rc);
57286 freePage(apNew[0], &rc);
57287 }else if( ISAUTOVACUUM ){
57288 /* Fix the pointer-map entries for all the cells that were shifted around.
57289 ** There are several different types of pointer-map entries that need to
57290 ** be dealt with by this routine. Some of these have been set already, but
57291 ** many have not. The following is a summary:
57293 ** 1) The entries associated with new sibling pages that were not
57294 ** siblings when this function was called. These have already
57295 ** been set. We don't need to worry about old siblings that were
57296 ** moved to the free-list - the freePage() code has taken care
57297 ** of those.
57299 ** 2) The pointer-map entries associated with the first overflow
57300 ** page in any overflow chains used by new divider cells. These
57301 ** have also already been taken care of by the insertCell() code.
57303 ** 3) If the sibling pages are not leaves, then the child pages of
57304 ** cells stored on the sibling pages may need to be updated.
57306 ** 4) If the sibling pages are not internal intkey nodes, then any
57307 ** overflow pages used by these cells may need to be updated
57308 ** (internal intkey nodes never contain pointers to overflow pages).
57310 ** 5) If the sibling pages are not leaves, then the pointer-map
57311 ** entries for the right-child pages of each sibling may need
57312 ** to be updated.
57314 ** Cases 1 and 2 are dealt with above by other code. The next
57315 ** block deals with cases 3 and 4 and the one after that, case 5. Since
57316 ** setting a pointer map entry is a relatively expensive operation, this
57317 ** code only sets pointer map entries for child or overflow pages that have
57318 ** actually moved between pages. */
57319 MemPage *pNew = apNew[0];
57320 MemPage *pOld = apCopy[0];
57321 int nOverflow = pOld->nOverflow;
57322 int iNextOld = pOld->nCell + nOverflow;
57323 int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
57324 j = 0; /* Current 'old' sibling page */
57325 k = 0; /* Current 'new' sibling page */
57326 for(i=0; i<nCell; i++){
57327 int isDivider = 0;
57328 while( i==iNextOld ){
57329 /* Cell i is the cell immediately following the last cell on old
57330 ** sibling page j. If the siblings are not leaf pages of an
57331 ** intkey b-tree, then cell i was a divider cell. */
57332 assert( j+1 < ArraySize(apCopy) );
57333 assert( j+1 < nOld );
57334 #if defined(__minix)
57335 /*LSC: While compiling with -O3:
57336 * error: array subscript is above array bounds [-Werror=array-bounds]
57337 * pOld = apCopy[++j];
57339 if (!(j+1 < ArraySize(apCopy)))
57340 abort();
57341 #endif /* defined(__minix) */
57342 pOld = apCopy[++j];
57343 iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
57344 if( pOld->nOverflow ){
57345 nOverflow = pOld->nOverflow;
57346 iOverflow = i + !leafData + pOld->aiOvfl[0];
57348 isDivider = !leafData;
57351 assert(nOverflow>0 || iOverflow<i );
57352 assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
57353 assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
57354 if( i==iOverflow ){
57355 isDivider = 1;
57356 if( (--nOverflow)>0 ){
57357 iOverflow++;
57361 if( i==cntNew[k] ){
57362 /* Cell i is the cell immediately following the last cell on new
57363 ** sibling page k. If the siblings are not leaf pages of an
57364 ** intkey b-tree, then cell i is a divider cell. */
57365 pNew = apNew[++k];
57366 if( !leafData ) continue;
57368 assert( j<nOld );
57369 assert( k<nNew );
57371 /* If the cell was originally divider cell (and is not now) or
57372 ** an overflow cell, or if the cell was located on a different sibling
57373 ** page before the balancing, then the pointer map entries associated
57374 ** with any child or overflow pages need to be updated. */
57375 if( isDivider || pOld->pgno!=pNew->pgno ){
57376 if( !leafCorrection ){
57377 ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
57379 if( szCell[i]>pNew->minLocal ){
57380 ptrmapPutOvflPtr(pNew, apCell[i], &rc);
57385 if( !leafCorrection ){
57386 for(i=0; i<nNew; i++){
57387 u32 key = get4byte(&apNew[i]->aData[8]);
57388 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
57392 #if 0
57393 /* The ptrmapCheckPages() contains assert() statements that verify that
57394 ** all pointer map pages are set correctly. This is helpful while
57395 ** debugging. This is usually disabled because a corrupt database may
57396 ** cause an assert() statement to fail. */
57397 ptrmapCheckPages(apNew, nNew);
57398 ptrmapCheckPages(&pParent, 1);
57399 #endif
57402 assert( pParent->isInit );
57403 TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
57404 nOld, nNew, nCell));
57407 ** Cleanup before returning.
57409 balance_cleanup:
57410 sqlite3ScratchFree(apCell);
57411 for(i=0; i<nOld; i++){
57412 releasePage(apOld[i]);
57414 for(i=0; i<nNew; i++){
57415 releasePage(apNew[i]);
57418 return rc;
57420 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
57421 #pragma optimize("", on)
57422 #endif
57426 ** This function is called when the root page of a b-tree structure is
57427 ** overfull (has one or more overflow pages).
57429 ** A new child page is allocated and the contents of the current root
57430 ** page, including overflow cells, are copied into the child. The root
57431 ** page is then overwritten to make it an empty page with the right-child
57432 ** pointer pointing to the new page.
57434 ** Before returning, all pointer-map entries corresponding to pages
57435 ** that the new child-page now contains pointers to are updated. The
57436 ** entry corresponding to the new right-child pointer of the root
57437 ** page is also updated.
57439 ** If successful, *ppChild is set to contain a reference to the child
57440 ** page and SQLITE_OK is returned. In this case the caller is required
57441 ** to call releasePage() on *ppChild exactly once. If an error occurs,
57442 ** an error code is returned and *ppChild is set to 0.
57444 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
57445 int rc; /* Return value from subprocedures */
57446 MemPage *pChild = 0; /* Pointer to a new child page */
57447 Pgno pgnoChild = 0; /* Page number of the new child page */
57448 BtShared *pBt = pRoot->pBt; /* The BTree */
57450 assert( pRoot->nOverflow>0 );
57451 assert( sqlite3_mutex_held(pBt->mutex) );
57453 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
57454 ** page that will become the new right-child of pPage. Copy the contents
57455 ** of the node stored on pRoot into the new child page.
57457 rc = sqlite3PagerWrite(pRoot->pDbPage);
57458 if( rc==SQLITE_OK ){
57459 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
57460 copyNodeContent(pRoot, pChild, &rc);
57461 if( ISAUTOVACUUM ){
57462 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
57465 if( rc ){
57466 *ppChild = 0;
57467 releasePage(pChild);
57468 return rc;
57470 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
57471 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
57472 assert( pChild->nCell==pRoot->nCell );
57474 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
57476 /* Copy the overflow cells from pRoot to pChild */
57477 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
57478 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
57479 memcpy(pChild->apOvfl, pRoot->apOvfl,
57480 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
57481 pChild->nOverflow = pRoot->nOverflow;
57483 /* Zero the contents of pRoot. Then install pChild as the right-child. */
57484 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
57485 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
57487 *ppChild = pChild;
57488 return SQLITE_OK;
57492 ** The page that pCur currently points to has just been modified in
57493 ** some way. This function figures out if this modification means the
57494 ** tree needs to be balanced, and if so calls the appropriate balancing
57495 ** routine. Balancing routines are:
57497 ** balance_quick()
57498 ** balance_deeper()
57499 ** balance_nonroot()
57501 static int balance(BtCursor *pCur){
57502 int rc = SQLITE_OK;
57503 const int nMin = pCur->pBt->usableSize * 2 / 3;
57504 u8 aBalanceQuickSpace[13];
57505 u8 *pFree = 0;
57507 TESTONLY( int balance_quick_called = 0 );
57508 TESTONLY( int balance_deeper_called = 0 );
57510 do {
57511 int iPage = pCur->iPage;
57512 MemPage *pPage = pCur->apPage[iPage];
57514 if( iPage==0 ){
57515 if( pPage->nOverflow ){
57516 /* The root page of the b-tree is overfull. In this case call the
57517 ** balance_deeper() function to create a new child for the root-page
57518 ** and copy the current contents of the root-page to it. The
57519 ** next iteration of the do-loop will balance the child page.
57521 assert( (balance_deeper_called++)==0 );
57522 rc = balance_deeper(pPage, &pCur->apPage[1]);
57523 if( rc==SQLITE_OK ){
57524 pCur->iPage = 1;
57525 pCur->aiIdx[0] = 0;
57526 pCur->aiIdx[1] = 0;
57527 assert( pCur->apPage[1]->nOverflow );
57529 }else{
57530 break;
57532 }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
57533 break;
57534 }else{
57535 MemPage * const pParent = pCur->apPage[iPage-1];
57536 int const iIdx = pCur->aiIdx[iPage-1];
57538 rc = sqlite3PagerWrite(pParent->pDbPage);
57539 if( rc==SQLITE_OK ){
57540 #ifndef SQLITE_OMIT_QUICKBALANCE
57541 if( pPage->hasData
57542 && pPage->nOverflow==1
57543 && pPage->aiOvfl[0]==pPage->nCell
57544 && pParent->pgno!=1
57545 && pParent->nCell==iIdx
57547 /* Call balance_quick() to create a new sibling of pPage on which
57548 ** to store the overflow cell. balance_quick() inserts a new cell
57549 ** into pParent, which may cause pParent overflow. If this
57550 ** happens, the next interation of the do-loop will balance pParent
57551 ** use either balance_nonroot() or balance_deeper(). Until this
57552 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
57553 ** buffer.
57555 ** The purpose of the following assert() is to check that only a
57556 ** single call to balance_quick() is made for each call to this
57557 ** function. If this were not verified, a subtle bug involving reuse
57558 ** of the aBalanceQuickSpace[] might sneak in.
57560 assert( (balance_quick_called++)==0 );
57561 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
57562 }else
57563 #endif
57565 /* In this case, call balance_nonroot() to redistribute cells
57566 ** between pPage and up to 2 of its sibling pages. This involves
57567 ** modifying the contents of pParent, which may cause pParent to
57568 ** become overfull or underfull. The next iteration of the do-loop
57569 ** will balance the parent page to correct this.
57571 ** If the parent page becomes overfull, the overflow cell or cells
57572 ** are stored in the pSpace buffer allocated immediately below.
57573 ** A subsequent iteration of the do-loop will deal with this by
57574 ** calling balance_nonroot() (balance_deeper() may be called first,
57575 ** but it doesn't deal with overflow cells - just moves them to a
57576 ** different page). Once this subsequent call to balance_nonroot()
57577 ** has completed, it is safe to release the pSpace buffer used by
57578 ** the previous call, as the overflow cell data will have been
57579 ** copied either into the body of a database page or into the new
57580 ** pSpace buffer passed to the latter call to balance_nonroot().
57582 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
57583 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
57584 if( pFree ){
57585 /* If pFree is not NULL, it points to the pSpace buffer used
57586 ** by a previous call to balance_nonroot(). Its contents are
57587 ** now stored either on real database pages or within the
57588 ** new pSpace buffer, so it may be safely freed here. */
57589 sqlite3PageFree(pFree);
57592 /* The pSpace buffer will be freed after the next call to
57593 ** balance_nonroot(), or just before this function returns, whichever
57594 ** comes first. */
57595 pFree = pSpace;
57599 pPage->nOverflow = 0;
57601 /* The next iteration of the do-loop balances the parent page. */
57602 releasePage(pPage);
57603 pCur->iPage--;
57605 }while( rc==SQLITE_OK );
57607 if( pFree ){
57608 sqlite3PageFree(pFree);
57610 return rc;
57615 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
57616 ** and the data is given by (pData,nData). The cursor is used only to
57617 ** define what table the record should be inserted into. The cursor
57618 ** is left pointing at a random location.
57620 ** For an INTKEY table, only the nKey value of the key is used. pKey is
57621 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
57623 ** If the seekResult parameter is non-zero, then a successful call to
57624 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
57625 ** been performed. seekResult is the search result returned (a negative
57626 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
57627 ** a positive value if pCur points at an etry that is larger than
57628 ** (pKey, nKey)).
57630 ** If the seekResult parameter is non-zero, then the caller guarantees that
57631 ** cursor pCur is pointing at the existing copy of a row that is to be
57632 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
57633 ** point to any entry or to no entry at all and so this function has to seek
57634 ** the cursor before the new key can be inserted.
57636 SQLITE_PRIVATE int sqlite3BtreeInsert(
57637 BtCursor *pCur, /* Insert data into the table of this cursor */
57638 const void *pKey, i64 nKey, /* The key of the new record */
57639 const void *pData, int nData, /* The data of the new record */
57640 int nZero, /* Number of extra 0 bytes to append to data */
57641 int appendBias, /* True if this is likely an append */
57642 int seekResult /* Result of prior MovetoUnpacked() call */
57644 int rc;
57645 int loc = seekResult; /* -1: before desired location +1: after */
57646 int szNew = 0;
57647 int idx;
57648 MemPage *pPage;
57649 Btree *p = pCur->pBtree;
57650 BtShared *pBt = p->pBt;
57651 unsigned char *oldCell;
57652 unsigned char *newCell = 0;
57654 if( pCur->eState==CURSOR_FAULT ){
57655 assert( pCur->skipNext!=SQLITE_OK );
57656 return pCur->skipNext;
57659 assert( cursorHoldsMutex(pCur) );
57660 assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
57661 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
57662 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
57664 /* Assert that the caller has been consistent. If this cursor was opened
57665 ** expecting an index b-tree, then the caller should be inserting blob
57666 ** keys with no associated data. If the cursor was opened expecting an
57667 ** intkey table, the caller should be inserting integer keys with a
57668 ** blob of associated data. */
57669 assert( (pKey==0)==(pCur->pKeyInfo==0) );
57671 /* Save the positions of any other cursors open on this table.
57673 ** In some cases, the call to btreeMoveto() below is a no-op. For
57674 ** example, when inserting data into a table with auto-generated integer
57675 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
57676 ** integer key to use. It then calls this function to actually insert the
57677 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
57678 ** that the cursor is already where it needs to be and returns without
57679 ** doing any work. To avoid thwarting these optimizations, it is important
57680 ** not to clear the cursor here.
57682 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
57683 if( rc ) return rc;
57685 /* If this is an insert into a table b-tree, invalidate any incrblob
57686 ** cursors open on the row being replaced (assuming this is a replace
57687 ** operation - if it is not, the following is a no-op). */
57688 if( pCur->pKeyInfo==0 ){
57689 invalidateIncrblobCursors(p, nKey, 0);
57692 if( !loc ){
57693 rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
57694 if( rc ) return rc;
57696 assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
57698 pPage = pCur->apPage[pCur->iPage];
57699 assert( pPage->intKey || nKey>=0 );
57700 assert( pPage->leaf || !pPage->intKey );
57702 TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
57703 pCur->pgnoRoot, nKey, nData, pPage->pgno,
57704 loc==0 ? "overwrite" : "new entry"));
57705 assert( pPage->isInit );
57706 allocateTempSpace(pBt);
57707 newCell = pBt->pTmpSpace;
57708 if( newCell==0 ) return SQLITE_NOMEM;
57709 rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
57710 if( rc ) goto end_insert;
57711 assert( szNew==cellSizePtr(pPage, newCell) );
57712 assert( szNew <= MX_CELL_SIZE(pBt) );
57713 idx = pCur->aiIdx[pCur->iPage];
57714 if( loc==0 ){
57715 u16 szOld;
57716 assert( idx<pPage->nCell );
57717 rc = sqlite3PagerWrite(pPage->pDbPage);
57718 if( rc ){
57719 goto end_insert;
57721 oldCell = findCell(pPage, idx);
57722 if( !pPage->leaf ){
57723 memcpy(newCell, oldCell, 4);
57725 szOld = cellSizePtr(pPage, oldCell);
57726 rc = clearCell(pPage, oldCell);
57727 dropCell(pPage, idx, szOld, &rc);
57728 if( rc ) goto end_insert;
57729 }else if( loc<0 && pPage->nCell>0 ){
57730 assert( pPage->leaf );
57731 idx = ++pCur->aiIdx[pCur->iPage];
57732 }else{
57733 assert( pPage->leaf );
57735 insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
57736 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
57738 /* If no error has occurred and pPage has an overflow cell, call balance()
57739 ** to redistribute the cells within the tree. Since balance() may move
57740 ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
57741 ** variables.
57743 ** Previous versions of SQLite called moveToRoot() to move the cursor
57744 ** back to the root page as balance() used to invalidate the contents
57745 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
57746 ** set the cursor state to "invalid". This makes common insert operations
57747 ** slightly faster.
57749 ** There is a subtle but important optimization here too. When inserting
57750 ** multiple records into an intkey b-tree using a single cursor (as can
57751 ** happen while processing an "INSERT INTO ... SELECT" statement), it
57752 ** is advantageous to leave the cursor pointing to the last entry in
57753 ** the b-tree if possible. If the cursor is left pointing to the last
57754 ** entry in the table, and the next row inserted has an integer key
57755 ** larger than the largest existing key, it is possible to insert the
57756 ** row without seeking the cursor. This can be a big performance boost.
57758 pCur->info.nSize = 0;
57759 pCur->validNKey = 0;
57760 if( rc==SQLITE_OK && pPage->nOverflow ){
57761 rc = balance(pCur);
57763 /* Must make sure nOverflow is reset to zero even if the balance()
57764 ** fails. Internal data structure corruption will result otherwise.
57765 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
57766 ** from trying to save the current position of the cursor. */
57767 pCur->apPage[pCur->iPage]->nOverflow = 0;
57768 pCur->eState = CURSOR_INVALID;
57770 assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
57772 end_insert:
57773 return rc;
57777 ** Delete the entry that the cursor is pointing to. The cursor
57778 ** is left pointing at a arbitrary location.
57780 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
57781 Btree *p = pCur->pBtree;
57782 BtShared *pBt = p->pBt;
57783 int rc; /* Return code */
57784 MemPage *pPage; /* Page to delete cell from */
57785 unsigned char *pCell; /* Pointer to cell to delete */
57786 int iCellIdx; /* Index of cell to delete */
57787 int iCellDepth; /* Depth of node containing pCell */
57789 assert( cursorHoldsMutex(pCur) );
57790 assert( pBt->inTransaction==TRANS_WRITE );
57791 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
57792 assert( pCur->wrFlag );
57793 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
57794 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
57796 if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
57797 || NEVER(pCur->eState!=CURSOR_VALID)
57799 return SQLITE_ERROR; /* Something has gone awry. */
57802 iCellDepth = pCur->iPage;
57803 iCellIdx = pCur->aiIdx[iCellDepth];
57804 pPage = pCur->apPage[iCellDepth];
57805 pCell = findCell(pPage, iCellIdx);
57807 /* If the page containing the entry to delete is not a leaf page, move
57808 ** the cursor to the largest entry in the tree that is smaller than
57809 ** the entry being deleted. This cell will replace the cell being deleted
57810 ** from the internal node. The 'previous' entry is used for this instead
57811 ** of the 'next' entry, as the previous entry is always a part of the
57812 ** sub-tree headed by the child page of the cell being deleted. This makes
57813 ** balancing the tree following the delete operation easier. */
57814 if( !pPage->leaf ){
57815 int notUsed;
57816 rc = sqlite3BtreePrevious(pCur, &notUsed);
57817 if( rc ) return rc;
57820 /* Save the positions of any other cursors open on this table before
57821 ** making any modifications. Make the page containing the entry to be
57822 ** deleted writable. Then free any overflow pages associated with the
57823 ** entry and finally remove the cell itself from within the page.
57825 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
57826 if( rc ) return rc;
57828 /* If this is a delete operation to remove a row from a table b-tree,
57829 ** invalidate any incrblob cursors open on the row being deleted. */
57830 if( pCur->pKeyInfo==0 ){
57831 invalidateIncrblobCursors(p, pCur->info.nKey, 0);
57834 rc = sqlite3PagerWrite(pPage->pDbPage);
57835 if( rc ) return rc;
57836 rc = clearCell(pPage, pCell);
57837 dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
57838 if( rc ) return rc;
57840 /* If the cell deleted was not located on a leaf page, then the cursor
57841 ** is currently pointing to the largest entry in the sub-tree headed
57842 ** by the child-page of the cell that was just deleted from an internal
57843 ** node. The cell from the leaf node needs to be moved to the internal
57844 ** node to replace the deleted cell. */
57845 if( !pPage->leaf ){
57846 MemPage *pLeaf = pCur->apPage[pCur->iPage];
57847 int nCell;
57848 Pgno n = pCur->apPage[iCellDepth+1]->pgno;
57849 unsigned char *pTmp;
57851 pCell = findCell(pLeaf, pLeaf->nCell-1);
57852 nCell = cellSizePtr(pLeaf, pCell);
57853 assert( MX_CELL_SIZE(pBt) >= nCell );
57855 allocateTempSpace(pBt);
57856 pTmp = pBt->pTmpSpace;
57858 rc = sqlite3PagerWrite(pLeaf->pDbPage);
57859 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
57860 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
57861 if( rc ) return rc;
57864 /* Balance the tree. If the entry deleted was located on a leaf page,
57865 ** then the cursor still points to that page. In this case the first
57866 ** call to balance() repairs the tree, and the if(...) condition is
57867 ** never true.
57869 ** Otherwise, if the entry deleted was on an internal node page, then
57870 ** pCur is pointing to the leaf page from which a cell was removed to
57871 ** replace the cell deleted from the internal node. This is slightly
57872 ** tricky as the leaf node may be underfull, and the internal node may
57873 ** be either under or overfull. In this case run the balancing algorithm
57874 ** on the leaf node first. If the balance proceeds far enough up the
57875 ** tree that we can be sure that any problem in the internal node has
57876 ** been corrected, so be it. Otherwise, after balancing the leaf node,
57877 ** walk the cursor up the tree to the internal node and balance it as
57878 ** well. */
57879 rc = balance(pCur);
57880 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
57881 while( pCur->iPage>iCellDepth ){
57882 releasePage(pCur->apPage[pCur->iPage--]);
57884 rc = balance(pCur);
57887 if( rc==SQLITE_OK ){
57888 moveToRoot(pCur);
57890 return rc;
57894 ** Create a new BTree table. Write into *piTable the page
57895 ** number for the root page of the new table.
57897 ** The type of type is determined by the flags parameter. Only the
57898 ** following values of flags are currently in use. Other values for
57899 ** flags might not work:
57901 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
57902 ** BTREE_ZERODATA Used for SQL indices
57904 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
57905 BtShared *pBt = p->pBt;
57906 MemPage *pRoot;
57907 Pgno pgnoRoot;
57908 int rc;
57909 int ptfFlags; /* Page-type flage for the root page of new table */
57911 assert( sqlite3BtreeHoldsMutex(p) );
57912 assert( pBt->inTransaction==TRANS_WRITE );
57913 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
57915 #ifdef SQLITE_OMIT_AUTOVACUUM
57916 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
57917 if( rc ){
57918 return rc;
57920 #else
57921 if( pBt->autoVacuum ){
57922 Pgno pgnoMove; /* Move a page here to make room for the root-page */
57923 MemPage *pPageMove; /* The page to move to. */
57925 /* Creating a new table may probably require moving an existing database
57926 ** to make room for the new tables root page. In case this page turns
57927 ** out to be an overflow page, delete all overflow page-map caches
57928 ** held by open cursors.
57930 invalidateAllOverflowCache(pBt);
57932 /* Read the value of meta[3] from the database to determine where the
57933 ** root page of the new table should go. meta[3] is the largest root-page
57934 ** created so far, so the new root-page is (meta[3]+1).
57936 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
57937 pgnoRoot++;
57939 /* The new root-page may not be allocated on a pointer-map page, or the
57940 ** PENDING_BYTE page.
57942 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
57943 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
57944 pgnoRoot++;
57946 assert( pgnoRoot>=3 );
57948 /* Allocate a page. The page that currently resides at pgnoRoot will
57949 ** be moved to the allocated page (unless the allocated page happens
57950 ** to reside at pgnoRoot).
57952 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
57953 if( rc!=SQLITE_OK ){
57954 return rc;
57957 if( pgnoMove!=pgnoRoot ){
57958 /* pgnoRoot is the page that will be used for the root-page of
57959 ** the new table (assuming an error did not occur). But we were
57960 ** allocated pgnoMove. If required (i.e. if it was not allocated
57961 ** by extending the file), the current page at position pgnoMove
57962 ** is already journaled.
57964 u8 eType = 0;
57965 Pgno iPtrPage = 0;
57967 /* Save the positions of any open cursors. This is required in
57968 ** case they are holding a reference to an xFetch reference
57969 ** corresponding to page pgnoRoot. */
57970 rc = saveAllCursors(pBt, 0, 0);
57971 releasePage(pPageMove);
57972 if( rc!=SQLITE_OK ){
57973 return rc;
57976 /* Move the page currently at pgnoRoot to pgnoMove. */
57977 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
57978 if( rc!=SQLITE_OK ){
57979 return rc;
57981 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
57982 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
57983 rc = SQLITE_CORRUPT_BKPT;
57985 if( rc!=SQLITE_OK ){
57986 releasePage(pRoot);
57987 return rc;
57989 assert( eType!=PTRMAP_ROOTPAGE );
57990 assert( eType!=PTRMAP_FREEPAGE );
57991 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
57992 releasePage(pRoot);
57994 /* Obtain the page at pgnoRoot */
57995 if( rc!=SQLITE_OK ){
57996 return rc;
57998 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
57999 if( rc!=SQLITE_OK ){
58000 return rc;
58002 rc = sqlite3PagerWrite(pRoot->pDbPage);
58003 if( rc!=SQLITE_OK ){
58004 releasePage(pRoot);
58005 return rc;
58007 }else{
58008 pRoot = pPageMove;
58011 /* Update the pointer-map and meta-data with the new root-page number. */
58012 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
58013 if( rc ){
58014 releasePage(pRoot);
58015 return rc;
58018 /* When the new root page was allocated, page 1 was made writable in
58019 ** order either to increase the database filesize, or to decrement the
58020 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
58022 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
58023 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
58024 if( NEVER(rc) ){
58025 releasePage(pRoot);
58026 return rc;
58029 }else{
58030 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
58031 if( rc ) return rc;
58033 #endif
58034 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
58035 if( createTabFlags & BTREE_INTKEY ){
58036 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
58037 }else{
58038 ptfFlags = PTF_ZERODATA | PTF_LEAF;
58040 zeroPage(pRoot, ptfFlags);
58041 sqlite3PagerUnref(pRoot->pDbPage);
58042 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
58043 *piTable = (int)pgnoRoot;
58044 return SQLITE_OK;
58046 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
58047 int rc;
58048 sqlite3BtreeEnter(p);
58049 rc = btreeCreateTable(p, piTable, flags);
58050 sqlite3BtreeLeave(p);
58051 return rc;
58055 ** Erase the given database page and all its children. Return
58056 ** the page to the freelist.
58058 static int clearDatabasePage(
58059 BtShared *pBt, /* The BTree that contains the table */
58060 Pgno pgno, /* Page number to clear */
58061 int freePageFlag, /* Deallocate page if true */
58062 int *pnChange /* Add number of Cells freed to this counter */
58064 MemPage *pPage;
58065 int rc;
58066 unsigned char *pCell;
58067 int i;
58068 int hdr;
58070 assert( sqlite3_mutex_held(pBt->mutex) );
58071 if( pgno>btreePagecount(pBt) ){
58072 return SQLITE_CORRUPT_BKPT;
58075 rc = getAndInitPage(pBt, pgno, &pPage, 0);
58076 if( rc ) return rc;
58077 hdr = pPage->hdrOffset;
58078 for(i=0; i<pPage->nCell; i++){
58079 pCell = findCell(pPage, i);
58080 if( !pPage->leaf ){
58081 rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
58082 if( rc ) goto cleardatabasepage_out;
58084 rc = clearCell(pPage, pCell);
58085 if( rc ) goto cleardatabasepage_out;
58087 if( !pPage->leaf ){
58088 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
58089 if( rc ) goto cleardatabasepage_out;
58090 }else if( pnChange ){
58091 assert( pPage->intKey );
58092 *pnChange += pPage->nCell;
58094 if( freePageFlag ){
58095 freePage(pPage, &rc);
58096 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
58097 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
58100 cleardatabasepage_out:
58101 releasePage(pPage);
58102 return rc;
58106 ** Delete all information from a single table in the database. iTable is
58107 ** the page number of the root of the table. After this routine returns,
58108 ** the root page is empty, but still exists.
58110 ** This routine will fail with SQLITE_LOCKED if there are any open
58111 ** read cursors on the table. Open write cursors are moved to the
58112 ** root of the table.
58114 ** If pnChange is not NULL, then table iTable must be an intkey table. The
58115 ** integer value pointed to by pnChange is incremented by the number of
58116 ** entries in the table.
58118 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
58119 int rc;
58120 BtShared *pBt = p->pBt;
58121 sqlite3BtreeEnter(p);
58122 assert( p->inTrans==TRANS_WRITE );
58124 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
58126 if( SQLITE_OK==rc ){
58127 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
58128 ** is the root of a table b-tree - if it is not, the following call is
58129 ** a no-op). */
58130 invalidateIncrblobCursors(p, 0, 1);
58131 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
58133 sqlite3BtreeLeave(p);
58134 return rc;
58138 ** Erase all information in a table and add the root of the table to
58139 ** the freelist. Except, the root of the principle table (the one on
58140 ** page 1) is never added to the freelist.
58142 ** This routine will fail with SQLITE_LOCKED if there are any open
58143 ** cursors on the table.
58145 ** If AUTOVACUUM is enabled and the page at iTable is not the last
58146 ** root page in the database file, then the last root page
58147 ** in the database file is moved into the slot formerly occupied by
58148 ** iTable and that last slot formerly occupied by the last root page
58149 ** is added to the freelist instead of iTable. In this say, all
58150 ** root pages are kept at the beginning of the database file, which
58151 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
58152 ** page number that used to be the last root page in the file before
58153 ** the move. If no page gets moved, *piMoved is set to 0.
58154 ** The last root page is recorded in meta[3] and the value of
58155 ** meta[3] is updated by this procedure.
58157 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
58158 int rc;
58159 MemPage *pPage = 0;
58160 BtShared *pBt = p->pBt;
58162 assert( sqlite3BtreeHoldsMutex(p) );
58163 assert( p->inTrans==TRANS_WRITE );
58165 /* It is illegal to drop a table if any cursors are open on the
58166 ** database. This is because in auto-vacuum mode the backend may
58167 ** need to move another root-page to fill a gap left by the deleted
58168 ** root page. If an open cursor was using this page a problem would
58169 ** occur.
58171 ** This error is caught long before control reaches this point.
58173 if( NEVER(pBt->pCursor) ){
58174 sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
58175 return SQLITE_LOCKED_SHAREDCACHE;
58178 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
58179 if( rc ) return rc;
58180 rc = sqlite3BtreeClearTable(p, iTable, 0);
58181 if( rc ){
58182 releasePage(pPage);
58183 return rc;
58186 *piMoved = 0;
58188 if( iTable>1 ){
58189 #ifdef SQLITE_OMIT_AUTOVACUUM
58190 freePage(pPage, &rc);
58191 releasePage(pPage);
58192 #else
58193 if( pBt->autoVacuum ){
58194 Pgno maxRootPgno;
58195 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
58197 if( iTable==maxRootPgno ){
58198 /* If the table being dropped is the table with the largest root-page
58199 ** number in the database, put the root page on the free list.
58201 freePage(pPage, &rc);
58202 releasePage(pPage);
58203 if( rc!=SQLITE_OK ){
58204 return rc;
58206 }else{
58207 /* The table being dropped does not have the largest root-page
58208 ** number in the database. So move the page that does into the
58209 ** gap left by the deleted root-page.
58211 MemPage *pMove;
58212 releasePage(pPage);
58213 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
58214 if( rc!=SQLITE_OK ){
58215 return rc;
58217 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
58218 releasePage(pMove);
58219 if( rc!=SQLITE_OK ){
58220 return rc;
58222 pMove = 0;
58223 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
58224 freePage(pMove, &rc);
58225 releasePage(pMove);
58226 if( rc!=SQLITE_OK ){
58227 return rc;
58229 *piMoved = maxRootPgno;
58232 /* Set the new 'max-root-page' value in the database header. This
58233 ** is the old value less one, less one more if that happens to
58234 ** be a root-page number, less one again if that is the
58235 ** PENDING_BYTE_PAGE.
58237 maxRootPgno--;
58238 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
58239 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
58240 maxRootPgno--;
58242 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
58244 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
58245 }else{
58246 freePage(pPage, &rc);
58247 releasePage(pPage);
58249 #endif
58250 }else{
58251 /* If sqlite3BtreeDropTable was called on page 1.
58252 ** This really never should happen except in a corrupt
58253 ** database.
58255 zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
58256 releasePage(pPage);
58258 return rc;
58260 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
58261 int rc;
58262 sqlite3BtreeEnter(p);
58263 rc = btreeDropTable(p, iTable, piMoved);
58264 sqlite3BtreeLeave(p);
58265 return rc;
58270 ** This function may only be called if the b-tree connection already
58271 ** has a read or write transaction open on the database.
58273 ** Read the meta-information out of a database file. Meta[0]
58274 ** is the number of free pages currently in the database. Meta[1]
58275 ** through meta[15] are available for use by higher layers. Meta[0]
58276 ** is read-only, the others are read/write.
58278 ** The schema layer numbers meta values differently. At the schema
58279 ** layer (and the SetCookie and ReadCookie opcodes) the number of
58280 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
58282 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
58283 BtShared *pBt = p->pBt;
58285 sqlite3BtreeEnter(p);
58286 assert( p->inTrans>TRANS_NONE );
58287 assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
58288 assert( pBt->pPage1 );
58289 assert( idx>=0 && idx<=15 );
58291 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
58293 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
58294 ** database, mark the database as read-only. */
58295 #ifdef SQLITE_OMIT_AUTOVACUUM
58296 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
58297 pBt->btsFlags |= BTS_READ_ONLY;
58299 #endif
58301 sqlite3BtreeLeave(p);
58305 ** Write meta-information back into the database. Meta[0] is
58306 ** read-only and may not be written.
58308 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
58309 BtShared *pBt = p->pBt;
58310 unsigned char *pP1;
58311 int rc;
58312 assert( idx>=1 && idx<=15 );
58313 sqlite3BtreeEnter(p);
58314 assert( p->inTrans==TRANS_WRITE );
58315 assert( pBt->pPage1!=0 );
58316 pP1 = pBt->pPage1->aData;
58317 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58318 if( rc==SQLITE_OK ){
58319 put4byte(&pP1[36 + idx*4], iMeta);
58320 #ifndef SQLITE_OMIT_AUTOVACUUM
58321 if( idx==BTREE_INCR_VACUUM ){
58322 assert( pBt->autoVacuum || iMeta==0 );
58323 assert( iMeta==0 || iMeta==1 );
58324 pBt->incrVacuum = (u8)iMeta;
58326 #endif
58328 sqlite3BtreeLeave(p);
58329 return rc;
58332 #ifndef SQLITE_OMIT_BTREECOUNT
58334 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
58335 ** number of entries in the b-tree and write the result to *pnEntry.
58337 ** SQLITE_OK is returned if the operation is successfully executed.
58338 ** Otherwise, if an error is encountered (i.e. an IO error or database
58339 ** corruption) an SQLite error code is returned.
58341 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
58342 i64 nEntry = 0; /* Value to return in *pnEntry */
58343 int rc; /* Return code */
58345 if( pCur->pgnoRoot==0 ){
58346 *pnEntry = 0;
58347 return SQLITE_OK;
58349 rc = moveToRoot(pCur);
58351 /* Unless an error occurs, the following loop runs one iteration for each
58352 ** page in the B-Tree structure (not including overflow pages).
58354 while( rc==SQLITE_OK ){
58355 int iIdx; /* Index of child node in parent */
58356 MemPage *pPage; /* Current page of the b-tree */
58358 /* If this is a leaf page or the tree is not an int-key tree, then
58359 ** this page contains countable entries. Increment the entry counter
58360 ** accordingly.
58362 pPage = pCur->apPage[pCur->iPage];
58363 if( pPage->leaf || !pPage->intKey ){
58364 nEntry += pPage->nCell;
58367 /* pPage is a leaf node. This loop navigates the cursor so that it
58368 ** points to the first interior cell that it points to the parent of
58369 ** the next page in the tree that has not yet been visited. The
58370 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
58371 ** of the page, or to the number of cells in the page if the next page
58372 ** to visit is the right-child of its parent.
58374 ** If all pages in the tree have been visited, return SQLITE_OK to the
58375 ** caller.
58377 if( pPage->leaf ){
58378 do {
58379 if( pCur->iPage==0 ){
58380 /* All pages of the b-tree have been visited. Return successfully. */
58381 *pnEntry = nEntry;
58382 return SQLITE_OK;
58384 moveToParent(pCur);
58385 }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
58387 pCur->aiIdx[pCur->iPage]++;
58388 pPage = pCur->apPage[pCur->iPage];
58391 /* Descend to the child node of the cell that the cursor currently
58392 ** points at. This is the right-child if (iIdx==pPage->nCell).
58394 iIdx = pCur->aiIdx[pCur->iPage];
58395 if( iIdx==pPage->nCell ){
58396 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
58397 }else{
58398 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
58402 /* An error has occurred. Return an error code. */
58403 return rc;
58405 #endif
58408 ** Return the pager associated with a BTree. This routine is used for
58409 ** testing and debugging only.
58411 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
58412 return p->pBt->pPager;
58415 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
58417 ** Append a message to the error message string.
58419 static void checkAppendMsg(
58420 IntegrityCk *pCheck,
58421 char *zMsg1,
58422 const char *zFormat,
58425 va_list ap;
58426 if( !pCheck->mxErr ) return;
58427 pCheck->mxErr--;
58428 pCheck->nErr++;
58429 va_start(ap, zFormat);
58430 if( pCheck->errMsg.nChar ){
58431 sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
58433 if( zMsg1 ){
58434 sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
58436 sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
58437 va_end(ap);
58438 if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
58439 pCheck->mallocFailed = 1;
58442 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58444 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
58447 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
58448 ** corresponds to page iPg is already set.
58450 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
58451 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
58452 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
58456 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
58458 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
58459 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
58460 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
58465 ** Add 1 to the reference count for page iPage. If this is the second
58466 ** reference to the page, add an error message to pCheck->zErrMsg.
58467 ** Return 1 if there are 2 ore more references to the page and 0 if
58468 ** if this is the first reference to the page.
58470 ** Also check that the page number is in bounds.
58472 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
58473 if( iPage==0 ) return 1;
58474 if( iPage>pCheck->nPage ){
58475 checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
58476 return 1;
58478 if( getPageReferenced(pCheck, iPage) ){
58479 checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
58480 return 1;
58482 setPageReferenced(pCheck, iPage);
58483 return 0;
58486 #ifndef SQLITE_OMIT_AUTOVACUUM
58488 ** Check that the entry in the pointer-map for page iChild maps to
58489 ** page iParent, pointer type ptrType. If not, append an error message
58490 ** to pCheck.
58492 static void checkPtrmap(
58493 IntegrityCk *pCheck, /* Integrity check context */
58494 Pgno iChild, /* Child page number */
58495 u8 eType, /* Expected pointer map type */
58496 Pgno iParent, /* Expected pointer map parent page number */
58497 char *zContext /* Context description (used for error msg) */
58499 int rc;
58500 u8 ePtrmapType;
58501 Pgno iPtrmapParent;
58503 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
58504 if( rc!=SQLITE_OK ){
58505 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
58506 checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
58507 return;
58510 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
58511 checkAppendMsg(pCheck, zContext,
58512 "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
58513 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
58516 #endif
58519 ** Check the integrity of the freelist or of an overflow page list.
58520 ** Verify that the number of pages on the list is N.
58522 static void checkList(
58523 IntegrityCk *pCheck, /* Integrity checking context */
58524 int isFreeList, /* True for a freelist. False for overflow page list */
58525 int iPage, /* Page number for first page in the list */
58526 int N, /* Expected number of pages in the list */
58527 char *zContext /* Context for error messages */
58529 int i;
58530 int expected = N;
58531 int iFirst = iPage;
58532 while( N-- > 0 && pCheck->mxErr ){
58533 DbPage *pOvflPage;
58534 unsigned char *pOvflData;
58535 if( iPage<1 ){
58536 checkAppendMsg(pCheck, zContext,
58537 "%d of %d pages missing from overflow list starting at %d",
58538 N+1, expected, iFirst);
58539 break;
58541 if( checkRef(pCheck, iPage, zContext) ) break;
58542 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
58543 checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
58544 break;
58546 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
58547 if( isFreeList ){
58548 int n = get4byte(&pOvflData[4]);
58549 #ifndef SQLITE_OMIT_AUTOVACUUM
58550 if( pCheck->pBt->autoVacuum ){
58551 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
58553 #endif
58554 if( n>(int)pCheck->pBt->usableSize/4-2 ){
58555 checkAppendMsg(pCheck, zContext,
58556 "freelist leaf count too big on page %d", iPage);
58557 N--;
58558 }else{
58559 for(i=0; i<n; i++){
58560 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
58561 #ifndef SQLITE_OMIT_AUTOVACUUM
58562 if( pCheck->pBt->autoVacuum ){
58563 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
58565 #endif
58566 checkRef(pCheck, iFreePage, zContext);
58568 N -= n;
58571 #ifndef SQLITE_OMIT_AUTOVACUUM
58572 else{
58573 /* If this database supports auto-vacuum and iPage is not the last
58574 ** page in this overflow list, check that the pointer-map entry for
58575 ** the following page matches iPage.
58577 if( pCheck->pBt->autoVacuum && N>0 ){
58578 i = get4byte(pOvflData);
58579 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
58582 #endif
58583 iPage = get4byte(pOvflData);
58584 sqlite3PagerUnref(pOvflPage);
58587 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58589 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
58591 ** Do various sanity checks on a single page of a tree. Return
58592 ** the tree depth. Root pages return 0. Parents of root pages
58593 ** return 1, and so forth.
58595 ** These checks are done:
58597 ** 1. Make sure that cells and freeblocks do not overlap
58598 ** but combine to completely cover the page.
58599 ** NO 2. Make sure cell keys are in order.
58600 ** NO 3. Make sure no key is less than or equal to zLowerBound.
58601 ** NO 4. Make sure no key is greater than or equal to zUpperBound.
58602 ** 5. Check the integrity of overflow pages.
58603 ** 6. Recursively call checkTreePage on all children.
58604 ** 7. Verify that the depth of all children is the same.
58605 ** 8. Make sure this page is at least 33% full or else it is
58606 ** the root of the tree.
58608 static int checkTreePage(
58609 IntegrityCk *pCheck, /* Context for the sanity check */
58610 int iPage, /* Page number of the page to check */
58611 char *zParentContext, /* Parent context */
58612 i64 *pnParentMinKey,
58613 i64 *pnParentMaxKey
58615 MemPage *pPage;
58616 int i, rc, depth, d2, pgno, cnt;
58617 int hdr, cellStart;
58618 int nCell;
58619 u8 *data;
58620 BtShared *pBt;
58621 int usableSize;
58622 char zContext[100];
58623 char *hit = 0;
58624 i64 nMinKey = 0;
58625 i64 nMaxKey = 0;
58627 sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
58629 /* Check that the page exists
58631 pBt = pCheck->pBt;
58632 usableSize = pBt->usableSize;
58633 if( iPage==0 ) return 0;
58634 if( checkRef(pCheck, iPage, zParentContext) ) return 0;
58635 if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
58636 checkAppendMsg(pCheck, zContext,
58637 "unable to get the page. error code=%d", rc);
58638 return 0;
58641 /* Clear MemPage.isInit to make sure the corruption detection code in
58642 ** btreeInitPage() is executed. */
58643 pPage->isInit = 0;
58644 if( (rc = btreeInitPage(pPage))!=0 ){
58645 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
58646 checkAppendMsg(pCheck, zContext,
58647 "btreeInitPage() returns error code %d", rc);
58648 releasePage(pPage);
58649 return 0;
58652 /* Check out all the cells.
58654 depth = 0;
58655 for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
58656 u8 *pCell;
58657 u32 sz;
58658 CellInfo info;
58660 /* Check payload overflow pages
58662 sqlite3_snprintf(sizeof(zContext), zContext,
58663 "On tree page %d cell %d: ", iPage, i);
58664 pCell = findCell(pPage,i);
58665 btreeParseCellPtr(pPage, pCell, &info);
58666 sz = info.nData;
58667 if( !pPage->intKey ) sz += (int)info.nKey;
58668 /* For intKey pages, check that the keys are in order.
58670 else if( i==0 ) nMinKey = nMaxKey = info.nKey;
58671 else{
58672 if( info.nKey <= nMaxKey ){
58673 checkAppendMsg(pCheck, zContext,
58674 "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
58676 nMaxKey = info.nKey;
58678 assert( sz==info.nPayload );
58679 if( (sz>info.nLocal)
58680 && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
58682 int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
58683 Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
58684 #ifndef SQLITE_OMIT_AUTOVACUUM
58685 if( pBt->autoVacuum ){
58686 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
58688 #endif
58689 checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
58692 /* Check sanity of left child page.
58694 if( !pPage->leaf ){
58695 pgno = get4byte(pCell);
58696 #ifndef SQLITE_OMIT_AUTOVACUUM
58697 if( pBt->autoVacuum ){
58698 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
58700 #endif
58701 d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
58702 if( i>0 && d2!=depth ){
58703 checkAppendMsg(pCheck, zContext, "Child page depth differs");
58705 depth = d2;
58709 if( !pPage->leaf ){
58710 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
58711 sqlite3_snprintf(sizeof(zContext), zContext,
58712 "On page %d at right child: ", iPage);
58713 #ifndef SQLITE_OMIT_AUTOVACUUM
58714 if( pBt->autoVacuum ){
58715 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
58717 #endif
58718 checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
58721 /* For intKey leaf pages, check that the min/max keys are in order
58722 ** with any left/parent/right pages.
58724 if( pPage->leaf && pPage->intKey ){
58725 /* if we are a left child page */
58726 if( pnParentMinKey ){
58727 /* if we are the left most child page */
58728 if( !pnParentMaxKey ){
58729 if( nMaxKey > *pnParentMinKey ){
58730 checkAppendMsg(pCheck, zContext,
58731 "Rowid %lld out of order (max larger than parent min of %lld)",
58732 nMaxKey, *pnParentMinKey);
58734 }else{
58735 if( nMinKey <= *pnParentMinKey ){
58736 checkAppendMsg(pCheck, zContext,
58737 "Rowid %lld out of order (min less than parent min of %lld)",
58738 nMinKey, *pnParentMinKey);
58740 if( nMaxKey > *pnParentMaxKey ){
58741 checkAppendMsg(pCheck, zContext,
58742 "Rowid %lld out of order (max larger than parent max of %lld)",
58743 nMaxKey, *pnParentMaxKey);
58745 *pnParentMinKey = nMaxKey;
58747 /* else if we're a right child page */
58748 } else if( pnParentMaxKey ){
58749 if( nMinKey <= *pnParentMaxKey ){
58750 checkAppendMsg(pCheck, zContext,
58751 "Rowid %lld out of order (min less than parent max of %lld)",
58752 nMinKey, *pnParentMaxKey);
58757 /* Check for complete coverage of the page
58759 data = pPage->aData;
58760 hdr = pPage->hdrOffset;
58761 hit = sqlite3PageMalloc( pBt->pageSize );
58762 if( hit==0 ){
58763 pCheck->mallocFailed = 1;
58764 }else{
58765 int contentOffset = get2byteNotZero(&data[hdr+5]);
58766 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
58767 memset(hit+contentOffset, 0, usableSize-contentOffset);
58768 memset(hit, 1, contentOffset);
58769 nCell = get2byte(&data[hdr+3]);
58770 cellStart = hdr + 12 - 4*pPage->leaf;
58771 for(i=0; i<nCell; i++){
58772 int pc = get2byte(&data[cellStart+i*2]);
58773 u32 size = 65536;
58774 int j;
58775 if( pc<=usableSize-4 ){
58776 size = cellSizePtr(pPage, &data[pc]);
58778 if( (int)(pc+size-1)>=usableSize ){
58779 checkAppendMsg(pCheck, 0,
58780 "Corruption detected in cell %d on page %d",i,iPage);
58781 }else{
58782 for(j=pc+size-1; j>=pc; j--) hit[j]++;
58785 i = get2byte(&data[hdr+1]);
58786 while( i>0 ){
58787 int size, j;
58788 assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
58789 size = get2byte(&data[i+2]);
58790 assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
58791 for(j=i+size-1; j>=i; j--) hit[j]++;
58792 j = get2byte(&data[i]);
58793 assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
58794 assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
58795 i = j;
58797 for(i=cnt=0; i<usableSize; i++){
58798 if( hit[i]==0 ){
58799 cnt++;
58800 }else if( hit[i]>1 ){
58801 checkAppendMsg(pCheck, 0,
58802 "Multiple uses for byte %d of page %d", i, iPage);
58803 break;
58806 if( cnt!=data[hdr+7] ){
58807 checkAppendMsg(pCheck, 0,
58808 "Fragmentation of %d bytes reported as %d on page %d",
58809 cnt, data[hdr+7], iPage);
58812 sqlite3PageFree(hit);
58813 releasePage(pPage);
58814 return depth+1;
58816 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58818 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
58820 ** This routine does a complete check of the given BTree file. aRoot[] is
58821 ** an array of pages numbers were each page number is the root page of
58822 ** a table. nRoot is the number of entries in aRoot.
58824 ** A read-only or read-write transaction must be opened before calling
58825 ** this function.
58827 ** Write the number of error seen in *pnErr. Except for some memory
58828 ** allocation errors, an error message held in memory obtained from
58829 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
58830 ** returned. If a memory allocation error occurs, NULL is returned.
58832 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
58833 Btree *p, /* The btree to be checked */
58834 int *aRoot, /* An array of root pages numbers for individual trees */
58835 int nRoot, /* Number of entries in aRoot[] */
58836 int mxErr, /* Stop reporting errors after this many */
58837 int *pnErr /* Write number of errors seen to this variable */
58839 Pgno i;
58840 int nRef;
58841 IntegrityCk sCheck;
58842 BtShared *pBt = p->pBt;
58843 char zErr[100];
58845 sqlite3BtreeEnter(p);
58846 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
58847 nRef = sqlite3PagerRefcount(pBt->pPager);
58848 sCheck.pBt = pBt;
58849 sCheck.pPager = pBt->pPager;
58850 sCheck.nPage = btreePagecount(sCheck.pBt);
58851 sCheck.mxErr = mxErr;
58852 sCheck.nErr = 0;
58853 sCheck.mallocFailed = 0;
58854 *pnErr = 0;
58855 if( sCheck.nPage==0 ){
58856 sqlite3BtreeLeave(p);
58857 return 0;
58860 sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
58861 if( !sCheck.aPgRef ){
58862 *pnErr = 1;
58863 sqlite3BtreeLeave(p);
58864 return 0;
58866 i = PENDING_BYTE_PAGE(pBt);
58867 if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
58868 sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
58869 sCheck.errMsg.useMalloc = 2;
58871 /* Check the integrity of the freelist
58873 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
58874 get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
58876 /* Check all the tables.
58878 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
58879 if( aRoot[i]==0 ) continue;
58880 #ifndef SQLITE_OMIT_AUTOVACUUM
58881 if( pBt->autoVacuum && aRoot[i]>1 ){
58882 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
58884 #endif
58885 checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
58888 /* Make sure every page in the file is referenced
58890 for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
58891 #ifdef SQLITE_OMIT_AUTOVACUUM
58892 if( getPageReferenced(&sCheck, i)==0 ){
58893 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
58895 #else
58896 /* If the database supports auto-vacuum, make sure no tables contain
58897 ** references to pointer-map pages.
58899 if( getPageReferenced(&sCheck, i)==0 &&
58900 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
58901 checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
58903 if( getPageReferenced(&sCheck, i)!=0 &&
58904 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
58905 checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
58907 #endif
58910 /* Make sure this analysis did not leave any unref() pages.
58911 ** This is an internal consistency check; an integrity check
58912 ** of the integrity check.
58914 if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
58915 checkAppendMsg(&sCheck, 0,
58916 "Outstanding page count goes from %d to %d during this analysis",
58917 nRef, sqlite3PagerRefcount(pBt->pPager)
58921 /* Clean up and report errors.
58923 sqlite3BtreeLeave(p);
58924 sqlite3_free(sCheck.aPgRef);
58925 if( sCheck.mallocFailed ){
58926 sqlite3StrAccumReset(&sCheck.errMsg);
58927 *pnErr = sCheck.nErr+1;
58928 return 0;
58930 *pnErr = sCheck.nErr;
58931 if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
58932 return sqlite3StrAccumFinish(&sCheck.errMsg);
58934 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58937 ** Return the full pathname of the underlying database file. Return
58938 ** an empty string if the database is in-memory or a TEMP database.
58940 ** The pager filename is invariant as long as the pager is
58941 ** open so it is safe to access without the BtShared mutex.
58943 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
58944 assert( p->pBt->pPager!=0 );
58945 return sqlite3PagerFilename(p->pBt->pPager, 1);
58949 ** Return the pathname of the journal file for this database. The return
58950 ** value of this routine is the same regardless of whether the journal file
58951 ** has been created or not.
58953 ** The pager journal filename is invariant as long as the pager is
58954 ** open so it is safe to access without the BtShared mutex.
58956 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
58957 assert( p->pBt->pPager!=0 );
58958 return sqlite3PagerJournalname(p->pBt->pPager);
58962 ** Return non-zero if a transaction is active.
58964 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
58965 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
58966 return (p && (p->inTrans==TRANS_WRITE));
58969 #ifndef SQLITE_OMIT_WAL
58971 ** Run a checkpoint on the Btree passed as the first argument.
58973 ** Return SQLITE_LOCKED if this or any other connection has an open
58974 ** transaction on the shared-cache the argument Btree is connected to.
58976 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
58978 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
58979 int rc = SQLITE_OK;
58980 if( p ){
58981 BtShared *pBt = p->pBt;
58982 sqlite3BtreeEnter(p);
58983 if( pBt->inTransaction!=TRANS_NONE ){
58984 rc = SQLITE_LOCKED;
58985 }else{
58986 rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
58988 sqlite3BtreeLeave(p);
58990 return rc;
58992 #endif
58995 ** Return non-zero if a read (or write) transaction is active.
58997 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
58998 assert( p );
58999 assert( sqlite3_mutex_held(p->db->mutex) );
59000 return p->inTrans!=TRANS_NONE;
59003 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
59004 assert( p );
59005 assert( sqlite3_mutex_held(p->db->mutex) );
59006 return p->nBackup!=0;
59010 ** This function returns a pointer to a blob of memory associated with
59011 ** a single shared-btree. The memory is used by client code for its own
59012 ** purposes (for example, to store a high-level schema associated with
59013 ** the shared-btree). The btree layer manages reference counting issues.
59015 ** The first time this is called on a shared-btree, nBytes bytes of memory
59016 ** are allocated, zeroed, and returned to the caller. For each subsequent
59017 ** call the nBytes parameter is ignored and a pointer to the same blob
59018 ** of memory returned.
59020 ** If the nBytes parameter is 0 and the blob of memory has not yet been
59021 ** allocated, a null pointer is returned. If the blob has already been
59022 ** allocated, it is returned as normal.
59024 ** Just before the shared-btree is closed, the function passed as the
59025 ** xFree argument when the memory allocation was made is invoked on the
59026 ** blob of allocated memory. The xFree function should not call sqlite3_free()
59027 ** on the memory, the btree layer does that.
59029 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
59030 BtShared *pBt = p->pBt;
59031 sqlite3BtreeEnter(p);
59032 if( !pBt->pSchema && nBytes ){
59033 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
59034 pBt->xFreeSchema = xFree;
59036 sqlite3BtreeLeave(p);
59037 return pBt->pSchema;
59041 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
59042 ** btree as the argument handle holds an exclusive lock on the
59043 ** sqlite_master table. Otherwise SQLITE_OK.
59045 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
59046 int rc;
59047 assert( sqlite3_mutex_held(p->db->mutex) );
59048 sqlite3BtreeEnter(p);
59049 rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
59050 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
59051 sqlite3BtreeLeave(p);
59052 return rc;
59056 #ifndef SQLITE_OMIT_SHARED_CACHE
59058 ** Obtain a lock on the table whose root page is iTab. The
59059 ** lock is a write lock if isWritelock is true or a read lock
59060 ** if it is false.
59062 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
59063 int rc = SQLITE_OK;
59064 assert( p->inTrans!=TRANS_NONE );
59065 if( p->sharable ){
59066 u8 lockType = READ_LOCK + isWriteLock;
59067 assert( READ_LOCK+1==WRITE_LOCK );
59068 assert( isWriteLock==0 || isWriteLock==1 );
59070 sqlite3BtreeEnter(p);
59071 rc = querySharedCacheTableLock(p, iTab, lockType);
59072 if( rc==SQLITE_OK ){
59073 rc = setSharedCacheTableLock(p, iTab, lockType);
59075 sqlite3BtreeLeave(p);
59077 return rc;
59079 #endif
59081 #ifndef SQLITE_OMIT_INCRBLOB
59083 ** Argument pCsr must be a cursor opened for writing on an
59084 ** INTKEY table currently pointing at a valid table entry.
59085 ** This function modifies the data stored as part of that entry.
59087 ** Only the data content may only be modified, it is not possible to
59088 ** change the length of the data stored. If this function is called with
59089 ** parameters that attempt to write past the end of the existing data,
59090 ** no modifications are made and SQLITE_CORRUPT is returned.
59092 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
59093 int rc;
59094 assert( cursorHoldsMutex(pCsr) );
59095 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
59096 assert( pCsr->isIncrblobHandle );
59098 rc = restoreCursorPosition(pCsr);
59099 if( rc!=SQLITE_OK ){
59100 return rc;
59102 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
59103 if( pCsr->eState!=CURSOR_VALID ){
59104 return SQLITE_ABORT;
59107 /* Save the positions of all other cursors open on this table. This is
59108 ** required in case any of them are holding references to an xFetch
59109 ** version of the b-tree page modified by the accessPayload call below.
59111 ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
59112 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
59113 ** saveAllCursors can only return SQLITE_OK.
59115 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
59116 assert( rc==SQLITE_OK );
59118 /* Check some assumptions:
59119 ** (a) the cursor is open for writing,
59120 ** (b) there is a read/write transaction open,
59121 ** (c) the connection holds a write-lock on the table (if required),
59122 ** (d) there are no conflicting read-locks, and
59123 ** (e) the cursor points at a valid row of an intKey table.
59125 if( !pCsr->wrFlag ){
59126 return SQLITE_READONLY;
59128 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
59129 && pCsr->pBt->inTransaction==TRANS_WRITE );
59130 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
59131 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
59132 assert( pCsr->apPage[pCsr->iPage]->intKey );
59134 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
59138 ** Set a flag on this cursor to cache the locations of pages from the
59139 ** overflow list for the current row. This is used by cursors opened
59140 ** for incremental blob IO only.
59142 ** This function sets a flag only. The actual page location cache
59143 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
59144 ** accessPayload() (the worker function for sqlite3BtreeData() and
59145 ** sqlite3BtreePutData()).
59147 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
59148 assert( cursorHoldsMutex(pCur) );
59149 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
59150 invalidateOverflowCache(pCur);
59151 pCur->isIncrblobHandle = 1;
59153 #endif
59156 ** Set both the "read version" (single byte at byte offset 18) and
59157 ** "write version" (single byte at byte offset 19) fields in the database
59158 ** header to iVersion.
59160 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
59161 BtShared *pBt = pBtree->pBt;
59162 int rc; /* Return code */
59164 assert( iVersion==1 || iVersion==2 );
59166 /* If setting the version fields to 1, do not automatically open the
59167 ** WAL connection, even if the version fields are currently set to 2.
59169 pBt->btsFlags &= ~BTS_NO_WAL;
59170 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
59172 rc = sqlite3BtreeBeginTrans(pBtree, 0);
59173 if( rc==SQLITE_OK ){
59174 u8 *aData = pBt->pPage1->aData;
59175 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
59176 rc = sqlite3BtreeBeginTrans(pBtree, 2);
59177 if( rc==SQLITE_OK ){
59178 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
59179 if( rc==SQLITE_OK ){
59180 aData[18] = (u8)iVersion;
59181 aData[19] = (u8)iVersion;
59187 pBt->btsFlags &= ~BTS_NO_WAL;
59188 return rc;
59192 ** set the mask of hint flags for cursor pCsr. Currently the only valid
59193 ** values are 0 and BTREE_BULKLOAD.
59195 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
59196 assert( mask==BTREE_BULKLOAD || mask==0 );
59197 pCsr->hints = mask;
59200 /************** End of btree.c ***********************************************/
59201 /************** Begin file backup.c ******************************************/
59203 ** 2009 January 28
59205 ** The author disclaims copyright to this source code. In place of
59206 ** a legal notice, here is a blessing:
59208 ** May you do good and not evil.
59209 ** May you find forgiveness for yourself and forgive others.
59210 ** May you share freely, never taking more than you give.
59212 *************************************************************************
59213 ** This file contains the implementation of the sqlite3_backup_XXX()
59214 ** API functions and the related features.
59218 ** Structure allocated for each backup operation.
59220 struct sqlite3_backup {
59221 sqlite3* pDestDb; /* Destination database handle */
59222 Btree *pDest; /* Destination b-tree file */
59223 u32 iDestSchema; /* Original schema cookie in destination */
59224 int bDestLocked; /* True once a write-transaction is open on pDest */
59226 Pgno iNext; /* Page number of the next source page to copy */
59227 sqlite3* pSrcDb; /* Source database handle */
59228 Btree *pSrc; /* Source b-tree file */
59230 int rc; /* Backup process error code */
59232 /* These two variables are set by every call to backup_step(). They are
59233 ** read by calls to backup_remaining() and backup_pagecount().
59235 Pgno nRemaining; /* Number of pages left to copy */
59236 Pgno nPagecount; /* Total number of pages to copy */
59238 int isAttached; /* True once backup has been registered with pager */
59239 sqlite3_backup *pNext; /* Next backup associated with source pager */
59243 ** THREAD SAFETY NOTES:
59245 ** Once it has been created using backup_init(), a single sqlite3_backup
59246 ** structure may be accessed via two groups of thread-safe entry points:
59248 ** * Via the sqlite3_backup_XXX() API function backup_step() and
59249 ** backup_finish(). Both these functions obtain the source database
59250 ** handle mutex and the mutex associated with the source BtShared
59251 ** structure, in that order.
59253 ** * Via the BackupUpdate() and BackupRestart() functions, which are
59254 ** invoked by the pager layer to report various state changes in
59255 ** the page cache associated with the source database. The mutex
59256 ** associated with the source database BtShared structure will always
59257 ** be held when either of these functions are invoked.
59259 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
59260 ** backup_pagecount() are not thread-safe functions. If they are called
59261 ** while some other thread is calling backup_step() or backup_finish(),
59262 ** the values returned may be invalid. There is no way for a call to
59263 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
59264 ** or backup_pagecount().
59266 ** Depending on the SQLite configuration, the database handles and/or
59267 ** the Btree objects may have their own mutexes that require locking.
59268 ** Non-sharable Btrees (in-memory databases for example), do not have
59269 ** associated mutexes.
59273 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
59274 ** in connection handle pDb. If such a database cannot be found, return
59275 ** a NULL pointer and write an error message to pErrorDb.
59277 ** If the "temp" database is requested, it may need to be opened by this
59278 ** function. If an error occurs while doing so, return 0 and write an
59279 ** error message to pErrorDb.
59281 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
59282 int i = sqlite3FindDbName(pDb, zDb);
59284 if( i==1 ){
59285 Parse *pParse;
59286 int rc = 0;
59287 pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
59288 if( pParse==0 ){
59289 sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
59290 rc = SQLITE_NOMEM;
59291 }else{
59292 pParse->db = pDb;
59293 if( sqlite3OpenTempDatabase(pParse) ){
59294 sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
59295 rc = SQLITE_ERROR;
59297 sqlite3DbFree(pErrorDb, pParse->zErrMsg);
59298 sqlite3ParserReset(pParse);
59299 sqlite3StackFree(pErrorDb, pParse);
59301 if( rc ){
59302 return 0;
59306 if( i<0 ){
59307 sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
59308 return 0;
59311 return pDb->aDb[i].pBt;
59315 ** Attempt to set the page size of the destination to match the page size
59316 ** of the source.
59318 static int setDestPgsz(sqlite3_backup *p){
59319 int rc;
59320 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
59321 return rc;
59325 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
59326 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
59327 ** a pointer to the new sqlite3_backup object.
59329 ** If an error occurs, NULL is returned and an error code and error message
59330 ** stored in database handle pDestDb.
59332 SQLITE_API sqlite3_backup *sqlite3_backup_init(
59333 sqlite3* pDestDb, /* Database to write to */
59334 const char *zDestDb, /* Name of database within pDestDb */
59335 sqlite3* pSrcDb, /* Database connection to read from */
59336 const char *zSrcDb /* Name of database within pSrcDb */
59338 sqlite3_backup *p; /* Value to return */
59340 /* Lock the source database handle. The destination database
59341 ** handle is not locked in this routine, but it is locked in
59342 ** sqlite3_backup_step(). The user is required to ensure that no
59343 ** other thread accesses the destination handle for the duration
59344 ** of the backup operation. Any attempt to use the destination
59345 ** database connection while a backup is in progress may cause
59346 ** a malfunction or a deadlock.
59348 sqlite3_mutex_enter(pSrcDb->mutex);
59349 sqlite3_mutex_enter(pDestDb->mutex);
59351 if( pSrcDb==pDestDb ){
59352 sqlite3Error(
59353 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
59355 p = 0;
59356 }else {
59357 /* Allocate space for a new sqlite3_backup object...
59358 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
59359 ** call to sqlite3_backup_init() and is destroyed by a call to
59360 ** sqlite3_backup_finish(). */
59361 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
59362 if( !p ){
59363 sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
59367 /* If the allocation succeeded, populate the new object. */
59368 if( p ){
59369 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
59370 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
59371 p->pDestDb = pDestDb;
59372 p->pSrcDb = pSrcDb;
59373 p->iNext = 1;
59374 p->isAttached = 0;
59376 if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
59377 /* One (or both) of the named databases did not exist or an OOM
59378 ** error was hit. The error has already been written into the
59379 ** pDestDb handle. All that is left to do here is free the
59380 ** sqlite3_backup structure.
59382 sqlite3_free(p);
59383 p = 0;
59386 if( p ){
59387 p->pSrc->nBackup++;
59390 sqlite3_mutex_leave(pDestDb->mutex);
59391 sqlite3_mutex_leave(pSrcDb->mutex);
59392 return p;
59396 ** Argument rc is an SQLite error code. Return true if this error is
59397 ** considered fatal if encountered during a backup operation. All errors
59398 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
59400 static int isFatalError(int rc){
59401 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
59405 ** Parameter zSrcData points to a buffer containing the data for
59406 ** page iSrcPg from the source database. Copy this data into the
59407 ** destination database.
59409 static int backupOnePage(
59410 sqlite3_backup *p, /* Backup handle */
59411 Pgno iSrcPg, /* Source database page to backup */
59412 const u8 *zSrcData, /* Source database page data */
59413 int bUpdate /* True for an update, false otherwise */
59415 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
59416 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
59417 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
59418 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
59419 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
59420 #ifdef SQLITE_HAS_CODEC
59421 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
59422 ** guaranteed that the shared-mutex is held by this thread, handle
59423 ** p->pSrc may not actually be the owner. */
59424 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
59425 int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
59426 #endif
59427 int rc = SQLITE_OK;
59428 i64 iOff;
59430 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
59431 assert( p->bDestLocked );
59432 assert( !isFatalError(p->rc) );
59433 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
59434 assert( zSrcData );
59436 /* Catch the case where the destination is an in-memory database and the
59437 ** page sizes of the source and destination differ.
59439 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
59440 rc = SQLITE_READONLY;
59443 #ifdef SQLITE_HAS_CODEC
59444 /* Backup is not possible if the page size of the destination is changing
59445 ** and a codec is in use.
59447 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
59448 rc = SQLITE_READONLY;
59451 /* Backup is not possible if the number of bytes of reserve space differ
59452 ** between source and destination. If there is a difference, try to
59453 ** fix the destination to agree with the source. If that is not possible,
59454 ** then the backup cannot proceed.
59456 if( nSrcReserve!=nDestReserve ){
59457 u32 newPgsz = nSrcPgsz;
59458 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
59459 if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
59461 #endif
59463 /* This loop runs once for each destination page spanned by the source
59464 ** page. For each iteration, variable iOff is set to the byte offset
59465 ** of the destination page.
59467 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
59468 DbPage *pDestPg = 0;
59469 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
59470 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
59471 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
59472 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
59474 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
59475 u8 *zDestData = sqlite3PagerGetData(pDestPg);
59476 u8 *zOut = &zDestData[iOff%nDestPgsz];
59478 /* Copy the data from the source page into the destination page.
59479 ** Then clear the Btree layer MemPage.isInit flag. Both this module
59480 ** and the pager code use this trick (clearing the first byte
59481 ** of the page 'extra' space to invalidate the Btree layers
59482 ** cached parse of the page). MemPage.isInit is marked
59483 ** "MUST BE FIRST" for this purpose.
59485 memcpy(zOut, zIn, nCopy);
59486 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
59487 if( iOff==0 && bUpdate==0 ){
59488 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
59491 sqlite3PagerUnref(pDestPg);
59494 return rc;
59498 ** If pFile is currently larger than iSize bytes, then truncate it to
59499 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
59500 ** this function is a no-op.
59502 ** Return SQLITE_OK if everything is successful, or an SQLite error
59503 ** code if an error occurs.
59505 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
59506 i64 iCurrent;
59507 int rc = sqlite3OsFileSize(pFile, &iCurrent);
59508 if( rc==SQLITE_OK && iCurrent>iSize ){
59509 rc = sqlite3OsTruncate(pFile, iSize);
59511 return rc;
59515 ** Register this backup object with the associated source pager for
59516 ** callbacks when pages are changed or the cache invalidated.
59518 static void attachBackupObject(sqlite3_backup *p){
59519 sqlite3_backup **pp;
59520 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
59521 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
59522 p->pNext = *pp;
59523 *pp = p;
59524 p->isAttached = 1;
59528 ** Copy nPage pages from the source b-tree to the destination.
59530 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
59531 int rc;
59532 int destMode; /* Destination journal mode */
59533 int pgszSrc = 0; /* Source page size */
59534 int pgszDest = 0; /* Destination page size */
59536 sqlite3_mutex_enter(p->pSrcDb->mutex);
59537 sqlite3BtreeEnter(p->pSrc);
59538 if( p->pDestDb ){
59539 sqlite3_mutex_enter(p->pDestDb->mutex);
59542 rc = p->rc;
59543 if( !isFatalError(rc) ){
59544 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
59545 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
59546 int ii; /* Iterator variable */
59547 int nSrcPage = -1; /* Size of source db in pages */
59548 int bCloseTrans = 0; /* True if src db requires unlocking */
59550 /* If the source pager is currently in a write-transaction, return
59551 ** SQLITE_BUSY immediately.
59553 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
59554 rc = SQLITE_BUSY;
59555 }else{
59556 rc = SQLITE_OK;
59559 /* Lock the destination database, if it is not locked already. */
59560 if( SQLITE_OK==rc && p->bDestLocked==0
59561 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
59563 p->bDestLocked = 1;
59564 sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
59567 /* If there is no open read-transaction on the source database, open
59568 ** one now. If a transaction is opened here, then it will be closed
59569 ** before this function exits.
59571 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
59572 rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
59573 bCloseTrans = 1;
59576 /* Do not allow backup if the destination database is in WAL mode
59577 ** and the page sizes are different between source and destination */
59578 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
59579 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
59580 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
59581 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
59582 rc = SQLITE_READONLY;
59585 /* Now that there is a read-lock on the source database, query the
59586 ** source pager for the number of pages in the database.
59588 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
59589 assert( nSrcPage>=0 );
59590 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
59591 const Pgno iSrcPg = p->iNext; /* Source page number */
59592 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
59593 DbPage *pSrcPg; /* Source page object */
59594 rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
59595 PAGER_GET_READONLY);
59596 if( rc==SQLITE_OK ){
59597 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
59598 sqlite3PagerUnref(pSrcPg);
59601 p->iNext++;
59603 if( rc==SQLITE_OK ){
59604 p->nPagecount = nSrcPage;
59605 p->nRemaining = nSrcPage+1-p->iNext;
59606 if( p->iNext>(Pgno)nSrcPage ){
59607 rc = SQLITE_DONE;
59608 }else if( !p->isAttached ){
59609 attachBackupObject(p);
59613 /* Update the schema version field in the destination database. This
59614 ** is to make sure that the schema-version really does change in
59615 ** the case where the source and destination databases have the
59616 ** same schema version.
59618 if( rc==SQLITE_DONE ){
59619 if( nSrcPage==0 ){
59620 rc = sqlite3BtreeNewDb(p->pDest);
59621 nSrcPage = 1;
59623 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
59624 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
59626 if( rc==SQLITE_OK ){
59627 if( p->pDestDb ){
59628 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
59630 if( destMode==PAGER_JOURNALMODE_WAL ){
59631 rc = sqlite3BtreeSetVersion(p->pDest, 2);
59634 if( rc==SQLITE_OK ){
59635 int nDestTruncate;
59636 /* Set nDestTruncate to the final number of pages in the destination
59637 ** database. The complication here is that the destination page
59638 ** size may be different to the source page size.
59640 ** If the source page size is smaller than the destination page size,
59641 ** round up. In this case the call to sqlite3OsTruncate() below will
59642 ** fix the size of the file. However it is important to call
59643 ** sqlite3PagerTruncateImage() here so that any pages in the
59644 ** destination file that lie beyond the nDestTruncate page mark are
59645 ** journalled by PagerCommitPhaseOne() before they are destroyed
59646 ** by the file truncation.
59648 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
59649 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
59650 if( pgszSrc<pgszDest ){
59651 int ratio = pgszDest/pgszSrc;
59652 nDestTruncate = (nSrcPage+ratio-1)/ratio;
59653 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
59654 nDestTruncate--;
59656 }else{
59657 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
59659 assert( nDestTruncate>0 );
59661 if( pgszSrc<pgszDest ){
59662 /* If the source page-size is smaller than the destination page-size,
59663 ** two extra things may need to happen:
59665 ** * The destination may need to be truncated, and
59667 ** * Data stored on the pages immediately following the
59668 ** pending-byte page in the source database may need to be
59669 ** copied into the destination database.
59671 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
59672 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
59673 Pgno iPg;
59674 int nDstPage;
59675 i64 iOff;
59676 i64 iEnd;
59678 assert( pFile );
59679 assert( nDestTruncate==0
59680 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
59681 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
59682 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
59685 /* This block ensures that all data required to recreate the original
59686 ** database has been stored in the journal for pDestPager and the
59687 ** journal synced to disk. So at this point we may safely modify
59688 ** the database file in any way, knowing that if a power failure
59689 ** occurs, the original database will be reconstructed from the
59690 ** journal file. */
59691 sqlite3PagerPagecount(pDestPager, &nDstPage);
59692 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
59693 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
59694 DbPage *pPg;
59695 rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
59696 if( rc==SQLITE_OK ){
59697 rc = sqlite3PagerWrite(pPg);
59698 sqlite3PagerUnref(pPg);
59702 if( rc==SQLITE_OK ){
59703 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
59706 /* Write the extra pages and truncate the database file as required */
59707 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
59708 for(
59709 iOff=PENDING_BYTE+pgszSrc;
59710 rc==SQLITE_OK && iOff<iEnd;
59711 iOff+=pgszSrc
59713 PgHdr *pSrcPg = 0;
59714 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
59715 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
59716 if( rc==SQLITE_OK ){
59717 u8 *zData = sqlite3PagerGetData(pSrcPg);
59718 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
59720 sqlite3PagerUnref(pSrcPg);
59722 if( rc==SQLITE_OK ){
59723 rc = backupTruncateFile(pFile, iSize);
59726 /* Sync the database file to disk. */
59727 if( rc==SQLITE_OK ){
59728 rc = sqlite3PagerSync(pDestPager, 0);
59730 }else{
59731 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
59732 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
59735 /* Finish committing the transaction to the destination database. */
59736 if( SQLITE_OK==rc
59737 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
59739 rc = SQLITE_DONE;
59744 /* If bCloseTrans is true, then this function opened a read transaction
59745 ** on the source database. Close the read transaction here. There is
59746 ** no need to check the return values of the btree methods here, as
59747 ** "committing" a read-only transaction cannot fail.
59749 if( bCloseTrans ){
59750 TESTONLY( int rc2 );
59751 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
59752 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
59753 assert( rc2==SQLITE_OK );
59756 if( rc==SQLITE_IOERR_NOMEM ){
59757 rc = SQLITE_NOMEM;
59759 p->rc = rc;
59761 if( p->pDestDb ){
59762 sqlite3_mutex_leave(p->pDestDb->mutex);
59764 sqlite3BtreeLeave(p->pSrc);
59765 sqlite3_mutex_leave(p->pSrcDb->mutex);
59766 return rc;
59770 ** Release all resources associated with an sqlite3_backup* handle.
59772 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
59773 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
59774 sqlite3 *pSrcDb; /* Source database connection */
59775 int rc; /* Value to return */
59777 /* Enter the mutexes */
59778 if( p==0 ) return SQLITE_OK;
59779 pSrcDb = p->pSrcDb;
59780 sqlite3_mutex_enter(pSrcDb->mutex);
59781 sqlite3BtreeEnter(p->pSrc);
59782 if( p->pDestDb ){
59783 sqlite3_mutex_enter(p->pDestDb->mutex);
59786 /* Detach this backup from the source pager. */
59787 if( p->pDestDb ){
59788 p->pSrc->nBackup--;
59790 if( p->isAttached ){
59791 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
59792 while( *pp!=p ){
59793 pp = &(*pp)->pNext;
59795 *pp = p->pNext;
59798 /* If a transaction is still open on the Btree, roll it back. */
59799 sqlite3BtreeRollback(p->pDest, SQLITE_OK);
59801 /* Set the error code of the destination database handle. */
59802 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
59803 if( p->pDestDb ){
59804 sqlite3Error(p->pDestDb, rc, 0);
59806 /* Exit the mutexes and free the backup context structure. */
59807 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
59809 sqlite3BtreeLeave(p->pSrc);
59810 if( p->pDestDb ){
59811 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
59812 ** call to sqlite3_backup_init() and is destroyed by a call to
59813 ** sqlite3_backup_finish(). */
59814 sqlite3_free(p);
59816 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
59817 return rc;
59821 ** Return the number of pages still to be backed up as of the most recent
59822 ** call to sqlite3_backup_step().
59824 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
59825 return p->nRemaining;
59829 ** Return the total number of pages in the source database as of the most
59830 ** recent call to sqlite3_backup_step().
59832 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
59833 return p->nPagecount;
59837 ** This function is called after the contents of page iPage of the
59838 ** source database have been modified. If page iPage has already been
59839 ** copied into the destination database, then the data written to the
59840 ** destination is now invalidated. The destination copy of iPage needs
59841 ** to be updated with the new data before the backup operation is
59842 ** complete.
59844 ** It is assumed that the mutex associated with the BtShared object
59845 ** corresponding to the source database is held when this function is
59846 ** called.
59848 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
59849 sqlite3_backup *p; /* Iterator variable */
59850 for(p=pBackup; p; p=p->pNext){
59851 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
59852 if( !isFatalError(p->rc) && iPage<p->iNext ){
59853 /* The backup process p has already copied page iPage. But now it
59854 ** has been modified by a transaction on the source pager. Copy
59855 ** the new data into the backup.
59857 int rc;
59858 assert( p->pDestDb );
59859 sqlite3_mutex_enter(p->pDestDb->mutex);
59860 rc = backupOnePage(p, iPage, aData, 1);
59861 sqlite3_mutex_leave(p->pDestDb->mutex);
59862 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
59863 if( rc!=SQLITE_OK ){
59864 p->rc = rc;
59871 ** Restart the backup process. This is called when the pager layer
59872 ** detects that the database has been modified by an external database
59873 ** connection. In this case there is no way of knowing which of the
59874 ** pages that have been copied into the destination database are still
59875 ** valid and which are not, so the entire process needs to be restarted.
59877 ** It is assumed that the mutex associated with the BtShared object
59878 ** corresponding to the source database is held when this function is
59879 ** called.
59881 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
59882 sqlite3_backup *p; /* Iterator variable */
59883 for(p=pBackup; p; p=p->pNext){
59884 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
59885 p->iNext = 1;
59889 #ifndef SQLITE_OMIT_VACUUM
59891 ** Copy the complete content of pBtFrom into pBtTo. A transaction
59892 ** must be active for both files.
59894 ** The size of file pTo may be reduced by this operation. If anything
59895 ** goes wrong, the transaction on pTo is rolled back. If successful, the
59896 ** transaction is committed before returning.
59898 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
59899 int rc;
59900 sqlite3_file *pFd; /* File descriptor for database pTo */
59901 sqlite3_backup b;
59902 sqlite3BtreeEnter(pTo);
59903 sqlite3BtreeEnter(pFrom);
59905 assert( sqlite3BtreeIsInTrans(pTo) );
59906 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
59907 if( pFd->pMethods ){
59908 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
59909 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
59910 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
59911 if( rc ) goto copy_finished;
59914 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
59915 ** to 0. This is used by the implementations of sqlite3_backup_step()
59916 ** and sqlite3_backup_finish() to detect that they are being called
59917 ** from this function, not directly by the user.
59919 memset(&b, 0, sizeof(b));
59920 b.pSrcDb = pFrom->db;
59921 b.pSrc = pFrom;
59922 b.pDest = pTo;
59923 b.iNext = 1;
59925 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
59926 ** file. By passing this as the number of pages to copy to
59927 ** sqlite3_backup_step(), we can guarantee that the copy finishes
59928 ** within a single call (unless an error occurs). The assert() statement
59929 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
59930 ** or an error code.
59932 sqlite3_backup_step(&b, 0x7FFFFFFF);
59933 assert( b.rc!=SQLITE_OK );
59934 rc = sqlite3_backup_finish(&b);
59935 if( rc==SQLITE_OK ){
59936 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
59937 }else{
59938 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
59941 assert( sqlite3BtreeIsInTrans(pTo)==0 );
59942 copy_finished:
59943 sqlite3BtreeLeave(pFrom);
59944 sqlite3BtreeLeave(pTo);
59945 return rc;
59947 #endif /* SQLITE_OMIT_VACUUM */
59949 /************** End of backup.c **********************************************/
59950 /************** Begin file vdbemem.c *****************************************/
59952 ** 2004 May 26
59954 ** The author disclaims copyright to this source code. In place of
59955 ** a legal notice, here is a blessing:
59957 ** May you do good and not evil.
59958 ** May you find forgiveness for yourself and forgive others.
59959 ** May you share freely, never taking more than you give.
59961 *************************************************************************
59963 ** This file contains code use to manipulate "Mem" structure. A "Mem"
59964 ** stores a single value in the VDBE. Mem is an opaque structure visible
59965 ** only within the VDBE. Interface routines refer to a Mem using the
59966 ** name sqlite_value
59970 ** If pMem is an object with a valid string representation, this routine
59971 ** ensures the internal encoding for the string representation is
59972 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
59974 ** If pMem is not a string object, or the encoding of the string
59975 ** representation is already stored using the requested encoding, then this
59976 ** routine is a no-op.
59978 ** SQLITE_OK is returned if the conversion is successful (or not required).
59979 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
59980 ** between formats.
59982 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
59983 #ifndef SQLITE_OMIT_UTF16
59984 int rc;
59985 #endif
59986 assert( (pMem->flags&MEM_RowSet)==0 );
59987 assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
59988 || desiredEnc==SQLITE_UTF16BE );
59989 if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
59990 return SQLITE_OK;
59992 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59993 #ifdef SQLITE_OMIT_UTF16
59994 return SQLITE_ERROR;
59995 #else
59997 /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
59998 ** then the encoding of the value may not have changed.
60000 rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
60001 assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
60002 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
60003 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
60004 return rc;
60005 #endif
60009 ** Make sure pMem->z points to a writable allocation of at least
60010 ** min(n,32) bytes.
60012 ** If the bPreserve argument is true, then copy of the content of
60013 ** pMem->z into the new allocation. pMem must be either a string or
60014 ** blob if bPreserve is true. If bPreserve is false, any prior content
60015 ** in pMem->z is discarded.
60017 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
60018 assert( 1 >=
60019 ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
60020 (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
60021 ((pMem->flags&MEM_Ephem) ? 1 : 0) +
60022 ((pMem->flags&MEM_Static) ? 1 : 0)
60024 assert( (pMem->flags&MEM_RowSet)==0 );
60026 /* If the bPreserve flag is set to true, then the memory cell must already
60027 ** contain a valid string or blob value. */
60028 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
60029 testcase( bPreserve && pMem->z==0 );
60031 if( pMem->zMalloc==0 || sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
60032 if( n<32 ) n = 32;
60033 if( bPreserve && pMem->z==pMem->zMalloc ){
60034 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
60035 bPreserve = 0;
60036 }else{
60037 sqlite3DbFree(pMem->db, pMem->zMalloc);
60038 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
60040 if( pMem->zMalloc==0 ){
60041 sqlite3VdbeMemRelease(pMem);
60042 pMem->flags = MEM_Null;
60043 return SQLITE_NOMEM;
60047 if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
60048 memcpy(pMem->zMalloc, pMem->z, pMem->n);
60050 if( (pMem->flags&MEM_Dyn)!=0 && pMem->xDel ){
60051 assert( pMem->xDel!=SQLITE_DYNAMIC );
60052 pMem->xDel((void *)(pMem->z));
60055 pMem->z = pMem->zMalloc;
60056 pMem->flags &= ~(MEM_Ephem|MEM_Static);
60057 pMem->xDel = 0;
60058 return SQLITE_OK;
60062 ** Make the given Mem object MEM_Dyn. In other words, make it so
60063 ** that any TEXT or BLOB content is stored in memory obtained from
60064 ** malloc(). In this way, we know that the memory is safe to be
60065 ** overwritten or altered.
60067 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
60069 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
60070 int f;
60071 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60072 assert( (pMem->flags&MEM_RowSet)==0 );
60073 ExpandBlob(pMem);
60074 f = pMem->flags;
60075 if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
60076 if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
60077 return SQLITE_NOMEM;
60079 pMem->z[pMem->n] = 0;
60080 pMem->z[pMem->n+1] = 0;
60081 pMem->flags |= MEM_Term;
60082 #ifdef SQLITE_DEBUG
60083 pMem->pScopyFrom = 0;
60084 #endif
60087 return SQLITE_OK;
60091 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
60092 ** blob stored in dynamically allocated space.
60094 #ifndef SQLITE_OMIT_INCRBLOB
60095 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
60096 if( pMem->flags & MEM_Zero ){
60097 int nByte;
60098 assert( pMem->flags&MEM_Blob );
60099 assert( (pMem->flags&MEM_RowSet)==0 );
60100 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60102 /* Set nByte to the number of bytes required to store the expanded blob. */
60103 nByte = pMem->n + pMem->u.nZero;
60104 if( nByte<=0 ){
60105 nByte = 1;
60107 if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
60108 return SQLITE_NOMEM;
60111 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
60112 pMem->n += pMem->u.nZero;
60113 pMem->flags &= ~(MEM_Zero|MEM_Term);
60115 return SQLITE_OK;
60117 #endif
60121 ** Make sure the given Mem is \u0000 terminated.
60123 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
60124 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60125 if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
60126 return SQLITE_OK; /* Nothing to do */
60128 if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
60129 return SQLITE_NOMEM;
60131 pMem->z[pMem->n] = 0;
60132 pMem->z[pMem->n+1] = 0;
60133 pMem->flags |= MEM_Term;
60134 return SQLITE_OK;
60138 ** Add MEM_Str to the set of representations for the given Mem. Numbers
60139 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
60140 ** is a no-op.
60142 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
60144 ** A MEM_Null value will never be passed to this function. This function is
60145 ** used for converting values to text for returning to the user (i.e. via
60146 ** sqlite3_value_text()), or for ensuring that values to be used as btree
60147 ** keys are strings. In the former case a NULL pointer is returned the
60148 ** user and the later is an internal programming error.
60150 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
60151 int rc = SQLITE_OK;
60152 int fg = pMem->flags;
60153 const int nByte = 32;
60155 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60156 assert( !(fg&MEM_Zero) );
60157 assert( !(fg&(MEM_Str|MEM_Blob)) );
60158 assert( fg&(MEM_Int|MEM_Real) );
60159 assert( (pMem->flags&MEM_RowSet)==0 );
60160 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60163 if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
60164 return SQLITE_NOMEM;
60167 /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
60168 ** string representation of the value. Then, if the required encoding
60169 ** is UTF-16le or UTF-16be do a translation.
60171 ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
60173 if( fg & MEM_Int ){
60174 sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
60175 }else{
60176 assert( fg & MEM_Real );
60177 sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
60179 pMem->n = sqlite3Strlen30(pMem->z);
60180 pMem->enc = SQLITE_UTF8;
60181 pMem->flags |= MEM_Str|MEM_Term;
60182 sqlite3VdbeChangeEncoding(pMem, enc);
60183 return rc;
60187 ** Memory cell pMem contains the context of an aggregate function.
60188 ** This routine calls the finalize method for that function. The
60189 ** result of the aggregate is stored back into pMem.
60191 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
60192 ** otherwise.
60194 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
60195 int rc = SQLITE_OK;
60196 if( ALWAYS(pFunc && pFunc->xFinalize) ){
60197 sqlite3_context ctx;
60198 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
60199 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60200 memset(&ctx, 0, sizeof(ctx));
60201 ctx.s.flags = MEM_Null;
60202 ctx.s.db = pMem->db;
60203 ctx.pMem = pMem;
60204 ctx.pFunc = pFunc;
60205 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
60206 assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
60207 sqlite3DbFree(pMem->db, pMem->zMalloc);
60208 memcpy(pMem, &ctx.s, sizeof(ctx.s));
60209 rc = ctx.isError;
60211 return rc;
60215 ** If the memory cell contains a string value that must be freed by
60216 ** invoking an external callback, free it now. Calling this function
60217 ** does not free any Mem.zMalloc buffer.
60219 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
60220 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
60221 if( p->flags&MEM_Agg ){
60222 sqlite3VdbeMemFinalize(p, p->u.pDef);
60223 assert( (p->flags & MEM_Agg)==0 );
60224 sqlite3VdbeMemRelease(p);
60225 }else if( p->flags&MEM_Dyn && p->xDel ){
60226 assert( (p->flags&MEM_RowSet)==0 );
60227 assert( p->xDel!=SQLITE_DYNAMIC );
60228 p->xDel((void *)p->z);
60229 p->xDel = 0;
60230 }else if( p->flags&MEM_RowSet ){
60231 sqlite3RowSetClear(p->u.pRowSet);
60232 }else if( p->flags&MEM_Frame ){
60233 sqlite3VdbeMemSetNull(p);
60238 ** Release any memory held by the Mem. This may leave the Mem in an
60239 ** inconsistent state, for example with (Mem.z==0) and
60240 ** (Mem.type==SQLITE_TEXT).
60242 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
60243 VdbeMemRelease(p);
60244 if( p->zMalloc ){
60245 sqlite3DbFree(p->db, p->zMalloc);
60246 p->zMalloc = 0;
60248 p->z = 0;
60249 assert( p->xDel==0 ); /* Zeroed by VdbeMemRelease() above */
60253 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
60254 ** If the double is out of range of a 64-bit signed integer then
60255 ** return the closest available 64-bit signed integer.
60257 static i64 doubleToInt64(double r){
60258 #ifdef SQLITE_OMIT_FLOATING_POINT
60259 /* When floating-point is omitted, double and int64 are the same thing */
60260 return r;
60261 #else
60263 ** Many compilers we encounter do not define constants for the
60264 ** minimum and maximum 64-bit integers, or they define them
60265 ** inconsistently. And many do not understand the "LL" notation.
60266 ** So we define our own static constants here using nothing
60267 ** larger than a 32-bit integer constant.
60269 static const i64 maxInt = LARGEST_INT64;
60270 static const i64 minInt = SMALLEST_INT64;
60272 if( r<=(double)minInt ){
60273 return minInt;
60274 }else if( r>=(double)maxInt ){
60275 return maxInt;
60276 }else{
60277 return (i64)r;
60279 #endif
60283 ** Return some kind of integer value which is the best we can do
60284 ** at representing the value that *pMem describes as an integer.
60285 ** If pMem is an integer, then the value is exact. If pMem is
60286 ** a floating-point then the value returned is the integer part.
60287 ** If pMem is a string or blob, then we make an attempt to convert
60288 ** it into a integer and return that. If pMem represents an
60289 ** an SQL-NULL value, return 0.
60291 ** If pMem represents a string value, its encoding might be changed.
60293 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
60294 int flags;
60295 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60296 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60297 flags = pMem->flags;
60298 if( flags & MEM_Int ){
60299 return pMem->u.i;
60300 }else if( flags & MEM_Real ){
60301 return doubleToInt64(pMem->r);
60302 }else if( flags & (MEM_Str|MEM_Blob) ){
60303 i64 value = 0;
60304 assert( pMem->z || pMem->n==0 );
60305 testcase( pMem->z==0 );
60306 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
60307 return value;
60308 }else{
60309 return 0;
60314 ** Return the best representation of pMem that we can get into a
60315 ** double. If pMem is already a double or an integer, return its
60316 ** value. If it is a string or blob, try to convert it to a double.
60317 ** If it is a NULL, return 0.0.
60319 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
60320 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60321 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60322 if( pMem->flags & MEM_Real ){
60323 return pMem->r;
60324 }else if( pMem->flags & MEM_Int ){
60325 return (double)pMem->u.i;
60326 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
60327 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
60328 double val = (double)0;
60329 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
60330 return val;
60331 }else{
60332 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
60333 return (double)0;
60338 ** The MEM structure is already a MEM_Real. Try to also make it a
60339 ** MEM_Int if we can.
60341 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
60342 assert( pMem->flags & MEM_Real );
60343 assert( (pMem->flags & MEM_RowSet)==0 );
60344 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60345 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60347 pMem->u.i = doubleToInt64(pMem->r);
60349 /* Only mark the value as an integer if
60351 ** (1) the round-trip conversion real->int->real is a no-op, and
60352 ** (2) The integer is neither the largest nor the smallest
60353 ** possible integer (ticket #3922)
60355 ** The second and third terms in the following conditional enforces
60356 ** the second condition under the assumption that addition overflow causes
60357 ** values to wrap around.
60359 if( pMem->r==(double)pMem->u.i
60360 && pMem->u.i>SMALLEST_INT64
60361 && pMem->u.i<LARGEST_INT64
60363 pMem->flags |= MEM_Int;
60368 ** Convert pMem to type integer. Invalidate any prior representations.
60370 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
60371 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60372 assert( (pMem->flags & MEM_RowSet)==0 );
60373 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60375 pMem->u.i = sqlite3VdbeIntValue(pMem);
60376 MemSetTypeFlag(pMem, MEM_Int);
60377 return SQLITE_OK;
60381 ** Convert pMem so that it is of type MEM_Real.
60382 ** Invalidate any prior representations.
60384 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
60385 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60386 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
60388 pMem->r = sqlite3VdbeRealValue(pMem);
60389 MemSetTypeFlag(pMem, MEM_Real);
60390 return SQLITE_OK;
60394 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
60395 ** Invalidate any prior representations.
60397 ** Every effort is made to force the conversion, even if the input
60398 ** is a string that does not look completely like a number. Convert
60399 ** as much of the string as we can and ignore the rest.
60401 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
60402 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
60403 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
60404 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60405 if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
60406 MemSetTypeFlag(pMem, MEM_Int);
60407 }else{
60408 pMem->r = sqlite3VdbeRealValue(pMem);
60409 MemSetTypeFlag(pMem, MEM_Real);
60410 sqlite3VdbeIntegerAffinity(pMem);
60413 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
60414 pMem->flags &= ~(MEM_Str|MEM_Blob);
60415 return SQLITE_OK;
60419 ** Delete any previous value and set the value stored in *pMem to NULL.
60421 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
60422 if( pMem->flags & MEM_Frame ){
60423 VdbeFrame *pFrame = pMem->u.pFrame;
60424 pFrame->pParent = pFrame->v->pDelFrame;
60425 pFrame->v->pDelFrame = pFrame;
60427 if( pMem->flags & MEM_RowSet ){
60428 sqlite3RowSetClear(pMem->u.pRowSet);
60430 MemSetTypeFlag(pMem, MEM_Null);
60431 pMem->type = SQLITE_NULL;
60433 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
60434 sqlite3VdbeMemSetNull((Mem*)p);
60438 ** Delete any previous value and set the value to be a BLOB of length
60439 ** n containing all zeros.
60441 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
60442 sqlite3VdbeMemRelease(pMem);
60443 pMem->flags = MEM_Blob|MEM_Zero;
60444 pMem->type = SQLITE_BLOB;
60445 pMem->n = 0;
60446 if( n<0 ) n = 0;
60447 pMem->u.nZero = n;
60448 pMem->enc = SQLITE_UTF8;
60450 #ifdef SQLITE_OMIT_INCRBLOB
60451 sqlite3VdbeMemGrow(pMem, n, 0);
60452 if( pMem->z ){
60453 pMem->n = n;
60454 memset(pMem->z, 0, n);
60456 #endif
60460 ** Delete any previous value and set the value stored in *pMem to val,
60461 ** manifest type INTEGER.
60463 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
60464 sqlite3VdbeMemRelease(pMem);
60465 pMem->u.i = val;
60466 pMem->flags = MEM_Int;
60467 pMem->type = SQLITE_INTEGER;
60470 #ifndef SQLITE_OMIT_FLOATING_POINT
60472 ** Delete any previous value and set the value stored in *pMem to val,
60473 ** manifest type REAL.
60475 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
60476 if( sqlite3IsNaN(val) ){
60477 sqlite3VdbeMemSetNull(pMem);
60478 }else{
60479 sqlite3VdbeMemRelease(pMem);
60480 pMem->r = val;
60481 pMem->flags = MEM_Real;
60482 pMem->type = SQLITE_FLOAT;
60485 #endif
60488 ** Delete any previous value and set the value of pMem to be an
60489 ** empty boolean index.
60491 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
60492 sqlite3 *db = pMem->db;
60493 assert( db!=0 );
60494 assert( (pMem->flags & MEM_RowSet)==0 );
60495 sqlite3VdbeMemRelease(pMem);
60496 pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
60497 if( db->mallocFailed ){
60498 pMem->flags = MEM_Null;
60499 }else{
60500 assert( pMem->zMalloc );
60501 pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
60502 sqlite3DbMallocSize(db, pMem->zMalloc));
60503 assert( pMem->u.pRowSet!=0 );
60504 pMem->flags = MEM_RowSet;
60509 ** Return true if the Mem object contains a TEXT or BLOB that is
60510 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
60512 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
60513 assert( p->db!=0 );
60514 if( p->flags & (MEM_Str|MEM_Blob) ){
60515 int n = p->n;
60516 if( p->flags & MEM_Zero ){
60517 n += p->u.nZero;
60519 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
60521 return 0;
60524 #ifdef SQLITE_DEBUG
60526 ** This routine prepares a memory cell for modication by breaking
60527 ** its link to a shallow copy and by marking any current shallow
60528 ** copies of this cell as invalid.
60530 ** This is used for testing and debugging only - to make sure shallow
60531 ** copies are not misused.
60533 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
60534 int i;
60535 Mem *pX;
60536 for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
60537 if( pX->pScopyFrom==pMem ){
60538 pX->flags |= MEM_Invalid;
60539 pX->pScopyFrom = 0;
60542 pMem->pScopyFrom = 0;
60544 #endif /* SQLITE_DEBUG */
60547 ** Size of struct Mem not including the Mem.zMalloc member.
60549 #define MEMCELLSIZE offsetof(Mem,zMalloc)
60552 ** Make an shallow copy of pFrom into pTo. Prior contents of
60553 ** pTo are freed. The pFrom->z field is not duplicated. If
60554 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
60555 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
60557 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
60558 assert( (pFrom->flags & MEM_RowSet)==0 );
60559 VdbeMemRelease(pTo);
60560 memcpy(pTo, pFrom, MEMCELLSIZE);
60561 pTo->xDel = 0;
60562 if( (pFrom->flags&MEM_Static)==0 ){
60563 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
60564 assert( srcType==MEM_Ephem || srcType==MEM_Static );
60565 pTo->flags |= srcType;
60570 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
60571 ** freed before the copy is made.
60573 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
60574 int rc = SQLITE_OK;
60576 assert( (pFrom->flags & MEM_RowSet)==0 );
60577 VdbeMemRelease(pTo);
60578 memcpy(pTo, pFrom, MEMCELLSIZE);
60579 pTo->flags &= ~MEM_Dyn;
60581 if( pTo->flags&(MEM_Str|MEM_Blob) ){
60582 if( 0==(pFrom->flags&MEM_Static) ){
60583 pTo->flags |= MEM_Ephem;
60584 rc = sqlite3VdbeMemMakeWriteable(pTo);
60588 return rc;
60592 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
60593 ** freed. If pFrom contains ephemeral data, a copy is made.
60595 ** pFrom contains an SQL NULL when this routine returns.
60597 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
60598 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
60599 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
60600 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
60602 sqlite3VdbeMemRelease(pTo);
60603 memcpy(pTo, pFrom, sizeof(Mem));
60604 pFrom->flags = MEM_Null;
60605 pFrom->xDel = 0;
60606 pFrom->zMalloc = 0;
60610 ** Change the value of a Mem to be a string or a BLOB.
60612 ** The memory management strategy depends on the value of the xDel
60613 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
60614 ** string is copied into a (possibly existing) buffer managed by the
60615 ** Mem structure. Otherwise, any existing buffer is freed and the
60616 ** pointer copied.
60618 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
60619 ** size limit) then no memory allocation occurs. If the string can be
60620 ** stored without allocating memory, then it is. If a memory allocation
60621 ** is required to store the string, then value of pMem is unchanged. In
60622 ** either case, SQLITE_TOOBIG is returned.
60624 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
60625 Mem *pMem, /* Memory cell to set to string value */
60626 const char *z, /* String pointer */
60627 int n, /* Bytes in string, or negative */
60628 u8 enc, /* Encoding of z. 0 for BLOBs */
60629 void (*xDel)(void*) /* Destructor function */
60631 int nByte = n; /* New value for pMem->n */
60632 int iLimit; /* Maximum allowed string or blob size */
60633 u16 flags = 0; /* New value for pMem->flags */
60635 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
60636 assert( (pMem->flags & MEM_RowSet)==0 );
60638 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
60639 if( !z ){
60640 sqlite3VdbeMemSetNull(pMem);
60641 return SQLITE_OK;
60644 if( pMem->db ){
60645 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
60646 }else{
60647 iLimit = SQLITE_MAX_LENGTH;
60649 flags = (enc==0?MEM_Blob:MEM_Str);
60650 if( nByte<0 ){
60651 assert( enc!=0 );
60652 if( enc==SQLITE_UTF8 ){
60653 for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
60654 }else{
60655 for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
60657 flags |= MEM_Term;
60660 /* The following block sets the new values of Mem.z and Mem.xDel. It
60661 ** also sets a flag in local variable "flags" to indicate the memory
60662 ** management (one of MEM_Dyn or MEM_Static).
60664 if( xDel==SQLITE_TRANSIENT ){
60665 int nAlloc = nByte;
60666 if( flags&MEM_Term ){
60667 nAlloc += (enc==SQLITE_UTF8?1:2);
60669 if( nByte>iLimit ){
60670 return SQLITE_TOOBIG;
60672 if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
60673 return SQLITE_NOMEM;
60675 memcpy(pMem->z, z, nAlloc);
60676 }else if( xDel==SQLITE_DYNAMIC ){
60677 sqlite3VdbeMemRelease(pMem);
60678 pMem->zMalloc = pMem->z = (char *)z;
60679 pMem->xDel = 0;
60680 }else{
60681 sqlite3VdbeMemRelease(pMem);
60682 pMem->z = (char *)z;
60683 pMem->xDel = xDel;
60684 flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
60687 pMem->n = nByte;
60688 pMem->flags = flags;
60689 pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
60690 pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
60692 #ifndef SQLITE_OMIT_UTF16
60693 if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
60694 return SQLITE_NOMEM;
60696 #endif
60698 if( nByte>iLimit ){
60699 return SQLITE_TOOBIG;
60702 return SQLITE_OK;
60706 ** Compare the values contained by the two memory cells, returning
60707 ** negative, zero or positive if pMem1 is less than, equal to, or greater
60708 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
60709 ** and reals) sorted numerically, followed by text ordered by the collating
60710 ** sequence pColl and finally blob's ordered by memcmp().
60712 ** Two NULL values are considered equal by this function.
60714 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
60715 int rc;
60716 int f1, f2;
60717 int combined_flags;
60719 f1 = pMem1->flags;
60720 f2 = pMem2->flags;
60721 combined_flags = f1|f2;
60722 assert( (combined_flags & MEM_RowSet)==0 );
60724 /* If one value is NULL, it is less than the other. If both values
60725 ** are NULL, return 0.
60727 if( combined_flags&MEM_Null ){
60728 return (f2&MEM_Null) - (f1&MEM_Null);
60731 /* If one value is a number and the other is not, the number is less.
60732 ** If both are numbers, compare as reals if one is a real, or as integers
60733 ** if both values are integers.
60735 if( combined_flags&(MEM_Int|MEM_Real) ){
60736 double r1, r2;
60737 if( (f1 & f2 & MEM_Int)!=0 ){
60738 if( pMem1->u.i < pMem2->u.i ) return -1;
60739 if( pMem1->u.i > pMem2->u.i ) return 1;
60740 return 0;
60742 if( (f1&MEM_Real)!=0 ){
60743 r1 = pMem1->r;
60744 }else if( (f1&MEM_Int)!=0 ){
60745 r1 = (double)pMem1->u.i;
60746 }else{
60747 return 1;
60749 if( (f2&MEM_Real)!=0 ){
60750 r2 = pMem2->r;
60751 }else if( (f2&MEM_Int)!=0 ){
60752 r2 = (double)pMem2->u.i;
60753 }else{
60754 return -1;
60756 if( r1<r2 ) return -1;
60757 if( r1>r2 ) return 1;
60758 return 0;
60761 /* If one value is a string and the other is a blob, the string is less.
60762 ** If both are strings, compare using the collating functions.
60764 if( combined_flags&MEM_Str ){
60765 if( (f1 & MEM_Str)==0 ){
60766 return 1;
60768 if( (f2 & MEM_Str)==0 ){
60769 return -1;
60772 assert( pMem1->enc==pMem2->enc );
60773 assert( pMem1->enc==SQLITE_UTF8 ||
60774 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
60776 /* The collation sequence must be defined at this point, even if
60777 ** the user deletes the collation sequence after the vdbe program is
60778 ** compiled (this was not always the case).
60780 assert( !pColl || pColl->xCmp );
60782 if( pColl ){
60783 if( pMem1->enc==pColl->enc ){
60784 /* The strings are already in the correct encoding. Call the
60785 ** comparison function directly */
60786 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
60787 }else{
60788 const void *v1, *v2;
60789 int n1, n2;
60790 Mem c1;
60791 Mem c2;
60792 memset(&c1, 0, sizeof(c1));
60793 memset(&c2, 0, sizeof(c2));
60794 sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
60795 sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
60796 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
60797 n1 = v1==0 ? 0 : c1.n;
60798 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
60799 n2 = v2==0 ? 0 : c2.n;
60800 rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
60801 sqlite3VdbeMemRelease(&c1);
60802 sqlite3VdbeMemRelease(&c2);
60803 return rc;
60806 /* If a NULL pointer was passed as the collate function, fall through
60807 ** to the blob case and use memcmp(). */
60810 /* Both values must be blobs. Compare using memcmp(). */
60811 rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
60812 if( rc==0 ){
60813 rc = pMem1->n - pMem2->n;
60815 return rc;
60819 ** Move data out of a btree key or data field and into a Mem structure.
60820 ** The data or key is taken from the entry that pCur is currently pointing
60821 ** to. offset and amt determine what portion of the data or key to retrieve.
60822 ** key is true to get the key or false to get data. The result is written
60823 ** into the pMem element.
60825 ** The pMem structure is assumed to be uninitialized. Any prior content
60826 ** is overwritten without being freed.
60828 ** If this routine fails for any reason (malloc returns NULL or unable
60829 ** to read from the disk) then the pMem is left in an inconsistent state.
60831 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
60832 BtCursor *pCur, /* Cursor pointing at record to retrieve. */
60833 u32 offset, /* Offset from the start of data to return bytes from. */
60834 u32 amt, /* Number of bytes to return. */
60835 int key, /* If true, retrieve from the btree key, not data. */
60836 Mem *pMem /* OUT: Return data in this Mem structure. */
60838 char *zData; /* Data from the btree layer */
60839 u32 available = 0; /* Number of bytes available on the local btree page */
60840 int rc = SQLITE_OK; /* Return code */
60842 assert( sqlite3BtreeCursorIsValid(pCur) );
60844 /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
60845 ** that both the BtShared and database handle mutexes are held. */
60846 assert( (pMem->flags & MEM_RowSet)==0 );
60847 if( key ){
60848 zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
60849 }else{
60850 zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
60852 assert( zData!=0 );
60854 if( offset+amt<=available ){
60855 sqlite3VdbeMemRelease(pMem);
60856 pMem->z = &zData[offset];
60857 pMem->flags = MEM_Blob|MEM_Ephem;
60858 }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
60859 pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
60860 pMem->enc = 0;
60861 pMem->type = SQLITE_BLOB;
60862 if( key ){
60863 rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
60864 }else{
60865 rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
60867 pMem->z[amt] = 0;
60868 pMem->z[amt+1] = 0;
60869 if( rc!=SQLITE_OK ){
60870 sqlite3VdbeMemRelease(pMem);
60873 pMem->n = (int)amt;
60875 return rc;
60878 /* This function is only available internally, it is not part of the
60879 ** external API. It works in a similar way to sqlite3_value_text(),
60880 ** except the data returned is in the encoding specified by the second
60881 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
60882 ** SQLITE_UTF8.
60884 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
60885 ** If that is the case, then the result must be aligned on an even byte
60886 ** boundary.
60888 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
60889 if( !pVal ) return 0;
60891 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
60892 assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
60893 assert( (pVal->flags & MEM_RowSet)==0 );
60895 if( pVal->flags&MEM_Null ){
60896 return 0;
60898 assert( (MEM_Blob>>3) == MEM_Str );
60899 pVal->flags |= (pVal->flags & MEM_Blob)>>3;
60900 ExpandBlob(pVal);
60901 if( pVal->flags&MEM_Str ){
60902 sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
60903 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
60904 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
60905 if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
60906 return 0;
60909 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
60910 }else{
60911 assert( (pVal->flags&MEM_Blob)==0 );
60912 sqlite3VdbeMemStringify(pVal, enc);
60913 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
60915 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
60916 || pVal->db->mallocFailed );
60917 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
60918 return pVal->z;
60919 }else{
60920 return 0;
60925 ** Create a new sqlite3_value object.
60927 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
60928 Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
60929 if( p ){
60930 p->flags = MEM_Null;
60931 p->type = SQLITE_NULL;
60932 p->db = db;
60934 return p;
60938 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
60939 ** valueNew(). See comments above valueNew() for details.
60941 struct ValueNewStat4Ctx {
60942 Parse *pParse;
60943 Index *pIdx;
60944 UnpackedRecord **ppRec;
60945 int iVal;
60949 ** Allocate and return a pointer to a new sqlite3_value object. If
60950 ** the second argument to this function is NULL, the object is allocated
60951 ** by calling sqlite3ValueNew().
60953 ** Otherwise, if the second argument is non-zero, then this function is
60954 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
60955 ** already been allocated, allocate the UnpackedRecord structure that
60956 ** that function will return to its caller here. Then return a pointer
60957 ** an sqlite3_value within the UnpackedRecord.a[] array.
60959 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
60960 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
60961 if( p ){
60962 UnpackedRecord *pRec = p->ppRec[0];
60964 if( pRec==0 ){
60965 Index *pIdx = p->pIdx; /* Index being probed */
60966 int nByte; /* Bytes of space to allocate */
60967 int i; /* Counter variable */
60968 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
60970 nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
60971 pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
60972 if( pRec ){
60973 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
60974 if( pRec->pKeyInfo ){
60975 assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
60976 assert( pRec->pKeyInfo->enc==ENC(db) );
60977 pRec->flags = UNPACKED_PREFIX_MATCH;
60978 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
60979 for(i=0; i<nCol; i++){
60980 pRec->aMem[i].flags = MEM_Null;
60981 pRec->aMem[i].type = SQLITE_NULL;
60982 pRec->aMem[i].db = db;
60984 }else{
60985 sqlite3DbFree(db, pRec);
60986 pRec = 0;
60989 if( pRec==0 ) return 0;
60990 p->ppRec[0] = pRec;
60993 pRec->nField = p->iVal+1;
60994 return &pRec->aMem[p->iVal];
60996 #else
60997 UNUSED_PARAMETER(p);
60998 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
60999 return sqlite3ValueNew(db);
61003 ** Extract a value from the supplied expression in the manner described
61004 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
61005 ** using valueNew().
61007 ** If pCtx is NULL and an error occurs after the sqlite3_value object
61008 ** has been allocated, it is freed before returning. Or, if pCtx is not
61009 ** NULL, it is assumed that the caller will free any allocated object
61010 ** in all cases.
61012 static int valueFromExpr(
61013 sqlite3 *db, /* The database connection */
61014 Expr *pExpr, /* The expression to evaluate */
61015 u8 enc, /* Encoding to use */
61016 u8 affinity, /* Affinity to use */
61017 sqlite3_value **ppVal, /* Write the new value here */
61018 struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
61020 int op;
61021 char *zVal = 0;
61022 sqlite3_value *pVal = 0;
61023 int negInt = 1;
61024 const char *zNeg = "";
61025 int rc = SQLITE_OK;
61027 if( !pExpr ){
61028 *ppVal = 0;
61029 return SQLITE_OK;
61031 op = pExpr->op;
61032 if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
61034 /* Handle negative integers in a single step. This is needed in the
61035 ** case when the value is -9223372036854775808.
61037 if( op==TK_UMINUS
61038 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
61039 pExpr = pExpr->pLeft;
61040 op = pExpr->op;
61041 negInt = -1;
61042 zNeg = "-";
61045 if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
61046 pVal = valueNew(db, pCtx);
61047 if( pVal==0 ) goto no_mem;
61048 if( ExprHasProperty(pExpr, EP_IntValue) ){
61049 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
61050 }else{
61051 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
61052 if( zVal==0 ) goto no_mem;
61053 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
61054 if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
61056 if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
61057 sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
61058 }else{
61059 sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
61061 if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
61062 if( enc!=SQLITE_UTF8 ){
61063 rc = sqlite3VdbeChangeEncoding(pVal, enc);
61065 }else if( op==TK_UMINUS ) {
61066 /* This branch happens for multiple negative signs. Ex: -(-5) */
61067 if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
61068 && pVal!=0
61070 sqlite3VdbeMemNumerify(pVal);
61071 if( pVal->u.i==SMALLEST_INT64 ){
61072 pVal->flags &= MEM_Int;
61073 pVal->flags |= MEM_Real;
61074 pVal->r = (double)LARGEST_INT64;
61075 }else{
61076 pVal->u.i = -pVal->u.i;
61078 pVal->r = -pVal->r;
61079 sqlite3ValueApplyAffinity(pVal, affinity, enc);
61081 }else if( op==TK_NULL ){
61082 pVal = valueNew(db, pCtx);
61083 if( pVal==0 ) goto no_mem;
61085 #ifndef SQLITE_OMIT_BLOB_LITERAL
61086 else if( op==TK_BLOB ){
61087 int nVal;
61088 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
61089 assert( pExpr->u.zToken[1]=='\'' );
61090 pVal = valueNew(db, pCtx);
61091 if( !pVal ) goto no_mem;
61092 zVal = &pExpr->u.zToken[2];
61093 nVal = sqlite3Strlen30(zVal)-1;
61094 assert( zVal[nVal]=='\'' );
61095 sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
61096 0, SQLITE_DYNAMIC);
61098 #endif
61100 if( pVal ){
61101 sqlite3VdbeMemStoreType(pVal);
61103 *ppVal = pVal;
61104 return rc;
61106 no_mem:
61107 db->mallocFailed = 1;
61108 sqlite3DbFree(db, zVal);
61109 assert( *ppVal==0 );
61110 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
61111 if( pCtx==0 ) sqlite3ValueFree(pVal);
61112 #else
61113 assert( pCtx==0 ); sqlite3ValueFree(pVal);
61114 #endif
61115 return SQLITE_NOMEM;
61119 ** Create a new sqlite3_value object, containing the value of pExpr.
61121 ** This only works for very simple expressions that consist of one constant
61122 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
61123 ** be converted directly into a value, then the value is allocated and
61124 ** a pointer written to *ppVal. The caller is responsible for deallocating
61125 ** the value by passing it to sqlite3ValueFree() later on. If the expression
61126 ** cannot be converted to a value, then *ppVal is set to NULL.
61128 SQLITE_PRIVATE int sqlite3ValueFromExpr(
61129 sqlite3 *db, /* The database connection */
61130 Expr *pExpr, /* The expression to evaluate */
61131 u8 enc, /* Encoding to use */
61132 u8 affinity, /* Affinity to use */
61133 sqlite3_value **ppVal /* Write the new value here */
61135 return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
61138 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
61140 ** The implementation of the sqlite_record() function. This function accepts
61141 ** a single argument of any type. The return value is a formatted database
61142 ** record (a blob) containing the argument value.
61144 ** This is used to convert the value stored in the 'sample' column of the
61145 ** sqlite_stat3 table to the record format SQLite uses internally.
61147 static void recordFunc(
61148 sqlite3_context *context,
61149 int argc,
61150 sqlite3_value **argv
61152 const int file_format = 1;
61153 int iSerial; /* Serial type */
61154 int nSerial; /* Bytes of space for iSerial as varint */
61155 int nVal; /* Bytes of space required for argv[0] */
61156 int nRet;
61157 sqlite3 *db;
61158 u8 *aRet;
61160 UNUSED_PARAMETER( argc );
61161 iSerial = sqlite3VdbeSerialType(argv[0], file_format);
61162 nSerial = sqlite3VarintLen(iSerial);
61163 nVal = sqlite3VdbeSerialTypeLen(iSerial);
61164 db = sqlite3_context_db_handle(context);
61166 nRet = 1 + nSerial + nVal;
61167 aRet = sqlite3DbMallocRaw(db, nRet);
61168 if( aRet==0 ){
61169 sqlite3_result_error_nomem(context);
61170 }else{
61171 aRet[0] = nSerial+1;
61172 sqlite3PutVarint(&aRet[1], iSerial);
61173 sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
61174 sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
61175 sqlite3DbFree(db, aRet);
61180 ** Register built-in functions used to help read ANALYZE data.
61182 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
61183 static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
61184 FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
61186 int i;
61187 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
61188 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
61189 for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
61190 sqlite3FuncDefInsert(pHash, &aFunc[i]);
61195 ** This function is used to allocate and populate UnpackedRecord
61196 ** structures intended to be compared against sample index keys stored
61197 ** in the sqlite_stat4 table.
61199 ** A single call to this function attempts to populates field iVal (leftmost
61200 ** is 0 etc.) of the unpacked record with a value extracted from expression
61201 ** pExpr. Extraction of values is possible if:
61203 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
61205 ** * The expression is a bound variable, and this is a reprepare, or
61207 ** * The sqlite3ValueFromExpr() function is able to extract a value
61208 ** from the expression (i.e. the expression is a literal value).
61210 ** If a value can be extracted, the affinity passed as the 5th argument
61211 ** is applied to it before it is copied into the UnpackedRecord. Output
61212 ** parameter *pbOk is set to true if a value is extracted, or false
61213 ** otherwise.
61215 ** When this function is called, *ppRec must either point to an object
61216 ** allocated by an earlier call to this function, or must be NULL. If it
61217 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
61218 ** is allocated (and *ppRec set to point to it) before returning.
61220 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
61221 ** error if a value cannot be extracted from pExpr. If an error does
61222 ** occur, an SQLite error code is returned.
61224 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
61225 Parse *pParse, /* Parse context */
61226 Index *pIdx, /* Index being probed */
61227 UnpackedRecord **ppRec, /* IN/OUT: Probe record */
61228 Expr *pExpr, /* The expression to extract a value from */
61229 u8 affinity, /* Affinity to use */
61230 int iVal, /* Array element to populate */
61231 int *pbOk /* OUT: True if value was extracted */
61233 int rc = SQLITE_OK;
61234 sqlite3_value *pVal = 0;
61235 sqlite3 *db = pParse->db;
61238 struct ValueNewStat4Ctx alloc;
61239 alloc.pParse = pParse;
61240 alloc.pIdx = pIdx;
61241 alloc.ppRec = ppRec;
61242 alloc.iVal = iVal;
61244 /* Skip over any TK_COLLATE nodes */
61245 pExpr = sqlite3ExprSkipCollate(pExpr);
61247 if( !pExpr ){
61248 pVal = valueNew(db, &alloc);
61249 if( pVal ){
61250 sqlite3VdbeMemSetNull((Mem*)pVal);
61252 }else if( pExpr->op==TK_VARIABLE
61253 || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
61255 Vdbe *v;
61256 int iBindVar = pExpr->iColumn;
61257 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
61258 if( (v = pParse->pReprepare)!=0 ){
61259 pVal = valueNew(db, &alloc);
61260 if( pVal ){
61261 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
61262 if( rc==SQLITE_OK ){
61263 sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
61265 pVal->db = pParse->db;
61266 sqlite3VdbeMemStoreType((Mem*)pVal);
61269 }else{
61270 rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
61272 *pbOk = (pVal!=0);
61274 assert( pVal==0 || pVal->db==db );
61275 return rc;
61279 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
61280 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
61281 ** the object.
61283 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
61284 if( pRec ){
61285 int i;
61286 int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
61287 Mem *aMem = pRec->aMem;
61288 sqlite3 *db = aMem[0].db;
61289 for(i=0; i<nCol; i++){
61290 sqlite3DbFree(db, aMem[i].zMalloc);
61292 sqlite3KeyInfoUnref(pRec->pKeyInfo);
61293 sqlite3DbFree(db, pRec);
61296 #endif /* ifdef SQLITE_ENABLE_STAT4 */
61299 ** Change the string value of an sqlite3_value object
61301 SQLITE_PRIVATE void sqlite3ValueSetStr(
61302 sqlite3_value *v, /* Value to be set */
61303 int n, /* Length of string z */
61304 const void *z, /* Text of the new string */
61305 u8 enc, /* Encoding to use */
61306 void (*xDel)(void*) /* Destructor for the string */
61308 if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
61312 ** Free an sqlite3_value object
61314 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
61315 if( !v ) return;
61316 sqlite3VdbeMemRelease((Mem *)v);
61317 sqlite3DbFree(((Mem*)v)->db, v);
61321 ** Return the number of bytes in the sqlite3_value object assuming
61322 ** that it uses the encoding "enc"
61324 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
61325 Mem *p = (Mem*)pVal;
61326 if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
61327 if( p->flags & MEM_Zero ){
61328 return p->n + p->u.nZero;
61329 }else{
61330 return p->n;
61333 return 0;
61336 /************** End of vdbemem.c *********************************************/
61337 /************** Begin file vdbeaux.c *****************************************/
61339 ** 2003 September 6
61341 ** The author disclaims copyright to this source code. In place of
61342 ** a legal notice, here is a blessing:
61344 ** May you do good and not evil.
61345 ** May you find forgiveness for yourself and forgive others.
61346 ** May you share freely, never taking more than you give.
61348 *************************************************************************
61349 ** This file contains code used for creating, destroying, and populating
61350 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
61351 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
61352 ** But that file was getting too big so this subroutines were split out.
61356 ** Create a new virtual database engine.
61358 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
61359 sqlite3 *db = pParse->db;
61360 Vdbe *p;
61361 p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
61362 if( p==0 ) return 0;
61363 p->db = db;
61364 if( db->pVdbe ){
61365 db->pVdbe->pPrev = p;
61367 p->pNext = db->pVdbe;
61368 p->pPrev = 0;
61369 db->pVdbe = p;
61370 p->magic = VDBE_MAGIC_INIT;
61371 p->pParse = pParse;
61372 assert( pParse->aLabel==0 );
61373 assert( pParse->nLabel==0 );
61374 assert( pParse->nOpAlloc==0 );
61375 return p;
61379 ** Remember the SQL string for a prepared statement.
61381 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
61382 assert( isPrepareV2==1 || isPrepareV2==0 );
61383 if( p==0 ) return;
61384 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
61385 if( !isPrepareV2 ) return;
61386 #endif
61387 assert( p->zSql==0 );
61388 p->zSql = sqlite3DbStrNDup(p->db, z, n);
61389 p->isPrepareV2 = (u8)isPrepareV2;
61393 ** Return the SQL associated with a prepared statement
61395 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
61396 Vdbe *p = (Vdbe *)pStmt;
61397 return (p && p->isPrepareV2) ? p->zSql : 0;
61401 ** Swap all content between two VDBE structures.
61403 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
61404 Vdbe tmp, *pTmp;
61405 char *zTmp;
61406 tmp = *pA;
61407 *pA = *pB;
61408 *pB = tmp;
61409 pTmp = pA->pNext;
61410 pA->pNext = pB->pNext;
61411 pB->pNext = pTmp;
61412 pTmp = pA->pPrev;
61413 pA->pPrev = pB->pPrev;
61414 pB->pPrev = pTmp;
61415 zTmp = pA->zSql;
61416 pA->zSql = pB->zSql;
61417 pB->zSql = zTmp;
61418 pB->isPrepareV2 = pA->isPrepareV2;
61422 ** Resize the Vdbe.aOp array so that it is at least one op larger than
61423 ** it was.
61425 ** If an out-of-memory error occurs while resizing the array, return
61426 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
61427 ** unchanged (this is so that any opcodes already allocated can be
61428 ** correctly deallocated along with the rest of the Vdbe).
61430 static int growOpArray(Vdbe *v){
61431 VdbeOp *pNew;
61432 Parse *p = v->pParse;
61433 int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
61434 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
61435 if( pNew ){
61436 p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
61437 v->aOp = pNew;
61439 return (pNew ? SQLITE_OK : SQLITE_NOMEM);
61442 #ifdef SQLITE_DEBUG
61443 /* This routine is just a convenient place to set a breakpoint that will
61444 ** fire after each opcode is inserted and displayed using
61445 ** "PRAGMA vdbe_addoptrace=on".
61447 static void test_addop_breakpoint(void){
61448 static int n = 0;
61449 n++;
61451 #endif
61454 ** Add a new instruction to the list of instructions current in the
61455 ** VDBE. Return the address of the new instruction.
61457 ** Parameters:
61459 ** p Pointer to the VDBE
61461 ** op The opcode for this instruction
61463 ** p1, p2, p3 Operands
61465 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
61466 ** the sqlite3VdbeChangeP4() function to change the value of the P4
61467 ** operand.
61469 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
61470 int i;
61471 VdbeOp *pOp;
61473 i = p->nOp;
61474 assert( p->magic==VDBE_MAGIC_INIT );
61475 assert( op>0 && op<0xff );
61476 if( p->pParse->nOpAlloc<=i ){
61477 if( growOpArray(p) ){
61478 return 1;
61481 p->nOp++;
61482 pOp = &p->aOp[i];
61483 pOp->opcode = (u8)op;
61484 pOp->p5 = 0;
61485 pOp->p1 = p1;
61486 pOp->p2 = p2;
61487 pOp->p3 = p3;
61488 pOp->p4.p = 0;
61489 pOp->p4type = P4_NOTUSED;
61490 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
61491 pOp->zComment = 0;
61492 #endif
61493 #ifdef SQLITE_DEBUG
61494 if( p->db->flags & SQLITE_VdbeAddopTrace ){
61495 int jj, kk;
61496 Parse *pParse = p->pParse;
61497 for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
61498 struct yColCache *x = pParse->aColCache + jj;
61499 if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
61500 printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
61501 kk++;
61503 if( kk ) printf("\n");
61504 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
61505 test_addop_breakpoint();
61507 #endif
61508 #ifdef VDBE_PROFILE
61509 pOp->cycles = 0;
61510 pOp->cnt = 0;
61511 #endif
61512 return i;
61514 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
61515 return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
61517 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
61518 return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
61520 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
61521 return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
61526 ** Add an opcode that includes the p4 value as a pointer.
61528 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
61529 Vdbe *p, /* Add the opcode to this VM */
61530 int op, /* The new opcode */
61531 int p1, /* The P1 operand */
61532 int p2, /* The P2 operand */
61533 int p3, /* The P3 operand */
61534 const char *zP4, /* The P4 operand */
61535 int p4type /* P4 operand type */
61537 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
61538 sqlite3VdbeChangeP4(p, addr, zP4, p4type);
61539 return addr;
61543 ** Add an OP_ParseSchema opcode. This routine is broken out from
61544 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
61545 ** as having been used.
61547 ** The zWhere string must have been obtained from sqlite3_malloc().
61548 ** This routine will take ownership of the allocated memory.
61550 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
61551 int j;
61552 int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
61553 sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
61554 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
61558 ** Add an opcode that includes the p4 value as an integer.
61560 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
61561 Vdbe *p, /* Add the opcode to this VM */
61562 int op, /* The new opcode */
61563 int p1, /* The P1 operand */
61564 int p2, /* The P2 operand */
61565 int p3, /* The P3 operand */
61566 int p4 /* The P4 operand as an integer */
61568 int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
61569 sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
61570 return addr;
61574 ** Create a new symbolic label for an instruction that has yet to be
61575 ** coded. The symbolic label is really just a negative number. The
61576 ** label can be used as the P2 value of an operation. Later, when
61577 ** the label is resolved to a specific address, the VDBE will scan
61578 ** through its operation list and change all values of P2 which match
61579 ** the label into the resolved address.
61581 ** The VDBE knows that a P2 value is a label because labels are
61582 ** always negative and P2 values are suppose to be non-negative.
61583 ** Hence, a negative P2 value is a label that has yet to be resolved.
61585 ** Zero is returned if a malloc() fails.
61587 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
61588 Parse *p = v->pParse;
61589 int i = p->nLabel++;
61590 assert( v->magic==VDBE_MAGIC_INIT );
61591 if( (i & (i-1))==0 ){
61592 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
61593 (i*2+1)*sizeof(p->aLabel[0]));
61595 if( p->aLabel ){
61596 p->aLabel[i] = -1;
61598 return -1-i;
61602 ** Resolve label "x" to be the address of the next instruction to
61603 ** be inserted. The parameter "x" must have been obtained from
61604 ** a prior call to sqlite3VdbeMakeLabel().
61606 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
61607 Parse *p = v->pParse;
61608 int j = -1-x;
61609 assert( v->magic==VDBE_MAGIC_INIT );
61610 assert( j<p->nLabel );
61611 if( j>=0 && p->aLabel ){
61612 p->aLabel[j] = v->nOp;
61614 p->iFixedOp = v->nOp - 1;
61618 ** Mark the VDBE as one that can only be run one time.
61620 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
61621 p->runOnlyOnce = 1;
61624 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
61627 ** The following type and function are used to iterate through all opcodes
61628 ** in a Vdbe main program and each of the sub-programs (triggers) it may
61629 ** invoke directly or indirectly. It should be used as follows:
61631 ** Op *pOp;
61632 ** VdbeOpIter sIter;
61634 ** memset(&sIter, 0, sizeof(sIter));
61635 ** sIter.v = v; // v is of type Vdbe*
61636 ** while( (pOp = opIterNext(&sIter)) ){
61637 ** // Do something with pOp
61638 ** }
61639 ** sqlite3DbFree(v->db, sIter.apSub);
61642 typedef struct VdbeOpIter VdbeOpIter;
61643 struct VdbeOpIter {
61644 Vdbe *v; /* Vdbe to iterate through the opcodes of */
61645 SubProgram **apSub; /* Array of subprograms */
61646 int nSub; /* Number of entries in apSub */
61647 int iAddr; /* Address of next instruction to return */
61648 int iSub; /* 0 = main program, 1 = first sub-program etc. */
61650 static Op *opIterNext(VdbeOpIter *p){
61651 Vdbe *v = p->v;
61652 Op *pRet = 0;
61653 Op *aOp;
61654 int nOp;
61656 if( p->iSub<=p->nSub ){
61658 if( p->iSub==0 ){
61659 aOp = v->aOp;
61660 nOp = v->nOp;
61661 }else{
61662 aOp = p->apSub[p->iSub-1]->aOp;
61663 nOp = p->apSub[p->iSub-1]->nOp;
61665 assert( p->iAddr<nOp );
61667 pRet = &aOp[p->iAddr];
61668 p->iAddr++;
61669 if( p->iAddr==nOp ){
61670 p->iSub++;
61671 p->iAddr = 0;
61674 if( pRet->p4type==P4_SUBPROGRAM ){
61675 int nByte = (p->nSub+1)*sizeof(SubProgram*);
61676 int j;
61677 for(j=0; j<p->nSub; j++){
61678 if( p->apSub[j]==pRet->p4.pProgram ) break;
61680 if( j==p->nSub ){
61681 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
61682 if( !p->apSub ){
61683 pRet = 0;
61684 }else{
61685 p->apSub[p->nSub++] = pRet->p4.pProgram;
61691 return pRet;
61695 ** Check if the program stored in the VM associated with pParse may
61696 ** throw an ABORT exception (causing the statement, but not entire transaction
61697 ** to be rolled back). This condition is true if the main program or any
61698 ** sub-programs contains any of the following:
61700 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
61701 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
61702 ** * OP_Destroy
61703 ** * OP_VUpdate
61704 ** * OP_VRename
61705 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
61707 ** Then check that the value of Parse.mayAbort is true if an
61708 ** ABORT may be thrown, or false otherwise. Return true if it does
61709 ** match, or false otherwise. This function is intended to be used as
61710 ** part of an assert statement in the compiler. Similar to:
61712 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
61714 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
61715 int hasAbort = 0;
61716 Op *pOp;
61717 VdbeOpIter sIter;
61718 memset(&sIter, 0, sizeof(sIter));
61719 sIter.v = v;
61721 while( (pOp = opIterNext(&sIter))!=0 ){
61722 int opcode = pOp->opcode;
61723 if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
61724 #ifndef SQLITE_OMIT_FOREIGN_KEY
61725 || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
61726 #endif
61727 || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
61728 && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
61730 hasAbort = 1;
61731 break;
61734 sqlite3DbFree(v->db, sIter.apSub);
61736 /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
61737 ** If malloc failed, then the while() loop above may not have iterated
61738 ** through all opcodes and hasAbort may be set incorrectly. Return
61739 ** true for this case to prevent the assert() in the callers frame
61740 ** from failing. */
61741 return ( v->db->mallocFailed || hasAbort==mayAbort );
61743 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
61746 ** Loop through the program looking for P2 values that are negative
61747 ** on jump instructions. Each such value is a label. Resolve the
61748 ** label by setting the P2 value to its correct non-zero value.
61750 ** This routine is called once after all opcodes have been inserted.
61752 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
61753 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
61754 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
61756 ** The Op.opflags field is set on all opcodes.
61758 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
61759 int i;
61760 int nMaxArgs = *pMaxFuncArgs;
61761 Op *pOp;
61762 Parse *pParse = p->pParse;
61763 int *aLabel = pParse->aLabel;
61764 p->readOnly = 1;
61765 p->bIsReader = 0;
61766 for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
61767 u8 opcode = pOp->opcode;
61769 /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
61770 ** cases from this switch! */
61771 switch( opcode ){
61772 case OP_Function:
61773 case OP_AggStep: {
61774 if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
61775 break;
61777 case OP_Transaction: {
61778 if( pOp->p2!=0 ) p->readOnly = 0;
61779 /* fall thru */
61781 case OP_AutoCommit:
61782 case OP_Savepoint: {
61783 p->bIsReader = 1;
61784 break;
61786 #ifndef SQLITE_OMIT_WAL
61787 case OP_Checkpoint:
61788 #endif
61789 case OP_Vacuum:
61790 case OP_JournalMode: {
61791 p->readOnly = 0;
61792 p->bIsReader = 1;
61793 break;
61795 #ifndef SQLITE_OMIT_VIRTUALTABLE
61796 case OP_VUpdate: {
61797 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
61798 break;
61800 case OP_VFilter: {
61801 int n;
61802 assert( p->nOp - i >= 3 );
61803 assert( pOp[-1].opcode==OP_Integer );
61804 n = pOp[-1].p1;
61805 if( n>nMaxArgs ) nMaxArgs = n;
61806 break;
61808 #endif
61809 case OP_Next:
61810 case OP_NextIfOpen:
61811 case OP_SorterNext: {
61812 pOp->p4.xAdvance = sqlite3BtreeNext;
61813 pOp->p4type = P4_ADVANCE;
61814 break;
61816 case OP_Prev:
61817 case OP_PrevIfOpen: {
61818 pOp->p4.xAdvance = sqlite3BtreePrevious;
61819 pOp->p4type = P4_ADVANCE;
61820 break;
61824 pOp->opflags = sqlite3OpcodeProperty[opcode];
61825 if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
61826 assert( -1-pOp->p2<pParse->nLabel );
61827 pOp->p2 = aLabel[-1-pOp->p2];
61830 sqlite3DbFree(p->db, pParse->aLabel);
61831 pParse->aLabel = 0;
61832 pParse->nLabel = 0;
61833 *pMaxFuncArgs = nMaxArgs;
61834 assert( p->bIsReader!=0 || p->btreeMask==0 );
61838 ** Return the address of the next instruction to be inserted.
61840 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
61841 assert( p->magic==VDBE_MAGIC_INIT );
61842 return p->nOp;
61846 ** This function returns a pointer to the array of opcodes associated with
61847 ** the Vdbe passed as the first argument. It is the callers responsibility
61848 ** to arrange for the returned array to be eventually freed using the
61849 ** vdbeFreeOpArray() function.
61851 ** Before returning, *pnOp is set to the number of entries in the returned
61852 ** array. Also, *pnMaxArg is set to the larger of its current value and
61853 ** the number of entries in the Vdbe.apArg[] array required to execute the
61854 ** returned program.
61856 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
61857 VdbeOp *aOp = p->aOp;
61858 assert( aOp && !p->db->mallocFailed );
61860 /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
61861 assert( p->btreeMask==0 );
61863 resolveP2Values(p, pnMaxArg);
61864 *pnOp = p->nOp;
61865 p->aOp = 0;
61866 return aOp;
61870 ** Add a whole list of operations to the operation stack. Return the
61871 ** address of the first operation added.
61873 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
61874 int addr;
61875 assert( p->magic==VDBE_MAGIC_INIT );
61876 if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p) ){
61877 return 0;
61879 addr = p->nOp;
61880 if( ALWAYS(nOp>0) ){
61881 int i;
61882 VdbeOpList const *pIn = aOp;
61883 for(i=0; i<nOp; i++, pIn++){
61884 int p2 = pIn->p2;
61885 VdbeOp *pOut = &p->aOp[i+addr];
61886 pOut->opcode = pIn->opcode;
61887 pOut->p1 = pIn->p1;
61888 if( p2<0 ){
61889 assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
61890 pOut->p2 = addr + ADDR(p2);
61891 }else{
61892 pOut->p2 = p2;
61894 pOut->p3 = pIn->p3;
61895 pOut->p4type = P4_NOTUSED;
61896 pOut->p4.p = 0;
61897 pOut->p5 = 0;
61898 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
61899 pOut->zComment = 0;
61900 #endif
61901 #ifdef SQLITE_DEBUG
61902 if( p->db->flags & SQLITE_VdbeAddopTrace ){
61903 sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
61905 #endif
61907 p->nOp += nOp;
61909 return addr;
61913 ** Change the value of the P1 operand for a specific instruction.
61914 ** This routine is useful when a large program is loaded from a
61915 ** static array using sqlite3VdbeAddOpList but we want to make a
61916 ** few minor changes to the program.
61918 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
61919 assert( p!=0 );
61920 if( ((u32)p->nOp)>addr ){
61921 p->aOp[addr].p1 = val;
61926 ** Change the value of the P2 operand for a specific instruction.
61927 ** This routine is useful for setting a jump destination.
61929 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
61930 assert( p!=0 );
61931 if( ((u32)p->nOp)>addr ){
61932 p->aOp[addr].p2 = val;
61937 ** Change the value of the P3 operand for a specific instruction.
61939 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
61940 assert( p!=0 );
61941 if( ((u32)p->nOp)>addr ){
61942 p->aOp[addr].p3 = val;
61947 ** Change the value of the P5 operand for the most recently
61948 ** added operation.
61950 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
61951 assert( p!=0 );
61952 if( p->aOp ){
61953 assert( p->nOp>0 );
61954 p->aOp[p->nOp-1].p5 = val;
61959 ** Change the P2 operand of instruction addr so that it points to
61960 ** the address of the next instruction to be coded.
61962 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
61963 sqlite3VdbeChangeP2(p, addr, p->nOp);
61964 p->pParse->iFixedOp = p->nOp - 1;
61969 ** If the input FuncDef structure is ephemeral, then free it. If
61970 ** the FuncDef is not ephermal, then do nothing.
61972 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
61973 if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
61974 sqlite3DbFree(db, pDef);
61978 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
61981 ** Delete a P4 value if necessary.
61983 static void freeP4(sqlite3 *db, int p4type, void *p4){
61984 if( p4 ){
61985 assert( db );
61986 switch( p4type ){
61987 case P4_REAL:
61988 case P4_INT64:
61989 case P4_DYNAMIC:
61990 case P4_INTARRAY: {
61991 sqlite3DbFree(db, p4);
61992 break;
61994 case P4_KEYINFO: {
61995 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
61996 break;
61998 case P4_MPRINTF: {
61999 if( db->pnBytesFreed==0 ) sqlite3_free(p4);
62000 break;
62002 case P4_FUNCDEF: {
62003 freeEphemeralFunction(db, (FuncDef*)p4);
62004 break;
62006 case P4_MEM: {
62007 if( db->pnBytesFreed==0 ){
62008 sqlite3ValueFree((sqlite3_value*)p4);
62009 }else{
62010 Mem *p = (Mem*)p4;
62011 sqlite3DbFree(db, p->zMalloc);
62012 sqlite3DbFree(db, p);
62014 break;
62016 case P4_VTAB : {
62017 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
62018 break;
62025 ** Free the space allocated for aOp and any p4 values allocated for the
62026 ** opcodes contained within. If aOp is not NULL it is assumed to contain
62027 ** nOp entries.
62029 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
62030 if( aOp ){
62031 Op *pOp;
62032 for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
62033 freeP4(db, pOp->p4type, pOp->p4.p);
62034 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62035 sqlite3DbFree(db, pOp->zComment);
62036 #endif
62039 sqlite3DbFree(db, aOp);
62043 ** Link the SubProgram object passed as the second argument into the linked
62044 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
62045 ** objects when the VM is no longer required.
62047 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
62048 p->pNext = pVdbe->pProgram;
62049 pVdbe->pProgram = p;
62053 ** Change the opcode at addr into OP_Noop
62055 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
62056 if( p->aOp ){
62057 VdbeOp *pOp = &p->aOp[addr];
62058 sqlite3 *db = p->db;
62059 freeP4(db, pOp->p4type, pOp->p4.p);
62060 memset(pOp, 0, sizeof(pOp[0]));
62061 pOp->opcode = OP_Noop;
62062 if( addr==p->nOp-1 ) p->nOp--;
62067 ** Remove the last opcode inserted
62069 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
62070 if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
62071 sqlite3VdbeChangeToNoop(p, p->nOp-1);
62072 return 1;
62073 }else{
62074 return 0;
62079 ** Change the value of the P4 operand for a specific instruction.
62080 ** This routine is useful when a large program is loaded from a
62081 ** static array using sqlite3VdbeAddOpList but we want to make a
62082 ** few minor changes to the program.
62084 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
62085 ** the string is made into memory obtained from sqlite3_malloc().
62086 ** A value of n==0 means copy bytes of zP4 up to and including the
62087 ** first null byte. If n>0 then copy n+1 bytes of zP4.
62089 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
62090 ** to a string or structure that is guaranteed to exist for the lifetime of
62091 ** the Vdbe. In these cases we can just copy the pointer.
62093 ** If addr<0 then change P4 on the most recently inserted instruction.
62095 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
62096 Op *pOp;
62097 sqlite3 *db;
62098 assert( p!=0 );
62099 db = p->db;
62100 assert( p->magic==VDBE_MAGIC_INIT );
62101 if( p->aOp==0 || db->mallocFailed ){
62102 if( n!=P4_VTAB ){
62103 freeP4(db, n, (void*)*(char**)&zP4);
62105 return;
62107 assert( p->nOp>0 );
62108 assert( addr<p->nOp );
62109 if( addr<0 ){
62110 addr = p->nOp - 1;
62112 pOp = &p->aOp[addr];
62113 assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
62114 freeP4(db, pOp->p4type, pOp->p4.p);
62115 pOp->p4.p = 0;
62116 if( n==P4_INT32 ){
62117 /* Note: this cast is safe, because the origin data point was an int
62118 ** that was cast to a (const char *). */
62119 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
62120 pOp->p4type = P4_INT32;
62121 }else if( zP4==0 ){
62122 pOp->p4.p = 0;
62123 pOp->p4type = P4_NOTUSED;
62124 }else if( n==P4_KEYINFO ){
62125 pOp->p4.p = (void*)zP4;
62126 pOp->p4type = P4_KEYINFO;
62127 }else if( n==P4_VTAB ){
62128 pOp->p4.p = (void*)zP4;
62129 pOp->p4type = P4_VTAB;
62130 sqlite3VtabLock((VTable *)zP4);
62131 assert( ((VTable *)zP4)->db==p->db );
62132 }else if( n<0 ){
62133 pOp->p4.p = (void*)zP4;
62134 pOp->p4type = (signed char)n;
62135 }else{
62136 if( n==0 ) n = sqlite3Strlen30(zP4);
62137 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
62138 pOp->p4type = P4_DYNAMIC;
62143 ** Set the P4 on the most recently added opcode to the KeyInfo for the
62144 ** index given.
62146 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
62147 Vdbe *v = pParse->pVdbe;
62148 assert( v!=0 );
62149 assert( pIdx!=0 );
62150 sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
62151 P4_KEYINFO);
62154 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62156 ** Change the comment on the most recently coded instruction. Or
62157 ** insert a No-op and add the comment to that new instruction. This
62158 ** makes the code easier to read during debugging. None of this happens
62159 ** in a production build.
62161 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
62162 assert( p->nOp>0 || p->aOp==0 );
62163 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
62164 if( p->nOp ){
62165 assert( p->aOp );
62166 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
62167 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
62170 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
62171 va_list ap;
62172 if( p ){
62173 va_start(ap, zFormat);
62174 vdbeVComment(p, zFormat, ap);
62175 va_end(ap);
62178 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
62179 va_list ap;
62180 if( p ){
62181 sqlite3VdbeAddOp0(p, OP_Noop);
62182 va_start(ap, zFormat);
62183 vdbeVComment(p, zFormat, ap);
62184 va_end(ap);
62187 #endif /* NDEBUG */
62190 ** Return the opcode for a given address. If the address is -1, then
62191 ** return the most recently inserted opcode.
62193 ** If a memory allocation error has occurred prior to the calling of this
62194 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
62195 ** is readable but not writable, though it is cast to a writable value.
62196 ** The return of a dummy opcode allows the call to continue functioning
62197 ** after a OOM fault without having to check to see if the return from
62198 ** this routine is a valid pointer. But because the dummy.opcode is 0,
62199 ** dummy will never be written to. This is verified by code inspection and
62200 ** by running with Valgrind.
62202 ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
62203 ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
62204 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
62205 ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
62206 ** having to double-check to make sure that the result is non-negative. But
62207 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
62208 ** check the value of p->nOp-1 before continuing.
62210 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
62211 /* C89 specifies that the constant "dummy" will be initialized to all
62212 ** zeros, which is correct. MSVC generates a warning, nevertheless. */
62213 static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
62214 assert( p->magic==VDBE_MAGIC_INIT );
62215 if( addr<0 ){
62216 #ifdef SQLITE_OMIT_TRACE
62217 if( p->nOp==0 ) return (VdbeOp*)&dummy;
62218 #endif
62219 addr = p->nOp - 1;
62221 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
62222 if( p->db->mallocFailed ){
62223 return (VdbeOp*)&dummy;
62224 }else{
62225 return &p->aOp[addr];
62229 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
62231 ** Return an integer value for one of the parameters to the opcode pOp
62232 ** determined by character c.
62234 static int translateP(char c, const Op *pOp){
62235 if( c=='1' ) return pOp->p1;
62236 if( c=='2' ) return pOp->p2;
62237 if( c=='3' ) return pOp->p3;
62238 if( c=='4' ) return pOp->p4.i;
62239 return pOp->p5;
62243 ** Compute a string for the "comment" field of a VDBE opcode listing.
62245 ** The Synopsis: field in comments in the vdbe.c source file gets converted
62246 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
62247 ** absence of other comments, this synopsis becomes the comment on the opcode.
62248 ** Some translation occurs:
62250 ** "PX" -> "r[X]"
62251 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
62252 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
62253 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
62255 static int displayComment(
62256 const Op *pOp, /* The opcode to be commented */
62257 const char *zP4, /* Previously obtained value for P4 */
62258 char *zTemp, /* Write result here */
62259 int nTemp /* Space available in zTemp[] */
62261 const char *zOpName;
62262 const char *zSynopsis;
62263 int nOpName;
62264 int ii, jj;
62265 zOpName = sqlite3OpcodeName(pOp->opcode);
62266 nOpName = sqlite3Strlen30(zOpName);
62267 if( zOpName[nOpName+1] ){
62268 int seenCom = 0;
62269 char c;
62270 zSynopsis = zOpName += nOpName + 1;
62271 for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
62272 if( c=='P' ){
62273 c = zSynopsis[++ii];
62274 if( c=='4' ){
62275 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
62276 }else if( c=='X' ){
62277 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
62278 seenCom = 1;
62279 }else{
62280 int v1 = translateP(c, pOp);
62281 int v2;
62282 sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
62283 if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
62284 ii += 3;
62285 jj += sqlite3Strlen30(zTemp+jj);
62286 v2 = translateP(zSynopsis[ii], pOp);
62287 if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
62288 ii += 2;
62289 v2++;
62291 if( v2>1 ){
62292 sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
62294 }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
62295 ii += 4;
62298 jj += sqlite3Strlen30(zTemp+jj);
62299 }else{
62300 zTemp[jj++] = c;
62303 if( !seenCom && jj<nTemp-5 && pOp->zComment ){
62304 sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
62305 jj += sqlite3Strlen30(zTemp+jj);
62307 if( jj<nTemp ) zTemp[jj] = 0;
62308 }else if( pOp->zComment ){
62309 sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
62310 jj = sqlite3Strlen30(zTemp);
62311 }else{
62312 zTemp[0] = 0;
62313 jj = 0;
62315 return jj;
62317 #endif /* SQLITE_DEBUG */
62320 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
62321 || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
62323 ** Compute a string that describes the P4 parameter for an opcode.
62324 ** Use zTemp for any required temporary buffer space.
62326 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
62327 char *zP4 = zTemp;
62328 assert( nTemp>=20 );
62329 switch( pOp->p4type ){
62330 case P4_KEYINFO: {
62331 int i, j;
62332 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
62333 assert( pKeyInfo->aSortOrder!=0 );
62334 sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
62335 i = sqlite3Strlen30(zTemp);
62336 for(j=0; j<pKeyInfo->nField; j++){
62337 CollSeq *pColl = pKeyInfo->aColl[j];
62338 const char *zColl = pColl ? pColl->zName : "nil";
62339 int n = sqlite3Strlen30(zColl);
62340 if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
62341 zColl = "B";
62342 n = 1;
62344 if( i+n>nTemp-6 ){
62345 memcpy(&zTemp[i],",...",4);
62346 break;
62348 zTemp[i++] = ',';
62349 if( pKeyInfo->aSortOrder[j] ){
62350 zTemp[i++] = '-';
62352 memcpy(&zTemp[i], zColl, n+1);
62353 i += n;
62355 zTemp[i++] = ')';
62356 zTemp[i] = 0;
62357 assert( i<nTemp );
62358 break;
62360 case P4_COLLSEQ: {
62361 CollSeq *pColl = pOp->p4.pColl;
62362 sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
62363 break;
62365 case P4_FUNCDEF: {
62366 FuncDef *pDef = pOp->p4.pFunc;
62367 sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
62368 break;
62370 case P4_INT64: {
62371 sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
62372 break;
62374 case P4_INT32: {
62375 sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
62376 break;
62378 case P4_REAL: {
62379 sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
62380 break;
62382 case P4_MEM: {
62383 Mem *pMem = pOp->p4.pMem;
62384 if( pMem->flags & MEM_Str ){
62385 zP4 = pMem->z;
62386 }else if( pMem->flags & MEM_Int ){
62387 sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
62388 }else if( pMem->flags & MEM_Real ){
62389 sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
62390 }else if( pMem->flags & MEM_Null ){
62391 sqlite3_snprintf(nTemp, zTemp, "NULL");
62392 }else{
62393 assert( pMem->flags & MEM_Blob );
62394 zP4 = "(blob)";
62396 break;
62398 #ifndef SQLITE_OMIT_VIRTUALTABLE
62399 case P4_VTAB: {
62400 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
62401 sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
62402 break;
62404 #endif
62405 case P4_INTARRAY: {
62406 sqlite3_snprintf(nTemp, zTemp, "intarray");
62407 break;
62409 case P4_SUBPROGRAM: {
62410 sqlite3_snprintf(nTemp, zTemp, "program");
62411 break;
62413 case P4_ADVANCE: {
62414 zTemp[0] = 0;
62415 break;
62417 default: {
62418 zP4 = pOp->p4.z;
62419 if( zP4==0 ){
62420 zP4 = zTemp;
62421 zTemp[0] = 0;
62425 assert( zP4!=0 );
62426 return zP4;
62428 #endif
62431 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
62433 ** The prepared statements need to know in advance the complete set of
62434 ** attached databases that will be use. A mask of these databases
62435 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
62436 ** p->btreeMask of databases that will require a lock.
62438 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
62439 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
62440 assert( i<(int)sizeof(p->btreeMask)*8 );
62441 p->btreeMask |= ((yDbMask)1)<<i;
62442 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
62443 p->lockMask |= ((yDbMask)1)<<i;
62447 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
62449 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
62450 ** this routine obtains the mutex associated with each BtShared structure
62451 ** that may be accessed by the VM passed as an argument. In doing so it also
62452 ** sets the BtShared.db member of each of the BtShared structures, ensuring
62453 ** that the correct busy-handler callback is invoked if required.
62455 ** If SQLite is not threadsafe but does support shared-cache mode, then
62456 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
62457 ** of all of BtShared structures accessible via the database handle
62458 ** associated with the VM.
62460 ** If SQLite is not threadsafe and does not support shared-cache mode, this
62461 ** function is a no-op.
62463 ** The p->btreeMask field is a bitmask of all btrees that the prepared
62464 ** statement p will ever use. Let N be the number of bits in p->btreeMask
62465 ** corresponding to btrees that use shared cache. Then the runtime of
62466 ** this routine is N*N. But as N is rarely more than 1, this should not
62467 ** be a problem.
62469 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
62470 int i;
62471 yDbMask mask;
62472 sqlite3 *db;
62473 Db *aDb;
62474 int nDb;
62475 if( p->lockMask==0 ) return; /* The common case */
62476 db = p->db;
62477 aDb = db->aDb;
62478 nDb = db->nDb;
62479 for(i=0, mask=1; i<nDb; i++, mask += mask){
62480 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
62481 sqlite3BtreeEnter(aDb[i].pBt);
62485 #endif
62487 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
62489 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
62491 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
62492 int i;
62493 yDbMask mask;
62494 sqlite3 *db;
62495 Db *aDb;
62496 int nDb;
62497 if( p->lockMask==0 ) return; /* The common case */
62498 db = p->db;
62499 aDb = db->aDb;
62500 nDb = db->nDb;
62501 for(i=0, mask=1; i<nDb; i++, mask += mask){
62502 if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
62503 sqlite3BtreeLeave(aDb[i].pBt);
62507 #endif
62509 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
62511 ** Print a single opcode. This routine is used for debugging only.
62513 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
62514 char *zP4;
62515 char zPtr[50];
62516 char zCom[100];
62517 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
62518 if( pOut==0 ) pOut = stdout;
62519 zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
62520 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62521 displayComment(pOp, zP4, zCom, sizeof(zCom));
62522 #else
62523 zCom[0] = 0
62524 #endif
62525 /* NB: The sqlite3OpcodeName() function is implemented by code created
62526 ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
62527 ** information from the vdbe.c source text */
62528 fprintf(pOut, zFormat1, pc,
62529 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
62530 zCom
62532 fflush(pOut);
62534 #endif
62537 ** Release an array of N Mem elements
62539 static void releaseMemArray(Mem *p, int N){
62540 if( p && N ){
62541 Mem *pEnd;
62542 sqlite3 *db = p->db;
62543 u8 malloc_failed = db->mallocFailed;
62544 if( db->pnBytesFreed ){
62545 for(pEnd=&p[N]; p<pEnd; p++){
62546 sqlite3DbFree(db, p->zMalloc);
62548 return;
62550 for(pEnd=&p[N]; p<pEnd; p++){
62551 assert( (&p[1])==pEnd || p[0].db==p[1].db );
62553 /* This block is really an inlined version of sqlite3VdbeMemRelease()
62554 ** that takes advantage of the fact that the memory cell value is
62555 ** being set to NULL after releasing any dynamic resources.
62557 ** The justification for duplicating code is that according to
62558 ** callgrind, this causes a certain test case to hit the CPU 4.7
62559 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
62560 ** sqlite3MemRelease() were called from here. With -O2, this jumps
62561 ** to 6.6 percent. The test case is inserting 1000 rows into a table
62562 ** with no indexes using a single prepared INSERT statement, bind()
62563 ** and reset(). Inserts are grouped into a transaction.
62565 if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
62566 sqlite3VdbeMemRelease(p);
62567 }else if( p->zMalloc ){
62568 sqlite3DbFree(db, p->zMalloc);
62569 p->zMalloc = 0;
62572 p->flags = MEM_Invalid;
62574 db->mallocFailed = malloc_failed;
62579 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
62580 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
62582 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
62583 int i;
62584 Mem *aMem = VdbeFrameMem(p);
62585 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
62586 for(i=0; i<p->nChildCsr; i++){
62587 sqlite3VdbeFreeCursor(p->v, apCsr[i]);
62589 releaseMemArray(aMem, p->nChildMem);
62590 sqlite3DbFree(p->v->db, p);
62593 #ifndef SQLITE_OMIT_EXPLAIN
62595 ** Give a listing of the program in the virtual machine.
62597 ** The interface is the same as sqlite3VdbeExec(). But instead of
62598 ** running the code, it invokes the callback once for each instruction.
62599 ** This feature is used to implement "EXPLAIN".
62601 ** When p->explain==1, each instruction is listed. When
62602 ** p->explain==2, only OP_Explain instructions are listed and these
62603 ** are shown in a different format. p->explain==2 is used to implement
62604 ** EXPLAIN QUERY PLAN.
62606 ** When p->explain==1, first the main program is listed, then each of
62607 ** the trigger subprograms are listed one by one.
62609 SQLITE_PRIVATE int sqlite3VdbeList(
62610 Vdbe *p /* The VDBE */
62612 int nRow; /* Stop when row count reaches this */
62613 int nSub = 0; /* Number of sub-vdbes seen so far */
62614 SubProgram **apSub = 0; /* Array of sub-vdbes */
62615 Mem *pSub = 0; /* Memory cell hold array of subprogs */
62616 sqlite3 *db = p->db; /* The database connection */
62617 int i; /* Loop counter */
62618 int rc = SQLITE_OK; /* Return code */
62619 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
62621 assert( p->explain );
62622 assert( p->magic==VDBE_MAGIC_RUN );
62623 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
62625 /* Even though this opcode does not use dynamic strings for
62626 ** the result, result columns may become dynamic if the user calls
62627 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
62629 releaseMemArray(pMem, 8);
62630 p->pResultSet = 0;
62632 if( p->rc==SQLITE_NOMEM ){
62633 /* This happens if a malloc() inside a call to sqlite3_column_text() or
62634 ** sqlite3_column_text16() failed. */
62635 db->mallocFailed = 1;
62636 return SQLITE_ERROR;
62639 /* When the number of output rows reaches nRow, that means the
62640 ** listing has finished and sqlite3_step() should return SQLITE_DONE.
62641 ** nRow is the sum of the number of rows in the main program, plus
62642 ** the sum of the number of rows in all trigger subprograms encountered
62643 ** so far. The nRow value will increase as new trigger subprograms are
62644 ** encountered, but p->pc will eventually catch up to nRow.
62646 nRow = p->nOp;
62647 if( p->explain==1 ){
62648 /* The first 8 memory cells are used for the result set. So we will
62649 ** commandeer the 9th cell to use as storage for an array of pointers
62650 ** to trigger subprograms. The VDBE is guaranteed to have at least 9
62651 ** cells. */
62652 assert( p->nMem>9 );
62653 pSub = &p->aMem[9];
62654 if( pSub->flags&MEM_Blob ){
62655 /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
62656 ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
62657 nSub = pSub->n/sizeof(Vdbe*);
62658 apSub = (SubProgram **)pSub->z;
62660 for(i=0; i<nSub; i++){
62661 nRow += apSub[i]->nOp;
62666 i = p->pc++;
62667 }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
62668 if( i>=nRow ){
62669 p->rc = SQLITE_OK;
62670 rc = SQLITE_DONE;
62671 }else if( db->u1.isInterrupted ){
62672 p->rc = SQLITE_INTERRUPT;
62673 rc = SQLITE_ERROR;
62674 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
62675 }else{
62676 char *zP4;
62677 Op *pOp;
62678 if( i<p->nOp ){
62679 /* The output line number is small enough that we are still in the
62680 ** main program. */
62681 pOp = &p->aOp[i];
62682 }else{
62683 /* We are currently listing subprograms. Figure out which one and
62684 ** pick up the appropriate opcode. */
62685 int j;
62686 i -= p->nOp;
62687 for(j=0; i>=apSub[j]->nOp; j++){
62688 i -= apSub[j]->nOp;
62690 pOp = &apSub[j]->aOp[i];
62692 if( p->explain==1 ){
62693 pMem->flags = MEM_Int;
62694 pMem->type = SQLITE_INTEGER;
62695 pMem->u.i = i; /* Program counter */
62696 pMem++;
62698 pMem->flags = MEM_Static|MEM_Str|MEM_Term;
62699 pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
62700 assert( pMem->z!=0 );
62701 pMem->n = sqlite3Strlen30(pMem->z);
62702 pMem->type = SQLITE_TEXT;
62703 pMem->enc = SQLITE_UTF8;
62704 pMem++;
62706 /* When an OP_Program opcode is encounter (the only opcode that has
62707 ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
62708 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
62709 ** has not already been seen.
62711 if( pOp->p4type==P4_SUBPROGRAM ){
62712 int nByte = (nSub+1)*sizeof(SubProgram*);
62713 int j;
62714 for(j=0; j<nSub; j++){
62715 if( apSub[j]==pOp->p4.pProgram ) break;
62717 if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
62718 apSub = (SubProgram **)pSub->z;
62719 apSub[nSub++] = pOp->p4.pProgram;
62720 pSub->flags |= MEM_Blob;
62721 pSub->n = nSub*sizeof(SubProgram*);
62726 pMem->flags = MEM_Int;
62727 pMem->u.i = pOp->p1; /* P1 */
62728 pMem->type = SQLITE_INTEGER;
62729 pMem++;
62731 pMem->flags = MEM_Int;
62732 pMem->u.i = pOp->p2; /* P2 */
62733 pMem->type = SQLITE_INTEGER;
62734 pMem++;
62736 pMem->flags = MEM_Int;
62737 pMem->u.i = pOp->p3; /* P3 */
62738 pMem->type = SQLITE_INTEGER;
62739 pMem++;
62741 if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
62742 assert( p->db->mallocFailed );
62743 return SQLITE_ERROR;
62745 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
62746 zP4 = displayP4(pOp, pMem->z, 32);
62747 if( zP4!=pMem->z ){
62748 sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
62749 }else{
62750 assert( pMem->z!=0 );
62751 pMem->n = sqlite3Strlen30(pMem->z);
62752 pMem->enc = SQLITE_UTF8;
62754 pMem->type = SQLITE_TEXT;
62755 pMem++;
62757 if( p->explain==1 ){
62758 if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
62759 assert( p->db->mallocFailed );
62760 return SQLITE_ERROR;
62762 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
62763 pMem->n = 2;
62764 sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
62765 pMem->type = SQLITE_TEXT;
62766 pMem->enc = SQLITE_UTF8;
62767 pMem++;
62769 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
62770 if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
62771 assert( p->db->mallocFailed );
62772 return SQLITE_ERROR;
62774 pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
62775 pMem->n = displayComment(pOp, zP4, pMem->z, 500);
62776 pMem->type = SQLITE_TEXT;
62777 pMem->enc = SQLITE_UTF8;
62778 #else
62779 pMem->flags = MEM_Null; /* Comment */
62780 pMem->type = SQLITE_NULL;
62781 #endif
62784 p->nResColumn = 8 - 4*(p->explain-1);
62785 p->pResultSet = &p->aMem[1];
62786 p->rc = SQLITE_OK;
62787 rc = SQLITE_ROW;
62789 return rc;
62791 #endif /* SQLITE_OMIT_EXPLAIN */
62793 #ifdef SQLITE_DEBUG
62795 ** Print the SQL that was used to generate a VDBE program.
62797 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
62798 const char *z = 0;
62799 if( p->zSql ){
62800 z = p->zSql;
62801 }else if( p->nOp>=1 ){
62802 const VdbeOp *pOp = &p->aOp[0];
62803 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
62804 z = pOp->p4.z;
62805 while( sqlite3Isspace(*z) ) z++;
62808 if( z ) printf("SQL: [%s]\n", z);
62810 #endif
62812 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
62814 ** Print an IOTRACE message showing SQL content.
62816 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
62817 int nOp = p->nOp;
62818 VdbeOp *pOp;
62819 if( sqlite3IoTrace==0 ) return;
62820 if( nOp<1 ) return;
62821 pOp = &p->aOp[0];
62822 if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
62823 int i, j;
62824 char z[1000];
62825 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
62826 for(i=0; sqlite3Isspace(z[i]); i++){}
62827 for(j=0; z[i]; i++){
62828 if( sqlite3Isspace(z[i]) ){
62829 if( z[i-1]!=' ' ){
62830 z[j++] = ' ';
62832 }else{
62833 z[j++] = z[i];
62836 z[j] = 0;
62837 sqlite3IoTrace("SQL %s\n", z);
62840 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
62843 ** Allocate space from a fixed size buffer and return a pointer to
62844 ** that space. If insufficient space is available, return NULL.
62846 ** The pBuf parameter is the initial value of a pointer which will
62847 ** receive the new memory. pBuf is normally NULL. If pBuf is not
62848 ** NULL, it means that memory space has already been allocated and that
62849 ** this routine should not allocate any new memory. When pBuf is not
62850 ** NULL simply return pBuf. Only allocate new memory space when pBuf
62851 ** is NULL.
62853 ** nByte is the number of bytes of space needed.
62855 ** *ppFrom points to available space and pEnd points to the end of the
62856 ** available space. When space is allocated, *ppFrom is advanced past
62857 ** the end of the allocated space.
62859 ** *pnByte is a counter of the number of bytes of space that have failed
62860 ** to allocate. If there is insufficient space in *ppFrom to satisfy the
62861 ** request, then increment *pnByte by the amount of the request.
62863 static void *allocSpace(
62864 void *pBuf, /* Where return pointer will be stored */
62865 int nByte, /* Number of bytes to allocate */
62866 u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
62867 u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
62868 int *pnByte /* If allocation cannot be made, increment *pnByte */
62870 assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
62871 if( pBuf ) return pBuf;
62872 nByte = ROUND8(nByte);
62873 if( &(*ppFrom)[nByte] <= pEnd ){
62874 pBuf = (void*)*ppFrom;
62875 *ppFrom += nByte;
62876 }else{
62877 *pnByte += nByte;
62879 return pBuf;
62883 ** Rewind the VDBE back to the beginning in preparation for
62884 ** running it.
62886 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
62887 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
62888 int i;
62889 #endif
62890 assert( p!=0 );
62891 assert( p->magic==VDBE_MAGIC_INIT );
62893 /* There should be at least one opcode.
62895 assert( p->nOp>0 );
62897 /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
62898 p->magic = VDBE_MAGIC_RUN;
62900 #ifdef SQLITE_DEBUG
62901 for(i=1; i<p->nMem; i++){
62902 assert( p->aMem[i].db==p->db );
62904 #endif
62905 p->pc = -1;
62906 p->rc = SQLITE_OK;
62907 p->errorAction = OE_Abort;
62908 p->magic = VDBE_MAGIC_RUN;
62909 p->nChange = 0;
62910 p->cacheCtr = 1;
62911 p->minWriteFileFormat = 255;
62912 p->iStatement = 0;
62913 p->nFkConstraint = 0;
62914 #ifdef VDBE_PROFILE
62915 for(i=0; i<p->nOp; i++){
62916 p->aOp[i].cnt = 0;
62917 p->aOp[i].cycles = 0;
62919 #endif
62923 ** Prepare a virtual machine for execution for the first time after
62924 ** creating the virtual machine. This involves things such
62925 ** as allocating stack space and initializing the program counter.
62926 ** After the VDBE has be prepped, it can be executed by one or more
62927 ** calls to sqlite3VdbeExec().
62929 ** This function may be called exact once on a each virtual machine.
62930 ** After this routine is called the VM has been "packaged" and is ready
62931 ** to run. After this routine is called, futher calls to
62932 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
62933 ** the Vdbe from the Parse object that helped generate it so that the
62934 ** the Vdbe becomes an independent entity and the Parse object can be
62935 ** destroyed.
62937 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
62938 ** to its initial state after it has been run.
62940 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
62941 Vdbe *p, /* The VDBE */
62942 Parse *pParse /* Parsing context */
62944 sqlite3 *db; /* The database connection */
62945 int nVar; /* Number of parameters */
62946 int nMem; /* Number of VM memory registers */
62947 int nCursor; /* Number of cursors required */
62948 int nArg; /* Number of arguments in subprograms */
62949 int nOnce; /* Number of OP_Once instructions */
62950 int n; /* Loop counter */
62951 u8 *zCsr; /* Memory available for allocation */
62952 u8 *zEnd; /* First byte past allocated memory */
62953 int nByte; /* How much extra memory is needed */
62955 assert( p!=0 );
62956 assert( p->nOp>0 );
62957 assert( pParse!=0 );
62958 assert( p->magic==VDBE_MAGIC_INIT );
62959 assert( pParse==p->pParse );
62960 db = p->db;
62961 assert( db->mallocFailed==0 );
62962 nVar = pParse->nVar;
62963 nMem = pParse->nMem;
62964 nCursor = pParse->nTab;
62965 nArg = pParse->nMaxArg;
62966 nOnce = pParse->nOnce;
62967 if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
62969 /* For each cursor required, also allocate a memory cell. Memory
62970 ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
62971 ** the vdbe program. Instead they are used to allocate space for
62972 ** VdbeCursor/BtCursor structures. The blob of memory associated with
62973 ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
62974 ** stores the blob of memory associated with cursor 1, etc.
62976 ** See also: allocateCursor().
62978 nMem += nCursor;
62980 /* Allocate space for memory registers, SQL variables, VDBE cursors and
62981 ** an array to marshal SQL function arguments in.
62983 zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
62984 zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
62986 resolveP2Values(p, &nArg);
62987 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
62988 if( pParse->explain && nMem<10 ){
62989 nMem = 10;
62991 memset(zCsr, 0, zEnd-zCsr);
62992 zCsr += (zCsr - (u8*)0)&7;
62993 assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
62994 p->expired = 0;
62996 /* Memory for registers, parameters, cursor, etc, is allocated in two
62997 ** passes. On the first pass, we try to reuse unused space at the
62998 ** end of the opcode array. If we are unable to satisfy all memory
62999 ** requirements by reusing the opcode array tail, then the second
63000 ** pass will fill in the rest using a fresh allocation.
63002 ** This two-pass approach that reuses as much memory as possible from
63003 ** the leftover space at the end of the opcode array can significantly
63004 ** reduce the amount of memory held by a prepared statement.
63006 do {
63007 nByte = 0;
63008 p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
63009 p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
63010 p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
63011 p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
63012 p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
63013 &zCsr, zEnd, &nByte);
63014 p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
63015 if( nByte ){
63016 p->pFree = sqlite3DbMallocZero(db, nByte);
63018 zCsr = p->pFree;
63019 zEnd = &zCsr[nByte];
63020 }while( nByte && !db->mallocFailed );
63022 p->nCursor = nCursor;
63023 p->nOnceFlag = nOnce;
63024 if( p->aVar ){
63025 p->nVar = (ynVar)nVar;
63026 for(n=0; n<nVar; n++){
63027 p->aVar[n].flags = MEM_Null;
63028 p->aVar[n].db = db;
63031 if( p->azVar ){
63032 p->nzVar = pParse->nzVar;
63033 memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
63034 memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
63036 if( p->aMem ){
63037 p->aMem--; /* aMem[] goes from 1..nMem */
63038 p->nMem = nMem; /* not from 0..nMem-1 */
63039 for(n=1; n<=nMem; n++){
63040 p->aMem[n].flags = MEM_Invalid;
63041 p->aMem[n].db = db;
63044 p->explain = pParse->explain;
63045 sqlite3VdbeRewind(p);
63049 ** Close a VDBE cursor and release all the resources that cursor
63050 ** happens to hold.
63052 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
63053 if( pCx==0 ){
63054 return;
63056 sqlite3VdbeSorterClose(p->db, pCx);
63057 if( pCx->pBt ){
63058 sqlite3BtreeClose(pCx->pBt);
63059 /* The pCx->pCursor will be close automatically, if it exists, by
63060 ** the call above. */
63061 }else if( pCx->pCursor ){
63062 sqlite3BtreeCloseCursor(pCx->pCursor);
63064 #ifndef SQLITE_OMIT_VIRTUALTABLE
63065 if( pCx->pVtabCursor ){
63066 sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
63067 const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
63068 p->inVtabMethod = 1;
63069 pModule->xClose(pVtabCursor);
63070 p->inVtabMethod = 0;
63072 #endif
63076 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
63077 ** is used, for example, when a trigger sub-program is halted to restore
63078 ** control to the main program.
63080 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
63081 Vdbe *v = pFrame->v;
63082 v->aOnceFlag = pFrame->aOnceFlag;
63083 v->nOnceFlag = pFrame->nOnceFlag;
63084 v->aOp = pFrame->aOp;
63085 v->nOp = pFrame->nOp;
63086 v->aMem = pFrame->aMem;
63087 v->nMem = pFrame->nMem;
63088 v->apCsr = pFrame->apCsr;
63089 v->nCursor = pFrame->nCursor;
63090 v->db->lastRowid = pFrame->lastRowid;
63091 v->nChange = pFrame->nChange;
63092 return pFrame->pc;
63096 ** Close all cursors.
63098 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
63099 ** cell array. This is necessary as the memory cell array may contain
63100 ** pointers to VdbeFrame objects, which may in turn contain pointers to
63101 ** open cursors.
63103 static void closeAllCursors(Vdbe *p){
63104 if( p->pFrame ){
63105 VdbeFrame *pFrame;
63106 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
63107 sqlite3VdbeFrameRestore(pFrame);
63109 p->pFrame = 0;
63110 p->nFrame = 0;
63112 if( p->apCsr ){
63113 int i;
63114 for(i=0; i<p->nCursor; i++){
63115 VdbeCursor *pC = p->apCsr[i];
63116 if( pC ){
63117 sqlite3VdbeFreeCursor(p, pC);
63118 p->apCsr[i] = 0;
63122 if( p->aMem ){
63123 releaseMemArray(&p->aMem[1], p->nMem);
63125 while( p->pDelFrame ){
63126 VdbeFrame *pDel = p->pDelFrame;
63127 p->pDelFrame = pDel->pParent;
63128 sqlite3VdbeFrameDelete(pDel);
63131 /* Delete any auxdata allocations made by the VM */
63132 sqlite3VdbeDeleteAuxData(p, -1, 0);
63133 assert( p->pAuxData==0 );
63137 ** Clean up the VM after execution.
63139 ** This routine will automatically close any cursors, lists, and/or
63140 ** sorters that were left open. It also deletes the values of
63141 ** variables in the aVar[] array.
63143 static void Cleanup(Vdbe *p){
63144 sqlite3 *db = p->db;
63146 #ifdef SQLITE_DEBUG
63147 /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
63148 ** Vdbe.aMem[] arrays have already been cleaned up. */
63149 int i;
63150 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
63151 if( p->aMem ){
63152 for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
63154 #endif
63156 sqlite3DbFree(db, p->zErrMsg);
63157 p->zErrMsg = 0;
63158 p->pResultSet = 0;
63162 ** Set the number of result columns that will be returned by this SQL
63163 ** statement. This is now set at compile time, rather than during
63164 ** execution of the vdbe program so that sqlite3_column_count() can
63165 ** be called on an SQL statement before sqlite3_step().
63167 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
63168 Mem *pColName;
63169 int n;
63170 sqlite3 *db = p->db;
63172 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
63173 sqlite3DbFree(db, p->aColName);
63174 n = nResColumn*COLNAME_N;
63175 p->nResColumn = (u16)nResColumn;
63176 p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
63177 if( p->aColName==0 ) return;
63178 while( n-- > 0 ){
63179 pColName->flags = MEM_Null;
63180 pColName->db = p->db;
63181 pColName++;
63186 ** Set the name of the idx'th column to be returned by the SQL statement.
63187 ** zName must be a pointer to a nul terminated string.
63189 ** This call must be made after a call to sqlite3VdbeSetNumCols().
63191 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
63192 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
63193 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
63195 SQLITE_PRIVATE int sqlite3VdbeSetColName(
63196 Vdbe *p, /* Vdbe being configured */
63197 int idx, /* Index of column zName applies to */
63198 int var, /* One of the COLNAME_* constants */
63199 const char *zName, /* Pointer to buffer containing name */
63200 void (*xDel)(void*) /* Memory management strategy for zName */
63202 int rc;
63203 Mem *pColName;
63204 assert( idx<p->nResColumn );
63205 assert( var<COLNAME_N );
63206 if( p->db->mallocFailed ){
63207 assert( !zName || xDel!=SQLITE_DYNAMIC );
63208 return SQLITE_NOMEM;
63210 assert( p->aColName!=0 );
63211 pColName = &(p->aColName[idx+var*p->nResColumn]);
63212 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
63213 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
63214 return rc;
63218 ** A read or write transaction may or may not be active on database handle
63219 ** db. If a transaction is active, commit it. If there is a
63220 ** write-transaction spanning more than one database file, this routine
63221 ** takes care of the master journal trickery.
63223 static int vdbeCommit(sqlite3 *db, Vdbe *p){
63224 int i;
63225 int nTrans = 0; /* Number of databases with an active write-transaction */
63226 int rc = SQLITE_OK;
63227 int needXcommit = 0;
63229 #ifdef SQLITE_OMIT_VIRTUALTABLE
63230 /* With this option, sqlite3VtabSync() is defined to be simply
63231 ** SQLITE_OK so p is not used.
63233 UNUSED_PARAMETER(p);
63234 #endif
63236 /* Before doing anything else, call the xSync() callback for any
63237 ** virtual module tables written in this transaction. This has to
63238 ** be done before determining whether a master journal file is
63239 ** required, as an xSync() callback may add an attached database
63240 ** to the transaction.
63242 rc = sqlite3VtabSync(db, p);
63244 /* This loop determines (a) if the commit hook should be invoked and
63245 ** (b) how many database files have open write transactions, not
63246 ** including the temp database. (b) is important because if more than
63247 ** one database file has an open write transaction, a master journal
63248 ** file is required for an atomic commit.
63250 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63251 Btree *pBt = db->aDb[i].pBt;
63252 if( sqlite3BtreeIsInTrans(pBt) ){
63253 needXcommit = 1;
63254 if( i!=1 ) nTrans++;
63255 sqlite3BtreeEnter(pBt);
63256 rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
63257 sqlite3BtreeLeave(pBt);
63260 if( rc!=SQLITE_OK ){
63261 return rc;
63264 /* If there are any write-transactions at all, invoke the commit hook */
63265 if( needXcommit && db->xCommitCallback ){
63266 rc = db->xCommitCallback(db->pCommitArg);
63267 if( rc ){
63268 return SQLITE_CONSTRAINT_COMMITHOOK;
63272 /* The simple case - no more than one database file (not counting the
63273 ** TEMP database) has a transaction active. There is no need for the
63274 ** master-journal.
63276 ** If the return value of sqlite3BtreeGetFilename() is a zero length
63277 ** string, it means the main database is :memory: or a temp file. In
63278 ** that case we do not support atomic multi-file commits, so use the
63279 ** simple case then too.
63281 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
63282 || nTrans<=1
63284 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63285 Btree *pBt = db->aDb[i].pBt;
63286 if( pBt ){
63287 rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
63291 /* Do the commit only if all databases successfully complete phase 1.
63292 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
63293 ** IO error while deleting or truncating a journal file. It is unlikely,
63294 ** but could happen. In this case abandon processing and return the error.
63296 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63297 Btree *pBt = db->aDb[i].pBt;
63298 if( pBt ){
63299 rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
63302 if( rc==SQLITE_OK ){
63303 sqlite3VtabCommit(db);
63307 /* The complex case - There is a multi-file write-transaction active.
63308 ** This requires a master journal file to ensure the transaction is
63309 ** committed atomicly.
63311 #ifndef SQLITE_OMIT_DISKIO
63312 else{
63313 sqlite3_vfs *pVfs = db->pVfs;
63314 int needSync = 0;
63315 char *zMaster = 0; /* File-name for the master journal */
63316 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
63317 sqlite3_file *pMaster = 0;
63318 i64 offset = 0;
63319 int res;
63320 int retryCount = 0;
63321 int nMainFile;
63323 /* Select a master journal file name */
63324 nMainFile = sqlite3Strlen30(zMainFile);
63325 zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
63326 if( zMaster==0 ) return SQLITE_NOMEM;
63327 do {
63328 u32 iRandom;
63329 if( retryCount ){
63330 if( retryCount>100 ){
63331 sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
63332 sqlite3OsDelete(pVfs, zMaster, 0);
63333 break;
63334 }else if( retryCount==1 ){
63335 sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
63338 retryCount++;
63339 sqlite3_randomness(sizeof(iRandom), &iRandom);
63340 sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
63341 (iRandom>>8)&0xffffff, iRandom&0xff);
63342 /* The antipenultimate character of the master journal name must
63343 ** be "9" to avoid name collisions when using 8+3 filenames. */
63344 assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
63345 sqlite3FileSuffix3(zMainFile, zMaster);
63346 rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
63347 }while( rc==SQLITE_OK && res );
63348 if( rc==SQLITE_OK ){
63349 /* Open the master journal. */
63350 rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
63351 SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
63352 SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
63355 if( rc!=SQLITE_OK ){
63356 sqlite3DbFree(db, zMaster);
63357 return rc;
63360 /* Write the name of each database file in the transaction into the new
63361 ** master journal file. If an error occurs at this point close
63362 ** and delete the master journal file. All the individual journal files
63363 ** still have 'null' as the master journal pointer, so they will roll
63364 ** back independently if a failure occurs.
63366 for(i=0; i<db->nDb; i++){
63367 Btree *pBt = db->aDb[i].pBt;
63368 if( sqlite3BtreeIsInTrans(pBt) ){
63369 char const *zFile = sqlite3BtreeGetJournalname(pBt);
63370 if( zFile==0 ){
63371 continue; /* Ignore TEMP and :memory: databases */
63373 assert( zFile[0]!=0 );
63374 if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
63375 needSync = 1;
63377 rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
63378 offset += sqlite3Strlen30(zFile)+1;
63379 if( rc!=SQLITE_OK ){
63380 sqlite3OsCloseFree(pMaster);
63381 sqlite3OsDelete(pVfs, zMaster, 0);
63382 sqlite3DbFree(db, zMaster);
63383 return rc;
63388 /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
63389 ** flag is set this is not required.
63391 if( needSync
63392 && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
63393 && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
63395 sqlite3OsCloseFree(pMaster);
63396 sqlite3OsDelete(pVfs, zMaster, 0);
63397 sqlite3DbFree(db, zMaster);
63398 return rc;
63401 /* Sync all the db files involved in the transaction. The same call
63402 ** sets the master journal pointer in each individual journal. If
63403 ** an error occurs here, do not delete the master journal file.
63405 ** If the error occurs during the first call to
63406 ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
63407 ** master journal file will be orphaned. But we cannot delete it,
63408 ** in case the master journal file name was written into the journal
63409 ** file before the failure occurred.
63411 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
63412 Btree *pBt = db->aDb[i].pBt;
63413 if( pBt ){
63414 rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
63417 sqlite3OsCloseFree(pMaster);
63418 assert( rc!=SQLITE_BUSY );
63419 if( rc!=SQLITE_OK ){
63420 sqlite3DbFree(db, zMaster);
63421 return rc;
63424 /* Delete the master journal file. This commits the transaction. After
63425 ** doing this the directory is synced again before any individual
63426 ** transaction files are deleted.
63428 rc = sqlite3OsDelete(pVfs, zMaster, 1);
63429 sqlite3DbFree(db, zMaster);
63430 zMaster = 0;
63431 if( rc ){
63432 return rc;
63435 /* All files and directories have already been synced, so the following
63436 ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
63437 ** deleting or truncating journals. If something goes wrong while
63438 ** this is happening we don't really care. The integrity of the
63439 ** transaction is already guaranteed, but some stray 'cold' journals
63440 ** may be lying around. Returning an error code won't help matters.
63442 disable_simulated_io_errors();
63443 sqlite3BeginBenignMalloc();
63444 for(i=0; i<db->nDb; i++){
63445 Btree *pBt = db->aDb[i].pBt;
63446 if( pBt ){
63447 sqlite3BtreeCommitPhaseTwo(pBt, 1);
63450 sqlite3EndBenignMalloc();
63451 enable_simulated_io_errors();
63453 sqlite3VtabCommit(db);
63455 #endif
63457 return rc;
63461 ** This routine checks that the sqlite3.nVdbeActive count variable
63462 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
63463 ** currently active. An assertion fails if the two counts do not match.
63464 ** This is an internal self-check only - it is not an essential processing
63465 ** step.
63467 ** This is a no-op if NDEBUG is defined.
63469 #ifndef NDEBUG
63470 static void checkActiveVdbeCnt(sqlite3 *db){
63471 Vdbe *p;
63472 int cnt = 0;
63473 int nWrite = 0;
63474 int nRead = 0;
63475 p = db->pVdbe;
63476 while( p ){
63477 if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
63478 cnt++;
63479 if( p->readOnly==0 ) nWrite++;
63480 if( p->bIsReader ) nRead++;
63482 p = p->pNext;
63484 assert( cnt==db->nVdbeActive );
63485 assert( nWrite==db->nVdbeWrite );
63486 assert( nRead==db->nVdbeRead );
63488 #else
63489 #define checkActiveVdbeCnt(x)
63490 #endif
63493 ** If the Vdbe passed as the first argument opened a statement-transaction,
63494 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
63495 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
63496 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
63497 ** statement transaction is committed.
63499 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
63500 ** Otherwise SQLITE_OK.
63502 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
63503 sqlite3 *const db = p->db;
63504 int rc = SQLITE_OK;
63506 /* If p->iStatement is greater than zero, then this Vdbe opened a
63507 ** statement transaction that should be closed here. The only exception
63508 ** is that an IO error may have occurred, causing an emergency rollback.
63509 ** In this case (db->nStatement==0), and there is nothing to do.
63511 if( db->nStatement && p->iStatement ){
63512 int i;
63513 const int iSavepoint = p->iStatement-1;
63515 assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
63516 assert( db->nStatement>0 );
63517 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
63519 for(i=0; i<db->nDb; i++){
63520 int rc2 = SQLITE_OK;
63521 Btree *pBt = db->aDb[i].pBt;
63522 if( pBt ){
63523 if( eOp==SAVEPOINT_ROLLBACK ){
63524 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
63526 if( rc2==SQLITE_OK ){
63527 rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
63529 if( rc==SQLITE_OK ){
63530 rc = rc2;
63534 db->nStatement--;
63535 p->iStatement = 0;
63537 if( rc==SQLITE_OK ){
63538 if( eOp==SAVEPOINT_ROLLBACK ){
63539 rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
63541 if( rc==SQLITE_OK ){
63542 rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
63546 /* If the statement transaction is being rolled back, also restore the
63547 ** database handles deferred constraint counter to the value it had when
63548 ** the statement transaction was opened. */
63549 if( eOp==SAVEPOINT_ROLLBACK ){
63550 db->nDeferredCons = p->nStmtDefCons;
63551 db->nDeferredImmCons = p->nStmtDefImmCons;
63554 return rc;
63558 ** This function is called when a transaction opened by the database
63559 ** handle associated with the VM passed as an argument is about to be
63560 ** committed. If there are outstanding deferred foreign key constraint
63561 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
63563 ** If there are outstanding FK violations and this function returns
63564 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
63565 ** and write an error message to it. Then return SQLITE_ERROR.
63567 #ifndef SQLITE_OMIT_FOREIGN_KEY
63568 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
63569 sqlite3 *db = p->db;
63570 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
63571 || (!deferred && p->nFkConstraint>0)
63573 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
63574 p->errorAction = OE_Abort;
63575 sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
63576 return SQLITE_ERROR;
63578 return SQLITE_OK;
63580 #endif
63583 ** This routine is called the when a VDBE tries to halt. If the VDBE
63584 ** has made changes and is in autocommit mode, then commit those
63585 ** changes. If a rollback is needed, then do the rollback.
63587 ** This routine is the only way to move the state of a VM from
63588 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
63589 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
63591 ** Return an error code. If the commit could not complete because of
63592 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
63593 ** means the close did not happen and needs to be repeated.
63595 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
63596 int rc; /* Used to store transient return codes */
63597 sqlite3 *db = p->db;
63599 /* This function contains the logic that determines if a statement or
63600 ** transaction will be committed or rolled back as a result of the
63601 ** execution of this virtual machine.
63603 ** If any of the following errors occur:
63605 ** SQLITE_NOMEM
63606 ** SQLITE_IOERR
63607 ** SQLITE_FULL
63608 ** SQLITE_INTERRUPT
63610 ** Then the internal cache might have been left in an inconsistent
63611 ** state. We need to rollback the statement transaction, if there is
63612 ** one, or the complete transaction if there is no statement transaction.
63615 if( p->db->mallocFailed ){
63616 p->rc = SQLITE_NOMEM;
63618 if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
63619 closeAllCursors(p);
63620 if( p->magic!=VDBE_MAGIC_RUN ){
63621 return SQLITE_OK;
63623 checkActiveVdbeCnt(db);
63625 /* No commit or rollback needed if the program never started or if the
63626 ** SQL statement does not read or write a database file. */
63627 if( p->pc>=0 && p->bIsReader ){
63628 int mrc; /* Primary error code from p->rc */
63629 int eStatementOp = 0;
63630 int isSpecialError; /* Set to true if a 'special' error */
63632 /* Lock all btrees used by the statement */
63633 sqlite3VdbeEnter(p);
63635 /* Check for one of the special errors */
63636 mrc = p->rc & 0xff;
63637 assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
63638 isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
63639 || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
63640 if( isSpecialError ){
63641 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
63642 ** no rollback is necessary. Otherwise, at least a savepoint
63643 ** transaction must be rolled back to restore the database to a
63644 ** consistent state.
63646 ** Even if the statement is read-only, it is important to perform
63647 ** a statement or transaction rollback operation. If the error
63648 ** occurred while writing to the journal, sub-journal or database
63649 ** file as part of an effort to free up cache space (see function
63650 ** pagerStress() in pager.c), the rollback is required to restore
63651 ** the pager to a consistent state.
63653 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
63654 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
63655 eStatementOp = SAVEPOINT_ROLLBACK;
63656 }else{
63657 /* We are forced to roll back the active transaction. Before doing
63658 ** so, abort any other statements this handle currently has active.
63660 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
63661 sqlite3CloseSavepoints(db);
63662 db->autoCommit = 1;
63667 /* Check for immediate foreign key violations. */
63668 if( p->rc==SQLITE_OK ){
63669 sqlite3VdbeCheckFk(p, 0);
63672 /* If the auto-commit flag is set and this is the only active writer
63673 ** VM, then we do either a commit or rollback of the current transaction.
63675 ** Note: This block also runs if one of the special errors handled
63676 ** above has occurred.
63678 if( !sqlite3VtabInSync(db)
63679 && db->autoCommit
63680 && db->nVdbeWrite==(p->readOnly==0)
63682 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
63683 rc = sqlite3VdbeCheckFk(p, 1);
63684 if( rc!=SQLITE_OK ){
63685 if( NEVER(p->readOnly) ){
63686 sqlite3VdbeLeave(p);
63687 return SQLITE_ERROR;
63689 rc = SQLITE_CONSTRAINT_FOREIGNKEY;
63690 }else{
63691 /* The auto-commit flag is true, the vdbe program was successful
63692 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
63693 ** key constraints to hold up the transaction. This means a commit
63694 ** is required. */
63695 rc = vdbeCommit(db, p);
63697 if( rc==SQLITE_BUSY && p->readOnly ){
63698 sqlite3VdbeLeave(p);
63699 return SQLITE_BUSY;
63700 }else if( rc!=SQLITE_OK ){
63701 p->rc = rc;
63702 sqlite3RollbackAll(db, SQLITE_OK);
63703 }else{
63704 db->nDeferredCons = 0;
63705 db->nDeferredImmCons = 0;
63706 db->flags &= ~SQLITE_DeferFKs;
63707 sqlite3CommitInternalChanges(db);
63709 }else{
63710 sqlite3RollbackAll(db, SQLITE_OK);
63712 db->nStatement = 0;
63713 }else if( eStatementOp==0 ){
63714 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
63715 eStatementOp = SAVEPOINT_RELEASE;
63716 }else if( p->errorAction==OE_Abort ){
63717 eStatementOp = SAVEPOINT_ROLLBACK;
63718 }else{
63719 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
63720 sqlite3CloseSavepoints(db);
63721 db->autoCommit = 1;
63725 /* If eStatementOp is non-zero, then a statement transaction needs to
63726 ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
63727 ** do so. If this operation returns an error, and the current statement
63728 ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
63729 ** current statement error code.
63731 if( eStatementOp ){
63732 rc = sqlite3VdbeCloseStatement(p, eStatementOp);
63733 if( rc ){
63734 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
63735 p->rc = rc;
63736 sqlite3DbFree(db, p->zErrMsg);
63737 p->zErrMsg = 0;
63739 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
63740 sqlite3CloseSavepoints(db);
63741 db->autoCommit = 1;
63745 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
63746 ** has been rolled back, update the database connection change-counter.
63748 if( p->changeCntOn ){
63749 if( eStatementOp!=SAVEPOINT_ROLLBACK ){
63750 sqlite3VdbeSetChanges(db, p->nChange);
63751 }else{
63752 sqlite3VdbeSetChanges(db, 0);
63754 p->nChange = 0;
63757 /* Release the locks */
63758 sqlite3VdbeLeave(p);
63761 /* We have successfully halted and closed the VM. Record this fact. */
63762 if( p->pc>=0 ){
63763 db->nVdbeActive--;
63764 if( !p->readOnly ) db->nVdbeWrite--;
63765 if( p->bIsReader ) db->nVdbeRead--;
63766 assert( db->nVdbeActive>=db->nVdbeRead );
63767 assert( db->nVdbeRead>=db->nVdbeWrite );
63768 assert( db->nVdbeWrite>=0 );
63770 p->magic = VDBE_MAGIC_HALT;
63771 checkActiveVdbeCnt(db);
63772 if( p->db->mallocFailed ){
63773 p->rc = SQLITE_NOMEM;
63776 /* If the auto-commit flag is set to true, then any locks that were held
63777 ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
63778 ** to invoke any required unlock-notify callbacks.
63780 if( db->autoCommit ){
63781 sqlite3ConnectionUnlocked(db);
63784 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
63785 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
63790 ** Each VDBE holds the result of the most recent sqlite3_step() call
63791 ** in p->rc. This routine sets that result back to SQLITE_OK.
63793 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
63794 p->rc = SQLITE_OK;
63798 ** Copy the error code and error message belonging to the VDBE passed
63799 ** as the first argument to its database handle (so that they will be
63800 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
63802 ** This function does not clear the VDBE error code or message, just
63803 ** copies them to the database handle.
63805 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
63806 sqlite3 *db = p->db;
63807 int rc = p->rc;
63808 if( p->zErrMsg ){
63809 u8 mallocFailed = db->mallocFailed;
63810 sqlite3BeginBenignMalloc();
63811 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
63812 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
63813 sqlite3EndBenignMalloc();
63814 db->mallocFailed = mallocFailed;
63815 db->errCode = rc;
63816 }else{
63817 sqlite3Error(db, rc, 0);
63819 return rc;
63822 #ifdef SQLITE_ENABLE_SQLLOG
63824 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
63825 ** invoke it.
63827 static void vdbeInvokeSqllog(Vdbe *v){
63828 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
63829 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
63830 assert( v->db->init.busy==0 );
63831 if( zExpanded ){
63832 sqlite3GlobalConfig.xSqllog(
63833 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
63835 sqlite3DbFree(v->db, zExpanded);
63839 #else
63840 # define vdbeInvokeSqllog(x)
63841 #endif
63844 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
63845 ** Write any error messages into *pzErrMsg. Return the result code.
63847 ** After this routine is run, the VDBE should be ready to be executed
63848 ** again.
63850 ** To look at it another way, this routine resets the state of the
63851 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
63852 ** VDBE_MAGIC_INIT.
63854 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
63855 sqlite3 *db;
63856 db = p->db;
63858 /* If the VM did not run to completion or if it encountered an
63859 ** error, then it might not have been halted properly. So halt
63860 ** it now.
63862 sqlite3VdbeHalt(p);
63864 /* If the VDBE has be run even partially, then transfer the error code
63865 ** and error message from the VDBE into the main database structure. But
63866 ** if the VDBE has just been set to run but has not actually executed any
63867 ** instructions yet, leave the main database error information unchanged.
63869 if( p->pc>=0 ){
63870 vdbeInvokeSqllog(p);
63871 sqlite3VdbeTransferError(p);
63872 sqlite3DbFree(db, p->zErrMsg);
63873 p->zErrMsg = 0;
63874 if( p->runOnlyOnce ) p->expired = 1;
63875 }else if( p->rc && p->expired ){
63876 /* The expired flag was set on the VDBE before the first call
63877 ** to sqlite3_step(). For consistency (since sqlite3_step() was
63878 ** called), set the database error in this case as well.
63880 sqlite3Error(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
63881 sqlite3DbFree(db, p->zErrMsg);
63882 p->zErrMsg = 0;
63885 /* Reclaim all memory used by the VDBE
63887 Cleanup(p);
63889 /* Save profiling information from this VDBE run.
63891 #ifdef VDBE_PROFILE
63893 FILE *out = fopen("vdbe_profile.out", "a");
63894 if( out ){
63895 int i;
63896 fprintf(out, "---- ");
63897 for(i=0; i<p->nOp; i++){
63898 fprintf(out, "%02x", p->aOp[i].opcode);
63900 fprintf(out, "\n");
63901 for(i=0; i<p->nOp; i++){
63902 fprintf(out, "%6d %10lld %8lld ",
63903 p->aOp[i].cnt,
63904 p->aOp[i].cycles,
63905 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
63907 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
63909 fclose(out);
63912 #endif
63913 p->iCurrentTime = 0;
63914 p->magic = VDBE_MAGIC_INIT;
63915 return p->rc & db->errMask;
63919 ** Clean up and delete a VDBE after execution. Return an integer which is
63920 ** the result code. Write any error message text into *pzErrMsg.
63922 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
63923 int rc = SQLITE_OK;
63924 if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
63925 rc = sqlite3VdbeReset(p);
63926 assert( (rc & p->db->errMask)==rc );
63928 sqlite3VdbeDelete(p);
63929 return rc;
63933 ** If parameter iOp is less than zero, then invoke the destructor for
63934 ** all auxiliary data pointers currently cached by the VM passed as
63935 ** the first argument.
63937 ** Or, if iOp is greater than or equal to zero, then the destructor is
63938 ** only invoked for those auxiliary data pointers created by the user
63939 ** function invoked by the OP_Function opcode at instruction iOp of
63940 ** VM pVdbe, and only then if:
63942 ** * the associated function parameter is the 32nd or later (counting
63943 ** from left to right), or
63945 ** * the corresponding bit in argument mask is clear (where the first
63946 ** function parameter corrsponds to bit 0 etc.).
63948 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
63949 AuxData **pp = &pVdbe->pAuxData;
63950 while( *pp ){
63951 AuxData *pAux = *pp;
63952 if( (iOp<0)
63953 || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
63955 testcase( pAux->iArg==31 );
63956 if( pAux->xDelete ){
63957 pAux->xDelete(pAux->pAux);
63959 *pp = pAux->pNext;
63960 sqlite3DbFree(pVdbe->db, pAux);
63961 }else{
63962 pp= &pAux->pNext;
63968 ** Free all memory associated with the Vdbe passed as the second argument,
63969 ** except for object itself, which is preserved.
63971 ** The difference between this function and sqlite3VdbeDelete() is that
63972 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
63973 ** the database connection and frees the object itself.
63975 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
63976 SubProgram *pSub, *pNext;
63977 int i;
63978 assert( p->db==0 || p->db==db );
63979 releaseMemArray(p->aVar, p->nVar);
63980 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
63981 for(pSub=p->pProgram; pSub; pSub=pNext){
63982 pNext = pSub->pNext;
63983 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
63984 sqlite3DbFree(db, pSub);
63986 for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
63987 vdbeFreeOpArray(db, p->aOp, p->nOp);
63988 sqlite3DbFree(db, p->aColName);
63989 sqlite3DbFree(db, p->zSql);
63990 sqlite3DbFree(db, p->pFree);
63991 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
63992 sqlite3DbFree(db, p->zExplain);
63993 sqlite3DbFree(db, p->pExplain);
63994 #endif
63998 ** Delete an entire VDBE.
64000 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
64001 sqlite3 *db;
64003 if( NEVER(p==0) ) return;
64004 db = p->db;
64005 assert( sqlite3_mutex_held(db->mutex) );
64006 sqlite3VdbeClearObject(db, p);
64007 if( p->pPrev ){
64008 p->pPrev->pNext = p->pNext;
64009 }else{
64010 assert( db->pVdbe==p );
64011 db->pVdbe = p->pNext;
64013 if( p->pNext ){
64014 p->pNext->pPrev = p->pPrev;
64016 p->magic = VDBE_MAGIC_DEAD;
64017 p->db = 0;
64018 sqlite3DbFree(db, p);
64022 ** Make sure the cursor p is ready to read or write the row to which it
64023 ** was last positioned. Return an error code if an OOM fault or I/O error
64024 ** prevents us from positioning the cursor to its correct position.
64026 ** If a MoveTo operation is pending on the given cursor, then do that
64027 ** MoveTo now. If no move is pending, check to see if the row has been
64028 ** deleted out from under the cursor and if it has, mark the row as
64029 ** a NULL row.
64031 ** If the cursor is already pointing to the correct row and that row has
64032 ** not been deleted out from under the cursor, then this routine is a no-op.
64034 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
64035 if( p->deferredMoveto ){
64036 int res, rc;
64037 #ifdef SQLITE_TEST
64038 extern int sqlite3_search_count;
64039 #endif
64040 assert( p->isTable );
64041 rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
64042 if( rc ) return rc;
64043 p->lastRowid = p->movetoTarget;
64044 if( res!=0 ) return SQLITE_CORRUPT_BKPT;
64045 p->rowidIsValid = 1;
64046 #ifdef SQLITE_TEST
64047 sqlite3_search_count++;
64048 #endif
64049 p->deferredMoveto = 0;
64050 p->cacheStatus = CACHE_STALE;
64051 }else if( p->pCursor ){
64052 int hasMoved;
64053 int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
64054 if( rc ) return rc;
64055 if( hasMoved ){
64056 p->cacheStatus = CACHE_STALE;
64057 p->nullRow = 1;
64060 return SQLITE_OK;
64064 ** The following functions:
64066 ** sqlite3VdbeSerialType()
64067 ** sqlite3VdbeSerialTypeLen()
64068 ** sqlite3VdbeSerialLen()
64069 ** sqlite3VdbeSerialPut()
64070 ** sqlite3VdbeSerialGet()
64072 ** encapsulate the code that serializes values for storage in SQLite
64073 ** data and index records. Each serialized value consists of a
64074 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
64075 ** integer, stored as a varint.
64077 ** In an SQLite index record, the serial type is stored directly before
64078 ** the blob of data that it corresponds to. In a table record, all serial
64079 ** types are stored at the start of the record, and the blobs of data at
64080 ** the end. Hence these functions allow the caller to handle the
64081 ** serial-type and data blob separately.
64083 ** The following table describes the various storage classes for data:
64085 ** serial type bytes of data type
64086 ** -------------- --------------- ---------------
64087 ** 0 0 NULL
64088 ** 1 1 signed integer
64089 ** 2 2 signed integer
64090 ** 3 3 signed integer
64091 ** 4 4 signed integer
64092 ** 5 6 signed integer
64093 ** 6 8 signed integer
64094 ** 7 8 IEEE float
64095 ** 8 0 Integer constant 0
64096 ** 9 0 Integer constant 1
64097 ** 10,11 reserved for expansion
64098 ** N>=12 and even (N-12)/2 BLOB
64099 ** N>=13 and odd (N-13)/2 text
64101 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
64102 ** of SQLite will not understand those serial types.
64106 ** Return the serial-type for the value stored in pMem.
64108 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
64109 int flags = pMem->flags;
64110 int n;
64112 if( flags&MEM_Null ){
64113 return 0;
64115 if( flags&MEM_Int ){
64116 /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
64117 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
64118 i64 i = pMem->u.i;
64119 u64 u;
64120 if( i<0 ){
64121 if( i<(-MAX_6BYTE) ) return 6;
64122 /* Previous test prevents: u = -(-9223372036854775808) */
64123 u = -i;
64124 }else{
64125 u = i;
64127 if( u<=127 ){
64128 return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
64130 if( u<=32767 ) return 2;
64131 if( u<=8388607 ) return 3;
64132 if( u<=2147483647 ) return 4;
64133 if( u<=MAX_6BYTE ) return 5;
64134 return 6;
64136 if( flags&MEM_Real ){
64137 return 7;
64139 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
64140 n = pMem->n;
64141 if( flags & MEM_Zero ){
64142 n += pMem->u.nZero;
64144 assert( n>=0 );
64145 return ((n*2) + 12 + ((flags&MEM_Str)!=0));
64149 ** Return the length of the data corresponding to the supplied serial-type.
64151 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
64152 if( serial_type>=12 ){
64153 return (serial_type-12)/2;
64154 }else{
64155 static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
64156 return aSize[serial_type];
64161 ** If we are on an architecture with mixed-endian floating
64162 ** points (ex: ARM7) then swap the lower 4 bytes with the
64163 ** upper 4 bytes. Return the result.
64165 ** For most architectures, this is a no-op.
64167 ** (later): It is reported to me that the mixed-endian problem
64168 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
64169 ** that early versions of GCC stored the two words of a 64-bit
64170 ** float in the wrong order. And that error has been propagated
64171 ** ever since. The blame is not necessarily with GCC, though.
64172 ** GCC might have just copying the problem from a prior compiler.
64173 ** I am also told that newer versions of GCC that follow a different
64174 ** ABI get the byte order right.
64176 ** Developers using SQLite on an ARM7 should compile and run their
64177 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
64178 ** enabled, some asserts below will ensure that the byte order of
64179 ** floating point values is correct.
64181 ** (2007-08-30) Frank van Vugt has studied this problem closely
64182 ** and has send his findings to the SQLite developers. Frank
64183 ** writes that some Linux kernels offer floating point hardware
64184 ** emulation that uses only 32-bit mantissas instead of a full
64185 ** 48-bits as required by the IEEE standard. (This is the
64186 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
64187 ** byte swapping becomes very complicated. To avoid problems,
64188 ** the necessary byte swapping is carried out using a 64-bit integer
64189 ** rather than a 64-bit float. Frank assures us that the code here
64190 ** works for him. We, the developers, have no way to independently
64191 ** verify this, but Frank seems to know what he is talking about
64192 ** so we trust him.
64194 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
64195 static u64 floatSwap(u64 in){
64196 union {
64197 u64 r;
64198 u32 i[2];
64199 } u;
64200 u32 t;
64202 u.r = in;
64203 t = u.i[0];
64204 u.i[0] = u.i[1];
64205 u.i[1] = t;
64206 return u.r;
64208 # define swapMixedEndianFloat(X) X = floatSwap(X)
64209 #else
64210 # define swapMixedEndianFloat(X)
64211 #endif
64214 ** Write the serialized data blob for the value stored in pMem into
64215 ** buf. It is assumed that the caller has allocated sufficient space.
64216 ** Return the number of bytes written.
64218 ** nBuf is the amount of space left in buf[]. The caller is responsible
64219 ** for allocating enough space to buf[] to hold the entire field, exclusive
64220 ** of the pMem->u.nZero bytes for a MEM_Zero value.
64222 ** Return the number of bytes actually written into buf[]. The number
64223 ** of bytes in the zero-filled tail is included in the return value only
64224 ** if those bytes were zeroed in buf[].
64226 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
64227 u32 len;
64229 /* Integer and Real */
64230 if( serial_type<=7 && serial_type>0 ){
64231 u64 v;
64232 u32 i;
64233 if( serial_type==7 ){
64234 assert( sizeof(v)==sizeof(pMem->r) );
64235 memcpy(&v, &pMem->r, sizeof(v));
64236 swapMixedEndianFloat(v);
64237 }else{
64238 v = pMem->u.i;
64240 len = i = sqlite3VdbeSerialTypeLen(serial_type);
64241 while( i-- ){
64242 buf[i] = (u8)(v&0xFF);
64243 v >>= 8;
64245 return len;
64248 /* String or blob */
64249 if( serial_type>=12 ){
64250 assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
64251 == (int)sqlite3VdbeSerialTypeLen(serial_type) );
64252 len = pMem->n;
64253 memcpy(buf, pMem->z, len);
64254 return len;
64257 /* NULL or constants 0 or 1 */
64258 return 0;
64262 ** Deserialize the data blob pointed to by buf as serial type serial_type
64263 ** and store the result in pMem. Return the number of bytes read.
64265 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
64266 const unsigned char *buf, /* Buffer to deserialize from */
64267 u32 serial_type, /* Serial type to deserialize */
64268 Mem *pMem /* Memory cell to write value into */
64270 u64 x;
64271 u32 y;
64272 int i;
64273 switch( serial_type ){
64274 case 10: /* Reserved for future use */
64275 case 11: /* Reserved for future use */
64276 case 0: { /* NULL */
64277 pMem->flags = MEM_Null;
64278 break;
64280 case 1: { /* 1-byte signed integer */
64281 pMem->u.i = (signed char)buf[0];
64282 pMem->flags = MEM_Int;
64283 return 1;
64285 case 2: { /* 2-byte signed integer */
64286 i = 256*(signed char)buf[0] | buf[1];
64287 pMem->u.i = (i64)i;
64288 pMem->flags = MEM_Int;
64289 return 2;
64291 case 3: { /* 3-byte signed integer */
64292 i = 65536*(signed char)buf[0] | (buf[1]<<8) | buf[2];
64293 pMem->u.i = (i64)i;
64294 pMem->flags = MEM_Int;
64295 return 3;
64297 case 4: { /* 4-byte signed integer */
64298 y = ((unsigned)buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
64299 pMem->u.i = (i64)*(int*)&y;
64300 pMem->flags = MEM_Int;
64301 return 4;
64303 case 5: { /* 6-byte signed integer */
64304 x = 256*(signed char)buf[0] + buf[1];
64305 y = ((unsigned)buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
64306 x = (x<<32) | y;
64307 pMem->u.i = *(i64*)&x;
64308 pMem->flags = MEM_Int;
64309 return 6;
64311 case 6: /* 8-byte signed integer */
64312 case 7: { /* IEEE floating point */
64313 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
64314 /* Verify that integers and floating point values use the same
64315 ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
64316 ** defined that 64-bit floating point values really are mixed
64317 ** endian.
64319 static const u64 t1 = ((u64)0x3ff00000)<<32;
64320 static const double r1 = 1.0;
64321 u64 t2 = t1;
64322 swapMixedEndianFloat(t2);
64323 assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
64324 #endif
64325 x = ((unsigned)buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
64326 y = ((unsigned)buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
64327 x = (x<<32) | y;
64328 if( serial_type==6 ){
64329 pMem->u.i = *(i64*)&x;
64330 pMem->flags = MEM_Int;
64331 }else{
64332 assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
64333 swapMixedEndianFloat(x);
64334 memcpy(&pMem->r, &x, sizeof(x));
64335 pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
64337 return 8;
64339 case 8: /* Integer 0 */
64340 case 9: { /* Integer 1 */
64341 pMem->u.i = serial_type-8;
64342 pMem->flags = MEM_Int;
64343 return 0;
64345 default: {
64346 static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
64347 u32 len = (serial_type-12)/2;
64348 pMem->z = (char *)buf;
64349 pMem->n = len;
64350 pMem->xDel = 0;
64351 pMem->flags = aFlag[serial_type&1];
64352 return len;
64355 return 0;
64359 ** This routine is used to allocate sufficient space for an UnpackedRecord
64360 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
64361 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
64363 ** The space is either allocated using sqlite3DbMallocRaw() or from within
64364 ** the unaligned buffer passed via the second and third arguments (presumably
64365 ** stack space). If the former, then *ppFree is set to a pointer that should
64366 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
64367 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
64368 ** before returning.
64370 ** If an OOM error occurs, NULL is returned.
64372 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
64373 KeyInfo *pKeyInfo, /* Description of the record */
64374 char *pSpace, /* Unaligned space available */
64375 int szSpace, /* Size of pSpace[] in bytes */
64376 char **ppFree /* OUT: Caller should free this pointer */
64378 UnpackedRecord *p; /* Unpacked record to return */
64379 int nOff; /* Increment pSpace by nOff to align it */
64380 int nByte; /* Number of bytes required for *p */
64382 /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
64383 ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
64384 ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
64386 nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
64387 nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
64388 if( nByte>szSpace+nOff ){
64389 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
64390 *ppFree = (char *)p;
64391 if( !p ) return 0;
64392 }else{
64393 p = (UnpackedRecord*)&pSpace[nOff];
64394 *ppFree = 0;
64397 p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
64398 assert( pKeyInfo->aSortOrder!=0 );
64399 p->pKeyInfo = pKeyInfo;
64400 p->nField = pKeyInfo->nField + 1;
64401 return p;
64405 ** Given the nKey-byte encoding of a record in pKey[], populate the
64406 ** UnpackedRecord structure indicated by the fourth argument with the
64407 ** contents of the decoded record.
64409 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
64410 KeyInfo *pKeyInfo, /* Information about the record format */
64411 int nKey, /* Size of the binary record */
64412 const void *pKey, /* The binary record */
64413 UnpackedRecord *p /* Populate this structure before returning. */
64415 const unsigned char *aKey = (const unsigned char *)pKey;
64416 int d;
64417 u32 idx; /* Offset in aKey[] to read from */
64418 u16 u; /* Unsigned loop counter */
64419 u32 szHdr;
64420 Mem *pMem = p->aMem;
64422 p->flags = 0;
64423 assert( EIGHT_BYTE_ALIGNMENT(pMem) );
64424 idx = getVarint32(aKey, szHdr);
64425 d = szHdr;
64426 u = 0;
64427 while( idx<szHdr && u<p->nField && d<=nKey ){
64428 u32 serial_type;
64430 idx += getVarint32(&aKey[idx], serial_type);
64431 pMem->enc = pKeyInfo->enc;
64432 pMem->db = pKeyInfo->db;
64433 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
64434 pMem->zMalloc = 0;
64435 d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
64436 pMem++;
64437 u++;
64439 assert( u<=pKeyInfo->nField + 1 );
64440 p->nField = u;
64444 ** This function compares the two table rows or index records
64445 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
64446 ** or positive integer if key1 is less than, equal to or
64447 ** greater than key2. The {nKey1, pKey1} key must be a blob
64448 ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
64449 ** key must be a parsed key such as obtained from
64450 ** sqlite3VdbeParseRecord.
64452 ** Key1 and Key2 do not have to contain the same number of fields.
64453 ** The key with fewer fields is usually compares less than the
64454 ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
64455 ** and the common prefixes are equal, then key1 is less than key2.
64456 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
64457 ** equal, then the keys are considered to be equal and
64458 ** the parts beyond the common prefix are ignored.
64460 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
64461 int nKey1, const void *pKey1, /* Left key */
64462 UnpackedRecord *pPKey2 /* Right key */
64464 u32 d1; /* Offset into aKey[] of next data element */
64465 u32 idx1; /* Offset into aKey[] of next header element */
64466 u32 szHdr1; /* Number of bytes in header */
64467 int i = 0;
64468 int rc = 0;
64469 const unsigned char *aKey1 = (const unsigned char *)pKey1;
64470 KeyInfo *pKeyInfo;
64471 Mem mem1;
64473 pKeyInfo = pPKey2->pKeyInfo;
64474 mem1.enc = pKeyInfo->enc;
64475 mem1.db = pKeyInfo->db;
64476 /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
64477 VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
64479 /* Compilers may complain that mem1.u.i is potentially uninitialized.
64480 ** We could initialize it, as shown here, to silence those complaints.
64481 ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
64482 ** the unnecessary initialization has a measurable negative performance
64483 ** impact, since this routine is a very high runner. And so, we choose
64484 ** to ignore the compiler warnings and leave this variable uninitialized.
64486 /* mem1.u.i = 0; // not needed, here to silence compiler warning */
64488 idx1 = getVarint32(aKey1, szHdr1);
64489 d1 = szHdr1;
64490 assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
64491 assert( pKeyInfo->aSortOrder!=0 );
64492 assert( pKeyInfo->nField>0 );
64493 assert( idx1<=szHdr1 || CORRUPT_DB );
64495 u32 serial_type1;
64497 /* Read the serial types for the next element in each key. */
64498 idx1 += getVarint32( aKey1+idx1, serial_type1 );
64500 /* Verify that there is enough key space remaining to avoid
64501 ** a buffer overread. The "d1+serial_type1+2" subexpression will
64502 ** always be greater than or equal to the amount of required key space.
64503 ** Use that approximation to avoid the more expensive call to
64504 ** sqlite3VdbeSerialTypeLen() in the common case.
64506 if( d1+serial_type1+2>(u32)nKey1
64507 && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
64509 break;
64512 /* Extract the values to be compared.
64514 d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
64516 /* Do the comparison
64518 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
64519 if( rc!=0 ){
64520 assert( mem1.zMalloc==0 ); /* See comment below */
64521 if( pKeyInfo->aSortOrder[i] ){
64522 rc = -rc; /* Invert the result for DESC sort order. */
64524 return rc;
64526 i++;
64527 }while( idx1<szHdr1 && i<pPKey2->nField );
64529 /* No memory allocation is ever used on mem1. Prove this using
64530 ** the following assert(). If the assert() fails, it indicates a
64531 ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
64533 assert( mem1.zMalloc==0 );
64535 /* rc==0 here means that one of the keys ran out of fields and
64536 ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
64537 ** flag is set, then break the tie by treating key2 as larger.
64538 ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
64539 ** are considered to be equal. Otherwise, the longer key is the
64540 ** larger. As it happens, the pPKey2 will always be the longer
64541 ** if there is a difference.
64543 assert( rc==0 );
64544 if( pPKey2->flags & UNPACKED_INCRKEY ){
64545 rc = -1;
64546 }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
64547 /* Leave rc==0 */
64548 }else if( idx1<szHdr1 ){
64549 rc = 1;
64551 return rc;
64556 ** pCur points at an index entry created using the OP_MakeRecord opcode.
64557 ** Read the rowid (the last field in the record) and store it in *rowid.
64558 ** Return SQLITE_OK if everything works, or an error code otherwise.
64560 ** pCur might be pointing to text obtained from a corrupt database file.
64561 ** So the content cannot be trusted. Do appropriate checks on the content.
64563 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
64564 i64 nCellKey = 0;
64565 int rc;
64566 u32 szHdr; /* Size of the header */
64567 u32 typeRowid; /* Serial type of the rowid */
64568 u32 lenRowid; /* Size of the rowid */
64569 Mem m, v;
64571 UNUSED_PARAMETER(db);
64573 /* Get the size of the index entry. Only indices entries of less
64574 ** than 2GiB are support - anything large must be database corruption.
64575 ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
64576 ** this code can safely assume that nCellKey is 32-bits
64578 assert( sqlite3BtreeCursorIsValid(pCur) );
64579 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
64580 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
64581 assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
64583 /* Read in the complete content of the index entry */
64584 memset(&m, 0, sizeof(m));
64585 rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
64586 if( rc ){
64587 return rc;
64590 /* The index entry must begin with a header size */
64591 (void)getVarint32((u8*)m.z, szHdr);
64592 testcase( szHdr==3 );
64593 testcase( szHdr==m.n );
64594 if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
64595 goto idx_rowid_corruption;
64598 /* The last field of the index should be an integer - the ROWID.
64599 ** Verify that the last entry really is an integer. */
64600 (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
64601 testcase( typeRowid==1 );
64602 testcase( typeRowid==2 );
64603 testcase( typeRowid==3 );
64604 testcase( typeRowid==4 );
64605 testcase( typeRowid==5 );
64606 testcase( typeRowid==6 );
64607 testcase( typeRowid==8 );
64608 testcase( typeRowid==9 );
64609 if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
64610 goto idx_rowid_corruption;
64612 lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
64613 testcase( (u32)m.n==szHdr+lenRowid );
64614 if( unlikely((u32)m.n<szHdr+lenRowid) ){
64615 goto idx_rowid_corruption;
64618 /* Fetch the integer off the end of the index record */
64619 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
64620 *rowid = v.u.i;
64621 sqlite3VdbeMemRelease(&m);
64622 return SQLITE_OK;
64624 /* Jump here if database corruption is detected after m has been
64625 ** allocated. Free the m object and return SQLITE_CORRUPT. */
64626 idx_rowid_corruption:
64627 testcase( m.zMalloc!=0 );
64628 sqlite3VdbeMemRelease(&m);
64629 return SQLITE_CORRUPT_BKPT;
64633 ** Compare the key of the index entry that cursor pC is pointing to against
64634 ** the key string in pUnpacked. Write into *pRes a number
64635 ** that is negative, zero, or positive if pC is less than, equal to,
64636 ** or greater than pUnpacked. Return SQLITE_OK on success.
64638 ** pUnpacked is either created without a rowid or is truncated so that it
64639 ** omits the rowid at the end. The rowid at the end of the index entry
64640 ** is ignored as well. Hence, this routine only compares the prefixes
64641 ** of the keys prior to the final rowid, not the entire key.
64643 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
64644 VdbeCursor *pC, /* The cursor to compare against */
64645 UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
64646 int *res /* Write the comparison result here */
64648 i64 nCellKey = 0;
64649 int rc;
64650 BtCursor *pCur = pC->pCursor;
64651 Mem m;
64653 assert( sqlite3BtreeCursorIsValid(pCur) );
64654 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
64655 assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
64656 /* nCellKey will always be between 0 and 0xffffffff because of the say
64657 ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
64658 if( nCellKey<=0 || nCellKey>0x7fffffff ){
64659 *res = 0;
64660 return SQLITE_CORRUPT_BKPT;
64662 memset(&m, 0, sizeof(m));
64663 rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
64664 if( rc ){
64665 return rc;
64667 assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
64668 *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
64669 sqlite3VdbeMemRelease(&m);
64670 return SQLITE_OK;
64674 ** This routine sets the value to be returned by subsequent calls to
64675 ** sqlite3_changes() on the database handle 'db'.
64677 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
64678 assert( sqlite3_mutex_held(db->mutex) );
64679 db->nChange = nChange;
64680 db->nTotalChange += nChange;
64684 ** Set a flag in the vdbe to update the change counter when it is finalised
64685 ** or reset.
64687 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
64688 v->changeCntOn = 1;
64692 ** Mark every prepared statement associated with a database connection
64693 ** as expired.
64695 ** An expired statement means that recompilation of the statement is
64696 ** recommend. Statements expire when things happen that make their
64697 ** programs obsolete. Removing user-defined functions or collating
64698 ** sequences, or changing an authorization function are the types of
64699 ** things that make prepared statements obsolete.
64701 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
64702 Vdbe *p;
64703 for(p = db->pVdbe; p; p=p->pNext){
64704 p->expired = 1;
64709 ** Return the database associated with the Vdbe.
64711 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
64712 return v->db;
64716 ** Return a pointer to an sqlite3_value structure containing the value bound
64717 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
64718 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
64719 ** constants) to the value before returning it.
64721 ** The returned value must be freed by the caller using sqlite3ValueFree().
64723 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
64724 assert( iVar>0 );
64725 if( v ){
64726 Mem *pMem = &v->aVar[iVar-1];
64727 if( 0==(pMem->flags & MEM_Null) ){
64728 sqlite3_value *pRet = sqlite3ValueNew(v->db);
64729 if( pRet ){
64730 sqlite3VdbeMemCopy((Mem *)pRet, pMem);
64731 sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
64732 sqlite3VdbeMemStoreType((Mem *)pRet);
64734 return pRet;
64737 return 0;
64741 ** Configure SQL variable iVar so that binding a new value to it signals
64742 ** to sqlite3_reoptimize() that re-preparing the statement may result
64743 ** in a better query plan.
64745 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
64746 assert( iVar>0 );
64747 if( iVar>32 ){
64748 v->expmask = 0xffffffff;
64749 }else{
64750 v->expmask |= ((u32)1 << (iVar-1));
64754 #ifndef SQLITE_OMIT_VIRTUALTABLE
64756 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
64757 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
64758 ** in memory obtained from sqlite3DbMalloc).
64760 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
64761 sqlite3 *db = p->db;
64762 sqlite3DbFree(db, p->zErrMsg);
64763 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
64764 sqlite3_free(pVtab->zErrMsg);
64765 pVtab->zErrMsg = 0;
64767 #endif /* SQLITE_OMIT_VIRTUALTABLE */
64769 /************** End of vdbeaux.c *********************************************/
64770 /************** Begin file vdbeapi.c *****************************************/
64772 ** 2004 May 26
64774 ** The author disclaims copyright to this source code. In place of
64775 ** a legal notice, here is a blessing:
64777 ** May you do good and not evil.
64778 ** May you find forgiveness for yourself and forgive others.
64779 ** May you share freely, never taking more than you give.
64781 *************************************************************************
64783 ** This file contains code use to implement APIs that are part of the
64784 ** VDBE.
64787 #ifndef SQLITE_OMIT_DEPRECATED
64789 ** Return TRUE (non-zero) of the statement supplied as an argument needs
64790 ** to be recompiled. A statement needs to be recompiled whenever the
64791 ** execution environment changes in a way that would alter the program
64792 ** that sqlite3_prepare() generates. For example, if new functions or
64793 ** collating sequences are registered or if an authorizer function is
64794 ** added or changed.
64796 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
64797 Vdbe *p = (Vdbe*)pStmt;
64798 return p==0 || p->expired;
64800 #endif
64803 ** Check on a Vdbe to make sure it has not been finalized. Log
64804 ** an error and return true if it has been finalized (or is otherwise
64805 ** invalid). Return false if it is ok.
64807 static int vdbeSafety(Vdbe *p){
64808 if( p->db==0 ){
64809 sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
64810 return 1;
64811 }else{
64812 return 0;
64815 static int vdbeSafetyNotNull(Vdbe *p){
64816 if( p==0 ){
64817 sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
64818 return 1;
64819 }else{
64820 return vdbeSafety(p);
64825 ** The following routine destroys a virtual machine that is created by
64826 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
64827 ** success/failure code that describes the result of executing the virtual
64828 ** machine.
64830 ** This routine sets the error code and string returned by
64831 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
64833 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
64834 int rc;
64835 if( pStmt==0 ){
64836 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
64837 ** pointer is a harmless no-op. */
64838 rc = SQLITE_OK;
64839 }else{
64840 Vdbe *v = (Vdbe*)pStmt;
64841 sqlite3 *db = v->db;
64842 if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
64843 sqlite3_mutex_enter(db->mutex);
64844 rc = sqlite3VdbeFinalize(v);
64845 rc = sqlite3ApiExit(db, rc);
64846 sqlite3LeaveMutexAndCloseZombie(db);
64848 return rc;
64852 ** Terminate the current execution of an SQL statement and reset it
64853 ** back to its starting state so that it can be reused. A success code from
64854 ** the prior execution is returned.
64856 ** This routine sets the error code and string returned by
64857 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
64859 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
64860 int rc;
64861 if( pStmt==0 ){
64862 rc = SQLITE_OK;
64863 }else{
64864 Vdbe *v = (Vdbe*)pStmt;
64865 sqlite3_mutex_enter(v->db->mutex);
64866 rc = sqlite3VdbeReset(v);
64867 sqlite3VdbeRewind(v);
64868 assert( (rc & (v->db->errMask))==rc );
64869 rc = sqlite3ApiExit(v->db, rc);
64870 sqlite3_mutex_leave(v->db->mutex);
64872 return rc;
64876 ** Set all the parameters in the compiled SQL statement to NULL.
64878 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
64879 int i;
64880 int rc = SQLITE_OK;
64881 Vdbe *p = (Vdbe*)pStmt;
64882 #if SQLITE_THREADSAFE
64883 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
64884 #endif
64885 sqlite3_mutex_enter(mutex);
64886 for(i=0; i<p->nVar; i++){
64887 sqlite3VdbeMemRelease(&p->aVar[i]);
64888 p->aVar[i].flags = MEM_Null;
64890 if( p->isPrepareV2 && p->expmask ){
64891 p->expired = 1;
64893 sqlite3_mutex_leave(mutex);
64894 return rc;
64898 /**************************** sqlite3_value_ *******************************
64899 ** The following routines extract information from a Mem or sqlite3_value
64900 ** structure.
64902 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
64903 Mem *p = (Mem*)pVal;
64904 if( p->flags & (MEM_Blob|MEM_Str) ){
64905 sqlite3VdbeMemExpandBlob(p);
64906 p->flags &= ~MEM_Str;
64907 p->flags |= MEM_Blob;
64908 return p->n ? p->z : 0;
64909 }else{
64910 return sqlite3_value_text(pVal);
64913 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
64914 return sqlite3ValueBytes(pVal, SQLITE_UTF8);
64916 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
64917 return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
64919 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
64920 return sqlite3VdbeRealValue((Mem*)pVal);
64922 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
64923 return (int)sqlite3VdbeIntValue((Mem*)pVal);
64925 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
64926 return sqlite3VdbeIntValue((Mem*)pVal);
64928 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
64929 return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
64931 #ifndef SQLITE_OMIT_UTF16
64932 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
64933 return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
64935 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
64936 return sqlite3ValueText(pVal, SQLITE_UTF16BE);
64938 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
64939 return sqlite3ValueText(pVal, SQLITE_UTF16LE);
64941 #endif /* SQLITE_OMIT_UTF16 */
64942 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
64943 return pVal->type;
64946 /**************************** sqlite3_result_ *******************************
64947 ** The following routines are used by user-defined functions to specify
64948 ** the function result.
64950 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
64951 ** result as a string or blob but if the string or blob is too large, it
64952 ** then sets the error code to SQLITE_TOOBIG
64954 static void setResultStrOrError(
64955 sqlite3_context *pCtx, /* Function context */
64956 const char *z, /* String pointer */
64957 int n, /* Bytes in string, or negative */
64958 u8 enc, /* Encoding of z. 0 for BLOBs */
64959 void (*xDel)(void*) /* Destructor function */
64961 if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
64962 sqlite3_result_error_toobig(pCtx);
64965 SQLITE_API void sqlite3_result_blob(
64966 sqlite3_context *pCtx,
64967 const void *z,
64968 int n,
64969 void (*xDel)(void *)
64971 assert( n>=0 );
64972 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64973 setResultStrOrError(pCtx, z, n, 0, xDel);
64975 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
64976 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64977 sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
64979 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
64980 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64981 pCtx->isError = SQLITE_ERROR;
64982 pCtx->fErrorOrAux = 1;
64983 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
64985 #ifndef SQLITE_OMIT_UTF16
64986 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
64987 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64988 pCtx->isError = SQLITE_ERROR;
64989 pCtx->fErrorOrAux = 1;
64990 sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
64992 #endif
64993 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
64994 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64995 sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
64997 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
64998 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
64999 sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
65001 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
65002 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65003 sqlite3VdbeMemSetNull(&pCtx->s);
65005 SQLITE_API void sqlite3_result_text(
65006 sqlite3_context *pCtx,
65007 const char *z,
65008 int n,
65009 void (*xDel)(void *)
65011 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65012 setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
65014 #ifndef SQLITE_OMIT_UTF16
65015 SQLITE_API void sqlite3_result_text16(
65016 sqlite3_context *pCtx,
65017 const void *z,
65018 int n,
65019 void (*xDel)(void *)
65021 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65022 setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
65024 SQLITE_API void sqlite3_result_text16be(
65025 sqlite3_context *pCtx,
65026 const void *z,
65027 int n,
65028 void (*xDel)(void *)
65030 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65031 setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
65033 SQLITE_API void sqlite3_result_text16le(
65034 sqlite3_context *pCtx,
65035 const void *z,
65036 int n,
65037 void (*xDel)(void *)
65039 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65040 setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
65042 #endif /* SQLITE_OMIT_UTF16 */
65043 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
65044 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65045 sqlite3VdbeMemCopy(&pCtx->s, pValue);
65047 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
65048 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65049 sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
65051 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
65052 pCtx->isError = errCode;
65053 pCtx->fErrorOrAux = 1;
65054 if( pCtx->s.flags & MEM_Null ){
65055 sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
65056 SQLITE_UTF8, SQLITE_STATIC);
65060 /* Force an SQLITE_TOOBIG error. */
65061 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
65062 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65063 pCtx->isError = SQLITE_TOOBIG;
65064 pCtx->fErrorOrAux = 1;
65065 sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
65066 SQLITE_UTF8, SQLITE_STATIC);
65069 /* An SQLITE_NOMEM error. */
65070 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
65071 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65072 sqlite3VdbeMemSetNull(&pCtx->s);
65073 pCtx->isError = SQLITE_NOMEM;
65074 pCtx->fErrorOrAux = 1;
65075 pCtx->s.db->mallocFailed = 1;
65079 ** This function is called after a transaction has been committed. It
65080 ** invokes callbacks registered with sqlite3_wal_hook() as required.
65082 static int doWalCallbacks(sqlite3 *db){
65083 int rc = SQLITE_OK;
65084 #ifndef SQLITE_OMIT_WAL
65085 int i;
65086 for(i=0; i<db->nDb; i++){
65087 Btree *pBt = db->aDb[i].pBt;
65088 if( pBt ){
65089 int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
65090 if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
65091 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
65095 #endif
65096 return rc;
65100 ** Execute the statement pStmt, either until a row of data is ready, the
65101 ** statement is completely executed or an error occurs.
65103 ** This routine implements the bulk of the logic behind the sqlite_step()
65104 ** API. The only thing omitted is the automatic recompile if a
65105 ** schema change has occurred. That detail is handled by the
65106 ** outer sqlite3_step() wrapper procedure.
65108 static int sqlite3Step(Vdbe *p){
65109 sqlite3 *db;
65110 int rc;
65112 assert(p);
65113 if( p->magic!=VDBE_MAGIC_RUN ){
65114 /* We used to require that sqlite3_reset() be called before retrying
65115 ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
65116 ** with version 3.7.0, we changed this so that sqlite3_reset() would
65117 ** be called automatically instead of throwing the SQLITE_MISUSE error.
65118 ** This "automatic-reset" change is not technically an incompatibility,
65119 ** since any application that receives an SQLITE_MISUSE is broken by
65120 ** definition.
65122 ** Nevertheless, some published applications that were originally written
65123 ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
65124 ** returns, and those were broken by the automatic-reset change. As a
65125 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
65126 ** legacy behavior of returning SQLITE_MISUSE for cases where the
65127 ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
65128 ** or SQLITE_BUSY error.
65130 #ifdef SQLITE_OMIT_AUTORESET
65131 if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
65132 sqlite3_reset((sqlite3_stmt*)p);
65133 }else{
65134 return SQLITE_MISUSE_BKPT;
65136 #else
65137 sqlite3_reset((sqlite3_stmt*)p);
65138 #endif
65141 /* Check that malloc() has not failed. If it has, return early. */
65142 db = p->db;
65143 if( db->mallocFailed ){
65144 p->rc = SQLITE_NOMEM;
65145 return SQLITE_NOMEM;
65148 if( p->pc<=0 && p->expired ){
65149 p->rc = SQLITE_SCHEMA;
65150 rc = SQLITE_ERROR;
65151 goto end_of_step;
65153 if( p->pc<0 ){
65154 /* If there are no other statements currently running, then
65155 ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
65156 ** from interrupting a statement that has not yet started.
65158 if( db->nVdbeActive==0 ){
65159 db->u1.isInterrupted = 0;
65162 assert( db->nVdbeWrite>0 || db->autoCommit==0
65163 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
65166 #ifndef SQLITE_OMIT_TRACE
65167 if( db->xProfile && !db->init.busy ){
65168 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
65170 #endif
65172 db->nVdbeActive++;
65173 if( p->readOnly==0 ) db->nVdbeWrite++;
65174 if( p->bIsReader ) db->nVdbeRead++;
65175 p->pc = 0;
65177 #ifndef SQLITE_OMIT_EXPLAIN
65178 if( p->explain ){
65179 rc = sqlite3VdbeList(p);
65180 }else
65181 #endif /* SQLITE_OMIT_EXPLAIN */
65183 db->nVdbeExec++;
65184 rc = sqlite3VdbeExec(p);
65185 db->nVdbeExec--;
65188 #ifndef SQLITE_OMIT_TRACE
65189 /* Invoke the profile callback if there is one
65191 if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
65192 sqlite3_int64 iNow;
65193 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
65194 db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
65196 #endif
65198 if( rc==SQLITE_DONE ){
65199 assert( p->rc==SQLITE_OK );
65200 p->rc = doWalCallbacks(db);
65201 if( p->rc!=SQLITE_OK ){
65202 rc = SQLITE_ERROR;
65206 db->errCode = rc;
65207 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
65208 p->rc = SQLITE_NOMEM;
65210 end_of_step:
65211 /* At this point local variable rc holds the value that should be
65212 ** returned if this statement was compiled using the legacy
65213 ** sqlite3_prepare() interface. According to the docs, this can only
65214 ** be one of the values in the first assert() below. Variable p->rc
65215 ** contains the value that would be returned if sqlite3_finalize()
65216 ** were called on statement p.
65218 assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
65219 || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
65221 assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
65222 if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
65223 /* If this statement was prepared using sqlite3_prepare_v2(), and an
65224 ** error has occurred, then return the error code in p->rc to the
65225 ** caller. Set the error code in the database handle to the same value.
65227 rc = sqlite3VdbeTransferError(p);
65229 return (rc&db->errMask);
65233 ** This is the top-level implementation of sqlite3_step(). Call
65234 ** sqlite3Step() to do most of the work. If a schema error occurs,
65235 ** call sqlite3Reprepare() and try again.
65237 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
65238 int rc = SQLITE_OK; /* Result from sqlite3Step() */
65239 int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
65240 Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
65241 int cnt = 0; /* Counter to prevent infinite loop of reprepares */
65242 sqlite3 *db; /* The database connection */
65244 if( vdbeSafetyNotNull(v) ){
65245 return SQLITE_MISUSE_BKPT;
65247 db = v->db;
65248 sqlite3_mutex_enter(db->mutex);
65249 v->doingRerun = 0;
65250 while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
65251 && cnt++ < SQLITE_MAX_SCHEMA_RETRY
65252 && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
65253 sqlite3_reset(pStmt);
65254 v->doingRerun = 1;
65255 assert( v->expired==0 );
65257 if( rc2!=SQLITE_OK ){
65258 /* This case occurs after failing to recompile an sql statement.
65259 ** The error message from the SQL compiler has already been loaded
65260 ** into the database handle. This block copies the error message
65261 ** from the database handle into the statement and sets the statement
65262 ** program counter to 0 to ensure that when the statement is
65263 ** finalized or reset the parser error message is available via
65264 ** sqlite3_errmsg() and sqlite3_errcode().
65266 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
65267 assert( zErr!=0 || db->mallocFailed );
65268 sqlite3DbFree(db, v->zErrMsg);
65269 if( !db->mallocFailed ){
65270 v->zErrMsg = sqlite3DbStrDup(db, zErr);
65271 v->rc = rc2;
65272 } else {
65273 v->zErrMsg = 0;
65274 v->rc = rc = SQLITE_NOMEM;
65277 rc = sqlite3ApiExit(db, rc);
65278 sqlite3_mutex_leave(db->mutex);
65279 return rc;
65284 ** Extract the user data from a sqlite3_context structure and return a
65285 ** pointer to it.
65287 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
65288 assert( p && p->pFunc );
65289 return p->pFunc->pUserData;
65293 ** Extract the user data from a sqlite3_context structure and return a
65294 ** pointer to it.
65296 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
65297 ** returns a copy of the pointer to the database connection (the 1st
65298 ** parameter) of the sqlite3_create_function() and
65299 ** sqlite3_create_function16() routines that originally registered the
65300 ** application defined function.
65302 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
65303 assert( p && p->pFunc );
65304 return p->s.db;
65308 ** Return the current time for a statement
65310 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
65311 Vdbe *v = p->pVdbe;
65312 int rc;
65313 if( v->iCurrentTime==0 ){
65314 rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
65315 if( rc ) v->iCurrentTime = 0;
65317 return v->iCurrentTime;
65321 ** The following is the implementation of an SQL function that always
65322 ** fails with an error message stating that the function is used in the
65323 ** wrong context. The sqlite3_overload_function() API might construct
65324 ** SQL function that use this routine so that the functions will exist
65325 ** for name resolution but are actually overloaded by the xFindFunction
65326 ** method of virtual tables.
65328 SQLITE_PRIVATE void sqlite3InvalidFunction(
65329 sqlite3_context *context, /* The function calling context */
65330 int NotUsed, /* Number of arguments to the function */
65331 sqlite3_value **NotUsed2 /* Value of each argument */
65333 const char *zName = context->pFunc->zName;
65334 char *zErr;
65335 UNUSED_PARAMETER2(NotUsed, NotUsed2);
65336 zErr = sqlite3_mprintf(
65337 "unable to use function %s in the requested context", zName);
65338 sqlite3_result_error(context, zErr, -1);
65339 sqlite3_free(zErr);
65343 ** Allocate or return the aggregate context for a user function. A new
65344 ** context is allocated on the first call. Subsequent calls return the
65345 ** same context that was returned on prior calls.
65347 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
65348 Mem *pMem;
65349 assert( p && p->pFunc && p->pFunc->xStep );
65350 assert( sqlite3_mutex_held(p->s.db->mutex) );
65351 pMem = p->pMem;
65352 testcase( nByte<0 );
65353 if( (pMem->flags & MEM_Agg)==0 ){
65354 if( nByte<=0 ){
65355 sqlite3VdbeMemReleaseExternal(pMem);
65356 pMem->flags = MEM_Null;
65357 pMem->z = 0;
65358 }else{
65359 sqlite3VdbeMemGrow(pMem, nByte, 0);
65360 pMem->flags = MEM_Agg;
65361 pMem->u.pDef = p->pFunc;
65362 if( pMem->z ){
65363 memset(pMem->z, 0, nByte);
65367 return (void*)pMem->z;
65371 ** Return the auxilary data pointer, if any, for the iArg'th argument to
65372 ** the user-function defined by pCtx.
65374 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
65375 AuxData *pAuxData;
65377 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65378 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
65379 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
65382 return (pAuxData ? pAuxData->pAux : 0);
65386 ** Set the auxilary data pointer and delete function, for the iArg'th
65387 ** argument to the user-function defined by pCtx. Any previous value is
65388 ** deleted by calling the delete function specified when it was set.
65390 SQLITE_API void sqlite3_set_auxdata(
65391 sqlite3_context *pCtx,
65392 int iArg,
65393 void *pAux,
65394 void (*xDelete)(void*)
65396 AuxData *pAuxData;
65397 Vdbe *pVdbe = pCtx->pVdbe;
65399 assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
65400 if( iArg<0 ) goto failed;
65402 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
65403 if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
65405 if( pAuxData==0 ){
65406 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
65407 if( !pAuxData ) goto failed;
65408 pAuxData->iOp = pCtx->iOp;
65409 pAuxData->iArg = iArg;
65410 pAuxData->pNext = pVdbe->pAuxData;
65411 pVdbe->pAuxData = pAuxData;
65412 if( pCtx->fErrorOrAux==0 ){
65413 pCtx->isError = 0;
65414 pCtx->fErrorOrAux = 1;
65416 }else if( pAuxData->xDelete ){
65417 pAuxData->xDelete(pAuxData->pAux);
65420 pAuxData->pAux = pAux;
65421 pAuxData->xDelete = xDelete;
65422 return;
65424 failed:
65425 if( xDelete ){
65426 xDelete(pAux);
65430 #ifndef SQLITE_OMIT_DEPRECATED
65432 ** Return the number of times the Step function of a aggregate has been
65433 ** called.
65435 ** This function is deprecated. Do not use it for new code. It is
65436 ** provide only to avoid breaking legacy code. New aggregate function
65437 ** implementations should keep their own counts within their aggregate
65438 ** context.
65440 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
65441 assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
65442 return p->pMem->n;
65444 #endif
65447 ** Return the number of columns in the result set for the statement pStmt.
65449 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
65450 Vdbe *pVm = (Vdbe *)pStmt;
65451 return pVm ? pVm->nResColumn : 0;
65455 ** Return the number of values available from the current row of the
65456 ** currently executing statement pStmt.
65458 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
65459 Vdbe *pVm = (Vdbe *)pStmt;
65460 if( pVm==0 || pVm->pResultSet==0 ) return 0;
65461 return pVm->nResColumn;
65466 ** Check to see if column iCol of the given statement is valid. If
65467 ** it is, return a pointer to the Mem for the value of that column.
65468 ** If iCol is not valid, return a pointer to a Mem which has a value
65469 ** of NULL.
65471 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
65472 Vdbe *pVm;
65473 Mem *pOut;
65475 pVm = (Vdbe *)pStmt;
65476 if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
65477 sqlite3_mutex_enter(pVm->db->mutex);
65478 pOut = &pVm->pResultSet[i];
65479 }else{
65480 /* If the value passed as the second argument is out of range, return
65481 ** a pointer to the following static Mem object which contains the
65482 ** value SQL NULL. Even though the Mem structure contains an element
65483 ** of type i64, on certain architectures (x86) with certain compiler
65484 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
65485 ** instead of an 8-byte one. This all works fine, except that when
65486 ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
65487 ** that a Mem structure is located on an 8-byte boundary. To prevent
65488 ** these assert()s from failing, when building with SQLITE_DEBUG defined
65489 ** using gcc, we force nullMem to be 8-byte aligned using the magical
65490 ** __attribute__((aligned(8))) macro. */
65491 static const Mem nullMem
65492 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
65493 __attribute__((aligned(8)))
65494 #endif
65495 = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
65496 #ifdef SQLITE_DEBUG
65497 0, 0, /* pScopyFrom, pFiller */
65498 #endif
65499 0, 0 };
65501 if( pVm && ALWAYS(pVm->db) ){
65502 sqlite3_mutex_enter(pVm->db->mutex);
65503 sqlite3Error(pVm->db, SQLITE_RANGE, 0);
65505 pOut = (Mem*)&nullMem;
65507 return pOut;
65511 ** This function is called after invoking an sqlite3_value_XXX function on a
65512 ** column value (i.e. a value returned by evaluating an SQL expression in the
65513 ** select list of a SELECT statement) that may cause a malloc() failure. If
65514 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
65515 ** code of statement pStmt set to SQLITE_NOMEM.
65517 ** Specifically, this is called from within:
65519 ** sqlite3_column_int()
65520 ** sqlite3_column_int64()
65521 ** sqlite3_column_text()
65522 ** sqlite3_column_text16()
65523 ** sqlite3_column_real()
65524 ** sqlite3_column_bytes()
65525 ** sqlite3_column_bytes16()
65526 ** sqiite3_column_blob()
65528 static void columnMallocFailure(sqlite3_stmt *pStmt)
65530 /* If malloc() failed during an encoding conversion within an
65531 ** sqlite3_column_XXX API, then set the return code of the statement to
65532 ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
65533 ** and _finalize() will return NOMEM.
65535 Vdbe *p = (Vdbe *)pStmt;
65536 if( p ){
65537 p->rc = sqlite3ApiExit(p->db, p->rc);
65538 sqlite3_mutex_leave(p->db->mutex);
65542 /**************************** sqlite3_column_ *******************************
65543 ** The following routines are used to access elements of the current row
65544 ** in the result set.
65546 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
65547 const void *val;
65548 val = sqlite3_value_blob( columnMem(pStmt,i) );
65549 /* Even though there is no encoding conversion, value_blob() might
65550 ** need to call malloc() to expand the result of a zeroblob()
65551 ** expression.
65553 columnMallocFailure(pStmt);
65554 return val;
65556 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
65557 int val = sqlite3_value_bytes( columnMem(pStmt,i) );
65558 columnMallocFailure(pStmt);
65559 return val;
65561 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
65562 int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
65563 columnMallocFailure(pStmt);
65564 return val;
65566 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
65567 double val = sqlite3_value_double( columnMem(pStmt,i) );
65568 columnMallocFailure(pStmt);
65569 return val;
65571 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
65572 int val = sqlite3_value_int( columnMem(pStmt,i) );
65573 columnMallocFailure(pStmt);
65574 return val;
65576 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
65577 sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
65578 columnMallocFailure(pStmt);
65579 return val;
65581 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
65582 const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
65583 columnMallocFailure(pStmt);
65584 return val;
65586 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
65587 Mem *pOut = columnMem(pStmt, i);
65588 if( pOut->flags&MEM_Static ){
65589 pOut->flags &= ~MEM_Static;
65590 pOut->flags |= MEM_Ephem;
65592 columnMallocFailure(pStmt);
65593 return (sqlite3_value *)pOut;
65595 #ifndef SQLITE_OMIT_UTF16
65596 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
65597 const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
65598 columnMallocFailure(pStmt);
65599 return val;
65601 #endif /* SQLITE_OMIT_UTF16 */
65602 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
65603 int iType = sqlite3_value_type( columnMem(pStmt,i) );
65604 columnMallocFailure(pStmt);
65605 return iType;
65609 ** Convert the N-th element of pStmt->pColName[] into a string using
65610 ** xFunc() then return that string. If N is out of range, return 0.
65612 ** There are up to 5 names for each column. useType determines which
65613 ** name is returned. Here are the names:
65615 ** 0 The column name as it should be displayed for output
65616 ** 1 The datatype name for the column
65617 ** 2 The name of the database that the column derives from
65618 ** 3 The name of the table that the column derives from
65619 ** 4 The name of the table column that the result column derives from
65621 ** If the result is not a simple column reference (if it is an expression
65622 ** or a constant) then useTypes 2, 3, and 4 return NULL.
65624 static const void *columnName(
65625 sqlite3_stmt *pStmt,
65626 int N,
65627 const void *(*xFunc)(Mem*),
65628 int useType
65630 const void *ret = 0;
65631 Vdbe *p = (Vdbe *)pStmt;
65632 int n;
65633 sqlite3 *db = p->db;
65635 assert( db!=0 );
65636 n = sqlite3_column_count(pStmt);
65637 if( N<n && N>=0 ){
65638 N += useType*n;
65639 sqlite3_mutex_enter(db->mutex);
65640 assert( db->mallocFailed==0 );
65641 ret = xFunc(&p->aColName[N]);
65642 /* A malloc may have failed inside of the xFunc() call. If this
65643 ** is the case, clear the mallocFailed flag and return NULL.
65645 if( db->mallocFailed ){
65646 db->mallocFailed = 0;
65647 ret = 0;
65649 sqlite3_mutex_leave(db->mutex);
65651 return ret;
65655 ** Return the name of the Nth column of the result set returned by SQL
65656 ** statement pStmt.
65658 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
65659 return columnName(
65660 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
65662 #ifndef SQLITE_OMIT_UTF16
65663 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
65664 return columnName(
65665 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
65667 #endif
65670 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
65671 ** not define OMIT_DECLTYPE.
65673 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
65674 # error "Must not define both SQLITE_OMIT_DECLTYPE \
65675 and SQLITE_ENABLE_COLUMN_METADATA"
65676 #endif
65678 #ifndef SQLITE_OMIT_DECLTYPE
65680 ** Return the column declaration type (if applicable) of the 'i'th column
65681 ** of the result set of SQL statement pStmt.
65683 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
65684 return columnName(
65685 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
65687 #ifndef SQLITE_OMIT_UTF16
65688 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
65689 return columnName(
65690 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
65692 #endif /* SQLITE_OMIT_UTF16 */
65693 #endif /* SQLITE_OMIT_DECLTYPE */
65695 #ifdef SQLITE_ENABLE_COLUMN_METADATA
65697 ** Return the name of the database from which a result column derives.
65698 ** NULL is returned if the result column is an expression or constant or
65699 ** anything else which is not an unabiguous reference to a database column.
65701 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
65702 return columnName(
65703 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
65705 #ifndef SQLITE_OMIT_UTF16
65706 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
65707 return columnName(
65708 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
65710 #endif /* SQLITE_OMIT_UTF16 */
65713 ** Return the name of the table from which a result column derives.
65714 ** NULL is returned if the result column is an expression or constant or
65715 ** anything else which is not an unabiguous reference to a database column.
65717 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
65718 return columnName(
65719 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
65721 #ifndef SQLITE_OMIT_UTF16
65722 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
65723 return columnName(
65724 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
65726 #endif /* SQLITE_OMIT_UTF16 */
65729 ** Return the name of the table column from which a result column derives.
65730 ** NULL is returned if the result column is an expression or constant or
65731 ** anything else which is not an unabiguous reference to a database column.
65733 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
65734 return columnName(
65735 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
65737 #ifndef SQLITE_OMIT_UTF16
65738 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
65739 return columnName(
65740 pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
65742 #endif /* SQLITE_OMIT_UTF16 */
65743 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
65746 /******************************* sqlite3_bind_ ***************************
65748 ** Routines used to attach values to wildcards in a compiled SQL statement.
65751 ** Unbind the value bound to variable i in virtual machine p. This is the
65752 ** the same as binding a NULL value to the column. If the "i" parameter is
65753 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
65755 ** A successful evaluation of this routine acquires the mutex on p.
65756 ** the mutex is released if any kind of error occurs.
65758 ** The error code stored in database p->db is overwritten with the return
65759 ** value in any case.
65761 static int vdbeUnbind(Vdbe *p, int i){
65762 Mem *pVar;
65763 if( vdbeSafetyNotNull(p) ){
65764 return SQLITE_MISUSE_BKPT;
65766 sqlite3_mutex_enter(p->db->mutex);
65767 if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
65768 sqlite3Error(p->db, SQLITE_MISUSE, 0);
65769 sqlite3_mutex_leave(p->db->mutex);
65770 sqlite3_log(SQLITE_MISUSE,
65771 "bind on a busy prepared statement: [%s]", p->zSql);
65772 return SQLITE_MISUSE_BKPT;
65774 if( i<1 || i>p->nVar ){
65775 sqlite3Error(p->db, SQLITE_RANGE, 0);
65776 sqlite3_mutex_leave(p->db->mutex);
65777 return SQLITE_RANGE;
65779 i--;
65780 pVar = &p->aVar[i];
65781 sqlite3VdbeMemRelease(pVar);
65782 pVar->flags = MEM_Null;
65783 sqlite3Error(p->db, SQLITE_OK, 0);
65785 /* If the bit corresponding to this variable in Vdbe.expmask is set, then
65786 ** binding a new value to this variable invalidates the current query plan.
65788 ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
65789 ** parameter in the WHERE clause might influence the choice of query plan
65790 ** for a statement, then the statement will be automatically recompiled,
65791 ** as if there had been a schema change, on the first sqlite3_step() call
65792 ** following any change to the bindings of that parameter.
65794 if( p->isPrepareV2 &&
65795 ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
65797 p->expired = 1;
65799 return SQLITE_OK;
65803 ** Bind a text or BLOB value.
65805 static int bindText(
65806 sqlite3_stmt *pStmt, /* The statement to bind against */
65807 int i, /* Index of the parameter to bind */
65808 const void *zData, /* Pointer to the data to be bound */
65809 int nData, /* Number of bytes of data to be bound */
65810 void (*xDel)(void*), /* Destructor for the data */
65811 u8 encoding /* Encoding for the data */
65813 Vdbe *p = (Vdbe *)pStmt;
65814 Mem *pVar;
65815 int rc;
65817 rc = vdbeUnbind(p, i);
65818 if( rc==SQLITE_OK ){
65819 if( zData!=0 ){
65820 pVar = &p->aVar[i-1];
65821 rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
65822 if( rc==SQLITE_OK && encoding!=0 ){
65823 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
65825 sqlite3Error(p->db, rc, 0);
65826 rc = sqlite3ApiExit(p->db, rc);
65828 sqlite3_mutex_leave(p->db->mutex);
65829 }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
65830 xDel((void*)zData);
65832 return rc;
65837 ** Bind a blob value to an SQL statement variable.
65839 SQLITE_API int sqlite3_bind_blob(
65840 sqlite3_stmt *pStmt,
65841 int i,
65842 const void *zData,
65843 int nData,
65844 void (*xDel)(void*)
65846 return bindText(pStmt, i, zData, nData, xDel, 0);
65848 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
65849 int rc;
65850 Vdbe *p = (Vdbe *)pStmt;
65851 rc = vdbeUnbind(p, i);
65852 if( rc==SQLITE_OK ){
65853 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
65854 sqlite3_mutex_leave(p->db->mutex);
65856 return rc;
65858 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
65859 return sqlite3_bind_int64(p, i, (i64)iValue);
65861 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
65862 int rc;
65863 Vdbe *p = (Vdbe *)pStmt;
65864 rc = vdbeUnbind(p, i);
65865 if( rc==SQLITE_OK ){
65866 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
65867 sqlite3_mutex_leave(p->db->mutex);
65869 return rc;
65871 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
65872 int rc;
65873 Vdbe *p = (Vdbe*)pStmt;
65874 rc = vdbeUnbind(p, i);
65875 if( rc==SQLITE_OK ){
65876 sqlite3_mutex_leave(p->db->mutex);
65878 return rc;
65880 SQLITE_API int sqlite3_bind_text(
65881 sqlite3_stmt *pStmt,
65882 int i,
65883 const char *zData,
65884 int nData,
65885 void (*xDel)(void*)
65887 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
65889 #ifndef SQLITE_OMIT_UTF16
65890 SQLITE_API int sqlite3_bind_text16(
65891 sqlite3_stmt *pStmt,
65892 int i,
65893 const void *zData,
65894 int nData,
65895 void (*xDel)(void*)
65897 return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
65899 #endif /* SQLITE_OMIT_UTF16 */
65900 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
65901 int rc;
65902 switch( pValue->type ){
65903 case SQLITE_INTEGER: {
65904 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
65905 break;
65907 case SQLITE_FLOAT: {
65908 rc = sqlite3_bind_double(pStmt, i, pValue->r);
65909 break;
65911 case SQLITE_BLOB: {
65912 if( pValue->flags & MEM_Zero ){
65913 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
65914 }else{
65915 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
65917 break;
65919 case SQLITE_TEXT: {
65920 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
65921 pValue->enc);
65922 break;
65924 default: {
65925 rc = sqlite3_bind_null(pStmt, i);
65926 break;
65929 return rc;
65931 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
65932 int rc;
65933 Vdbe *p = (Vdbe *)pStmt;
65934 rc = vdbeUnbind(p, i);
65935 if( rc==SQLITE_OK ){
65936 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
65937 sqlite3_mutex_leave(p->db->mutex);
65939 return rc;
65943 ** Return the number of wildcards that can be potentially bound to.
65944 ** This routine is added to support DBD::SQLite.
65946 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
65947 Vdbe *p = (Vdbe*)pStmt;
65948 return p ? p->nVar : 0;
65952 ** Return the name of a wildcard parameter. Return NULL if the index
65953 ** is out of range or if the wildcard is unnamed.
65955 ** The result is always UTF-8.
65957 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
65958 Vdbe *p = (Vdbe*)pStmt;
65959 if( p==0 || i<1 || i>p->nzVar ){
65960 return 0;
65962 return p->azVar[i-1];
65966 ** Given a wildcard parameter name, return the index of the variable
65967 ** with that name. If there is no variable with the given name,
65968 ** return 0.
65970 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
65971 int i;
65972 if( p==0 ){
65973 return 0;
65975 if( zName ){
65976 for(i=0; i<p->nzVar; i++){
65977 const char *z = p->azVar[i];
65978 if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
65979 return i+1;
65983 return 0;
65985 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
65986 return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
65990 ** Transfer all bindings from the first statement over to the second.
65992 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
65993 Vdbe *pFrom = (Vdbe*)pFromStmt;
65994 Vdbe *pTo = (Vdbe*)pToStmt;
65995 int i;
65996 assert( pTo->db==pFrom->db );
65997 assert( pTo->nVar==pFrom->nVar );
65998 sqlite3_mutex_enter(pTo->db->mutex);
65999 for(i=0; i<pFrom->nVar; i++){
66000 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
66002 sqlite3_mutex_leave(pTo->db->mutex);
66003 return SQLITE_OK;
66006 #ifndef SQLITE_OMIT_DEPRECATED
66008 ** Deprecated external interface. Internal/core SQLite code
66009 ** should call sqlite3TransferBindings.
66011 ** Is is misuse to call this routine with statements from different
66012 ** database connections. But as this is a deprecated interface, we
66013 ** will not bother to check for that condition.
66015 ** If the two statements contain a different number of bindings, then
66016 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
66017 ** SQLITE_OK is returned.
66019 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
66020 Vdbe *pFrom = (Vdbe*)pFromStmt;
66021 Vdbe *pTo = (Vdbe*)pToStmt;
66022 if( pFrom->nVar!=pTo->nVar ){
66023 return SQLITE_ERROR;
66025 if( pTo->isPrepareV2 && pTo->expmask ){
66026 pTo->expired = 1;
66028 if( pFrom->isPrepareV2 && pFrom->expmask ){
66029 pFrom->expired = 1;
66031 return sqlite3TransferBindings(pFromStmt, pToStmt);
66033 #endif
66036 ** Return the sqlite3* database handle to which the prepared statement given
66037 ** in the argument belongs. This is the same database handle that was
66038 ** the first argument to the sqlite3_prepare() that was used to create
66039 ** the statement in the first place.
66041 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
66042 return pStmt ? ((Vdbe*)pStmt)->db : 0;
66046 ** Return true if the prepared statement is guaranteed to not modify the
66047 ** database.
66049 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
66050 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
66054 ** Return true if the prepared statement is in need of being reset.
66056 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
66057 Vdbe *v = (Vdbe*)pStmt;
66058 return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
66062 ** Return a pointer to the next prepared statement after pStmt associated
66063 ** with database connection pDb. If pStmt is NULL, return the first
66064 ** prepared statement for the database connection. Return NULL if there
66065 ** are no more.
66067 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
66068 sqlite3_stmt *pNext;
66069 sqlite3_mutex_enter(pDb->mutex);
66070 if( pStmt==0 ){
66071 pNext = (sqlite3_stmt*)pDb->pVdbe;
66072 }else{
66073 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
66075 sqlite3_mutex_leave(pDb->mutex);
66076 return pNext;
66080 ** Return the value of a status counter for a prepared statement
66082 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
66083 Vdbe *pVdbe = (Vdbe*)pStmt;
66084 u32 v = pVdbe->aCounter[op];
66085 if( resetFlag ) pVdbe->aCounter[op] = 0;
66086 return (int)v;
66089 /************** End of vdbeapi.c *********************************************/
66090 /************** Begin file vdbetrace.c ***************************************/
66092 ** 2009 November 25
66094 ** The author disclaims copyright to this source code. In place of
66095 ** a legal notice, here is a blessing:
66097 ** May you do good and not evil.
66098 ** May you find forgiveness for yourself and forgive others.
66099 ** May you share freely, never taking more than you give.
66101 *************************************************************************
66103 ** This file contains code used to insert the values of host parameters
66104 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
66106 ** The Vdbe parse-tree explainer is also found here.
66109 #ifndef SQLITE_OMIT_TRACE
66112 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
66113 ** bytes in this text up to but excluding the first character in
66114 ** a host parameter. If the text contains no host parameters, return
66115 ** the total number of bytes in the text.
66117 static int findNextHostParameter(const char *zSql, int *pnToken){
66118 int tokenType;
66119 int nTotal = 0;
66120 int n;
66122 *pnToken = 0;
66123 while( zSql[0] ){
66124 n = sqlite3GetToken((u8*)zSql, &tokenType);
66125 assert( n>0 && tokenType!=TK_ILLEGAL );
66126 if( tokenType==TK_VARIABLE ){
66127 *pnToken = n;
66128 break;
66130 nTotal += n;
66131 zSql += n;
66133 return nTotal;
66137 ** This function returns a pointer to a nul-terminated string in memory
66138 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
66139 ** string contains a copy of zRawSql but with host parameters expanded to
66140 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
66141 ** then the returned string holds a copy of zRawSql with "-- " prepended
66142 ** to each line of text.
66144 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
66145 ** then long strings and blobs are truncated to that many bytes. This
66146 ** can be used to prevent unreasonably large trace strings when dealing
66147 ** with large (multi-megabyte) strings and blobs.
66149 ** The calling function is responsible for making sure the memory returned
66150 ** is eventually freed.
66152 ** ALGORITHM: Scan the input string looking for host parameters in any of
66153 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
66154 ** string literals, quoted identifier names, and comments. For text forms,
66155 ** the host parameter index is found by scanning the perpared
66156 ** statement for the corresponding OP_Variable opcode. Once the host
66157 ** parameter index is known, locate the value in p->aVar[]. Then render
66158 ** the value as a literal in place of the host parameter name.
66160 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
66161 Vdbe *p, /* The prepared statement being evaluated */
66162 const char *zRawSql /* Raw text of the SQL statement */
66164 sqlite3 *db; /* The database connection */
66165 int idx = 0; /* Index of a host parameter */
66166 int nextIndex = 1; /* Index of next ? host parameter */
66167 int n; /* Length of a token prefix */
66168 int nToken; /* Length of the parameter token */
66169 int i; /* Loop counter */
66170 Mem *pVar; /* Value of a host parameter */
66171 StrAccum out; /* Accumulate the output here */
66172 char zBase[100]; /* Initial working space */
66174 db = p->db;
66175 sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
66176 db->aLimit[SQLITE_LIMIT_LENGTH]);
66177 out.db = db;
66178 if( db->nVdbeExec>1 ){
66179 while( *zRawSql ){
66180 const char *zStart = zRawSql;
66181 while( *(zRawSql++)!='\n' && *zRawSql );
66182 sqlite3StrAccumAppend(&out, "-- ", 3);
66183 assert( (zRawSql - zStart) > 0 );
66184 sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
66186 }else{
66187 while( zRawSql[0] ){
66188 n = findNextHostParameter(zRawSql, &nToken);
66189 assert( n>0 );
66190 sqlite3StrAccumAppend(&out, zRawSql, n);
66191 zRawSql += n;
66192 assert( zRawSql[0] || nToken==0 );
66193 if( nToken==0 ) break;
66194 if( zRawSql[0]=='?' ){
66195 if( nToken>1 ){
66196 assert( sqlite3Isdigit(zRawSql[1]) );
66197 sqlite3GetInt32(&zRawSql[1], &idx);
66198 }else{
66199 idx = nextIndex;
66201 }else{
66202 assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
66203 testcase( zRawSql[0]==':' );
66204 testcase( zRawSql[0]=='$' );
66205 testcase( zRawSql[0]=='@' );
66206 idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
66207 assert( idx>0 );
66209 zRawSql += nToken;
66210 nextIndex = idx + 1;
66211 assert( idx>0 && idx<=p->nVar );
66212 pVar = &p->aVar[idx-1];
66213 if( pVar->flags & MEM_Null ){
66214 sqlite3StrAccumAppend(&out, "NULL", 4);
66215 }else if( pVar->flags & MEM_Int ){
66216 sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
66217 }else if( pVar->flags & MEM_Real ){
66218 sqlite3XPrintf(&out, 0, "%!.15g", pVar->r);
66219 }else if( pVar->flags & MEM_Str ){
66220 int nOut; /* Number of bytes of the string text to include in output */
66221 #ifndef SQLITE_OMIT_UTF16
66222 u8 enc = ENC(db);
66223 Mem utf8;
66224 if( enc!=SQLITE_UTF8 ){
66225 memset(&utf8, 0, sizeof(utf8));
66226 utf8.db = db;
66227 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
66228 sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
66229 pVar = &utf8;
66231 #endif
66232 nOut = pVar->n;
66233 #ifdef SQLITE_TRACE_SIZE_LIMIT
66234 if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
66235 nOut = SQLITE_TRACE_SIZE_LIMIT;
66236 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
66238 #endif
66239 sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
66240 #ifdef SQLITE_TRACE_SIZE_LIMIT
66241 if( nOut<pVar->n ){
66242 sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
66244 #endif
66245 #ifndef SQLITE_OMIT_UTF16
66246 if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
66247 #endif
66248 }else if( pVar->flags & MEM_Zero ){
66249 sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
66250 }else{
66251 int nOut; /* Number of bytes of the blob to include in output */
66252 assert( pVar->flags & MEM_Blob );
66253 sqlite3StrAccumAppend(&out, "x'", 2);
66254 nOut = pVar->n;
66255 #ifdef SQLITE_TRACE_SIZE_LIMIT
66256 if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
66257 #endif
66258 for(i=0; i<nOut; i++){
66259 sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
66261 sqlite3StrAccumAppend(&out, "'", 1);
66262 #ifdef SQLITE_TRACE_SIZE_LIMIT
66263 if( nOut<pVar->n ){
66264 sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
66266 #endif
66270 return sqlite3StrAccumFinish(&out);
66273 #endif /* #ifndef SQLITE_OMIT_TRACE */
66275 /*****************************************************************************
66276 ** The following code implements the data-structure explaining logic
66277 ** for the Vdbe.
66280 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
66283 ** Allocate a new Explain object
66285 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
66286 if( pVdbe ){
66287 Explain *p;
66288 sqlite3BeginBenignMalloc();
66289 p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
66290 if( p ){
66291 p->pVdbe = pVdbe;
66292 sqlite3_free(pVdbe->pExplain);
66293 pVdbe->pExplain = p;
66294 sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
66295 SQLITE_MAX_LENGTH);
66296 p->str.useMalloc = 2;
66297 }else{
66298 sqlite3EndBenignMalloc();
66304 ** Return true if the Explain ends with a new-line.
66306 static int endsWithNL(Explain *p){
66307 return p && p->str.zText && p->str.nChar
66308 && p->str.zText[p->str.nChar-1]=='\n';
66312 ** Append text to the indentation
66314 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
66315 Explain *p;
66316 if( pVdbe && (p = pVdbe->pExplain)!=0 ){
66317 va_list ap;
66318 if( p->nIndent && endsWithNL(p) ){
66319 int n = p->nIndent;
66320 if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
66321 sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
66323 va_start(ap, zFormat);
66324 sqlite3VXPrintf(&p->str, SQLITE_PRINTF_INTERNAL, zFormat, ap);
66325 va_end(ap);
66330 ** Append a '\n' if there is not already one.
66332 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
66333 Explain *p;
66334 if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
66335 sqlite3StrAccumAppend(&p->str, "\n", 1);
66340 ** Push a new indentation level. Subsequent lines will be indented
66341 ** so that they begin at the current cursor position.
66343 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
66344 Explain *p;
66345 if( pVdbe && (p = pVdbe->pExplain)!=0 ){
66346 if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
66347 const char *z = p->str.zText;
66348 int i = p->str.nChar-1;
66349 int x;
66350 while( i>=0 && z[i]!='\n' ){ i--; }
66351 x = (p->str.nChar - 1) - i;
66352 if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
66353 x = p->aIndent[p->nIndent-1];
66355 p->aIndent[p->nIndent] = x;
66357 p->nIndent++;
66362 ** Pop the indentation stack by one level.
66364 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
66365 if( p && p->pExplain ) p->pExplain->nIndent--;
66369 ** Free the indentation structure
66371 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
66372 if( pVdbe && pVdbe->pExplain ){
66373 sqlite3_free(pVdbe->zExplain);
66374 sqlite3ExplainNL(pVdbe);
66375 pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
66376 sqlite3_free(pVdbe->pExplain);
66377 pVdbe->pExplain = 0;
66378 sqlite3EndBenignMalloc();
66383 ** Return the explanation of a virtual machine.
66385 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
66386 return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
66388 #endif /* defined(SQLITE_DEBUG) */
66390 /************** End of vdbetrace.c *******************************************/
66391 /************** Begin file vdbe.c ********************************************/
66393 ** 2001 September 15
66395 ** The author disclaims copyright to this source code. In place of
66396 ** a legal notice, here is a blessing:
66398 ** May you do good and not evil.
66399 ** May you find forgiveness for yourself and forgive others.
66400 ** May you share freely, never taking more than you give.
66402 *************************************************************************
66403 ** The code in this file implements execution method of the
66404 ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
66405 ** handles housekeeping details such as creating and deleting
66406 ** VDBE instances. This file is solely interested in executing
66407 ** the VDBE program.
66409 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
66410 ** to a VDBE.
66412 ** The SQL parser generates a program which is then executed by
66413 ** the VDBE to do the work of the SQL statement. VDBE programs are
66414 ** similar in form to assembly language. The program consists of
66415 ** a linear sequence of operations. Each operation has an opcode
66416 ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
66417 ** is a null-terminated string. Operand P5 is an unsigned character.
66418 ** Few opcodes use all 5 operands.
66420 ** Computation results are stored on a set of registers numbered beginning
66421 ** with 1 and going up to Vdbe.nMem. Each register can store
66422 ** either an integer, a null-terminated string, a floating point
66423 ** number, or the SQL "NULL" value. An implicit conversion from one
66424 ** type to the other occurs as necessary.
66426 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
66427 ** function which does the work of interpreting a VDBE program.
66428 ** But other routines are also provided to help in building up
66429 ** a program instruction by instruction.
66431 ** Various scripts scan this source file in order to generate HTML
66432 ** documentation, headers files, or other derived files. The formatting
66433 ** of the code in this file is, therefore, important. See other comments
66434 ** in this file for details. If in doubt, do not deviate from existing
66435 ** commenting and indentation practices when changing or adding code.
66439 ** Invoke this macro on memory cells just prior to changing the
66440 ** value of the cell. This macro verifies that shallow copies are
66441 ** not misused.
66443 #ifdef SQLITE_DEBUG
66444 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
66445 #else
66446 # define memAboutToChange(P,M)
66447 #endif
66450 ** The following global variable is incremented every time a cursor
66451 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
66452 ** procedures use this information to make sure that indices are
66453 ** working correctly. This variable has no function other than to
66454 ** help verify the correct operation of the library.
66456 #ifdef SQLITE_TEST
66457 SQLITE_API int sqlite3_search_count = 0;
66458 #endif
66461 ** When this global variable is positive, it gets decremented once before
66462 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
66463 ** field of the sqlite3 structure is set in order to simulate an interrupt.
66465 ** This facility is used for testing purposes only. It does not function
66466 ** in an ordinary build.
66468 #ifdef SQLITE_TEST
66469 SQLITE_API int sqlite3_interrupt_count = 0;
66470 #endif
66473 ** The next global variable is incremented each type the OP_Sort opcode
66474 ** is executed. The test procedures use this information to make sure that
66475 ** sorting is occurring or not occurring at appropriate times. This variable
66476 ** has no function other than to help verify the correct operation of the
66477 ** library.
66479 #ifdef SQLITE_TEST
66480 SQLITE_API int sqlite3_sort_count = 0;
66481 #endif
66484 ** The next global variable records the size of the largest MEM_Blob
66485 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
66486 ** use this information to make sure that the zero-blob functionality
66487 ** is working correctly. This variable has no function other than to
66488 ** help verify the correct operation of the library.
66490 #ifdef SQLITE_TEST
66491 SQLITE_API int sqlite3_max_blobsize = 0;
66492 static void updateMaxBlobsize(Mem *p){
66493 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
66494 sqlite3_max_blobsize = p->n;
66497 #endif
66500 ** The next global variable is incremented each type the OP_Found opcode
66501 ** is executed. This is used to test whether or not the foreign key
66502 ** operation implemented using OP_FkIsZero is working. This variable
66503 ** has no function other than to help verify the correct operation of the
66504 ** library.
66506 #ifdef SQLITE_TEST
66507 SQLITE_API int sqlite3_found_count = 0;
66508 #endif
66511 ** Test a register to see if it exceeds the current maximum blob size.
66512 ** If it does, record the new maximum blob size.
66514 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
66515 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
66516 #else
66517 # define UPDATE_MAX_BLOBSIZE(P)
66518 #endif
66521 ** Convert the given register into a string if it isn't one
66522 ** already. Return non-zero if a malloc() fails.
66524 #define Stringify(P, enc) \
66525 if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
66526 { goto no_mem; }
66529 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
66530 ** a pointer to a dynamically allocated string where some other entity
66531 ** is responsible for deallocating that string. Because the register
66532 ** does not control the string, it might be deleted without the register
66533 ** knowing it.
66535 ** This routine converts an ephemeral string into a dynamically allocated
66536 ** string that the register itself controls. In other words, it
66537 ** converts an MEM_Ephem string into an MEM_Dyn string.
66539 #define Deephemeralize(P) \
66540 if( ((P)->flags&MEM_Ephem)!=0 \
66541 && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
66543 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
66544 # define isSorter(x) ((x)->pSorter!=0)
66547 ** Argument pMem points at a register that will be passed to a
66548 ** user-defined function or returned to the user as the result of a query.
66549 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
66550 ** routines.
66552 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
66553 int flags = pMem->flags;
66554 if( flags & MEM_Null ){
66555 pMem->type = SQLITE_NULL;
66557 else if( flags & MEM_Int ){
66558 pMem->type = SQLITE_INTEGER;
66560 else if( flags & MEM_Real ){
66561 pMem->type = SQLITE_FLOAT;
66563 else if( flags & MEM_Str ){
66564 pMem->type = SQLITE_TEXT;
66565 }else{
66566 pMem->type = SQLITE_BLOB;
66571 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
66572 ** if we run out of memory.
66574 static VdbeCursor *allocateCursor(
66575 Vdbe *p, /* The virtual machine */
66576 int iCur, /* Index of the new VdbeCursor */
66577 int nField, /* Number of fields in the table or index */
66578 int iDb, /* Database the cursor belongs to, or -1 */
66579 int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
66581 /* Find the memory cell that will be used to store the blob of memory
66582 ** required for this VdbeCursor structure. It is convenient to use a
66583 ** vdbe memory cell to manage the memory allocation required for a
66584 ** VdbeCursor structure for the following reasons:
66586 ** * Sometimes cursor numbers are used for a couple of different
66587 ** purposes in a vdbe program. The different uses might require
66588 ** different sized allocations. Memory cells provide growable
66589 ** allocations.
66591 ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
66592 ** be freed lazily via the sqlite3_release_memory() API. This
66593 ** minimizes the number of malloc calls made by the system.
66595 ** Memory cells for cursors are allocated at the top of the address
66596 ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
66597 ** cursor 1 is managed by memory cell (p->nMem-1), etc.
66599 Mem *pMem = &p->aMem[p->nMem-iCur];
66601 int nByte;
66602 VdbeCursor *pCx = 0;
66603 nByte =
66604 ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
66605 (isBtreeCursor?sqlite3BtreeCursorSize():0);
66607 assert( iCur<p->nCursor );
66608 if( p->apCsr[iCur] ){
66609 sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
66610 p->apCsr[iCur] = 0;
66612 if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
66613 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
66614 memset(pCx, 0, sizeof(VdbeCursor));
66615 pCx->iDb = iDb;
66616 pCx->nField = nField;
66617 if( isBtreeCursor ){
66618 pCx->pCursor = (BtCursor*)
66619 &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
66620 sqlite3BtreeCursorZero(pCx->pCursor);
66623 return pCx;
66627 ** Try to convert a value into a numeric representation if we can
66628 ** do so without loss of information. In other words, if the string
66629 ** looks like a number, convert it into a number. If it does not
66630 ** look like a number, leave it alone.
66632 static void applyNumericAffinity(Mem *pRec){
66633 if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
66634 double rValue;
66635 i64 iValue;
66636 u8 enc = pRec->enc;
66637 if( (pRec->flags&MEM_Str)==0 ) return;
66638 if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
66639 if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
66640 pRec->u.i = iValue;
66641 pRec->flags |= MEM_Int;
66642 }else{
66643 pRec->r = rValue;
66644 pRec->flags |= MEM_Real;
66650 ** Processing is determine by the affinity parameter:
66652 ** SQLITE_AFF_INTEGER:
66653 ** SQLITE_AFF_REAL:
66654 ** SQLITE_AFF_NUMERIC:
66655 ** Try to convert pRec to an integer representation or a
66656 ** floating-point representation if an integer representation
66657 ** is not possible. Note that the integer representation is
66658 ** always preferred, even if the affinity is REAL, because
66659 ** an integer representation is more space efficient on disk.
66661 ** SQLITE_AFF_TEXT:
66662 ** Convert pRec to a text representation.
66664 ** SQLITE_AFF_NONE:
66665 ** No-op. pRec is unchanged.
66667 static void applyAffinity(
66668 Mem *pRec, /* The value to apply affinity to */
66669 char affinity, /* The affinity to be applied */
66670 u8 enc /* Use this text encoding */
66672 if( affinity==SQLITE_AFF_TEXT ){
66673 /* Only attempt the conversion to TEXT if there is an integer or real
66674 ** representation (blob and NULL do not get converted) but no string
66675 ** representation.
66677 if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
66678 sqlite3VdbeMemStringify(pRec, enc);
66680 pRec->flags &= ~(MEM_Real|MEM_Int);
66681 }else if( affinity!=SQLITE_AFF_NONE ){
66682 assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
66683 || affinity==SQLITE_AFF_NUMERIC );
66684 applyNumericAffinity(pRec);
66685 if( pRec->flags & MEM_Real ){
66686 sqlite3VdbeIntegerAffinity(pRec);
66692 ** Try to convert the type of a function argument or a result column
66693 ** into a numeric representation. Use either INTEGER or REAL whichever
66694 ** is appropriate. But only do the conversion if it is possible without
66695 ** loss of information and return the revised type of the argument.
66697 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
66698 Mem *pMem = (Mem*)pVal;
66699 if( pMem->type==SQLITE_TEXT ){
66700 applyNumericAffinity(pMem);
66701 sqlite3VdbeMemStoreType(pMem);
66703 return pMem->type;
66707 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
66708 ** not the internal Mem* type.
66710 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
66711 sqlite3_value *pVal,
66712 u8 affinity,
66713 u8 enc
66715 applyAffinity((Mem *)pVal, affinity, enc);
66718 #ifdef SQLITE_DEBUG
66720 ** Write a nice string representation of the contents of cell pMem
66721 ** into buffer zBuf, length nBuf.
66723 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
66724 char *zCsr = zBuf;
66725 int f = pMem->flags;
66727 static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
66729 if( f&MEM_Blob ){
66730 int i;
66731 char c;
66732 if( f & MEM_Dyn ){
66733 c = 'z';
66734 assert( (f & (MEM_Static|MEM_Ephem))==0 );
66735 }else if( f & MEM_Static ){
66736 c = 't';
66737 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
66738 }else if( f & MEM_Ephem ){
66739 c = 'e';
66740 assert( (f & (MEM_Static|MEM_Dyn))==0 );
66741 }else{
66742 c = 's';
66745 sqlite3_snprintf(100, zCsr, "%c", c);
66746 zCsr += sqlite3Strlen30(zCsr);
66747 sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
66748 zCsr += sqlite3Strlen30(zCsr);
66749 for(i=0; i<16 && i<pMem->n; i++){
66750 sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
66751 zCsr += sqlite3Strlen30(zCsr);
66753 for(i=0; i<16 && i<pMem->n; i++){
66754 char z = pMem->z[i];
66755 if( z<32 || z>126 ) *zCsr++ = '.';
66756 else *zCsr++ = z;
66759 sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
66760 zCsr += sqlite3Strlen30(zCsr);
66761 if( f & MEM_Zero ){
66762 sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
66763 zCsr += sqlite3Strlen30(zCsr);
66765 *zCsr = '\0';
66766 }else if( f & MEM_Str ){
66767 int j, k;
66768 zBuf[0] = ' ';
66769 if( f & MEM_Dyn ){
66770 zBuf[1] = 'z';
66771 assert( (f & (MEM_Static|MEM_Ephem))==0 );
66772 }else if( f & MEM_Static ){
66773 zBuf[1] = 't';
66774 assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
66775 }else if( f & MEM_Ephem ){
66776 zBuf[1] = 'e';
66777 assert( (f & (MEM_Static|MEM_Dyn))==0 );
66778 }else{
66779 zBuf[1] = 's';
66781 k = 2;
66782 sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
66783 k += sqlite3Strlen30(&zBuf[k]);
66784 zBuf[k++] = '[';
66785 for(j=0; j<15 && j<pMem->n; j++){
66786 u8 c = pMem->z[j];
66787 if( c>=0x20 && c<0x7f ){
66788 zBuf[k++] = c;
66789 }else{
66790 zBuf[k++] = '.';
66793 zBuf[k++] = ']';
66794 sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
66795 k += sqlite3Strlen30(&zBuf[k]);
66796 zBuf[k++] = 0;
66799 #endif
66801 #ifdef SQLITE_DEBUG
66803 ** Print the value of a register for tracing purposes:
66805 static void memTracePrint(Mem *p){
66806 if( p->flags & MEM_Invalid ){
66807 printf(" undefined");
66808 }else if( p->flags & MEM_Null ){
66809 printf(" NULL");
66810 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
66811 printf(" si:%lld", p->u.i);
66812 }else if( p->flags & MEM_Int ){
66813 printf(" i:%lld", p->u.i);
66814 #ifndef SQLITE_OMIT_FLOATING_POINT
66815 }else if( p->flags & MEM_Real ){
66816 printf(" r:%g", p->r);
66817 #endif
66818 }else if( p->flags & MEM_RowSet ){
66819 printf(" (rowset)");
66820 }else{
66821 char zBuf[200];
66822 sqlite3VdbeMemPrettyPrint(p, zBuf);
66823 printf(" %s", zBuf);
66826 static void registerTrace(int iReg, Mem *p){
66827 printf("REG[%d] = ", iReg);
66828 memTracePrint(p);
66829 printf("\n");
66831 #endif
66833 #ifdef SQLITE_DEBUG
66834 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
66835 #else
66836 # define REGISTER_TRACE(R,M)
66837 #endif
66840 #ifdef VDBE_PROFILE
66843 ** hwtime.h contains inline assembler code for implementing
66844 ** high-performance timing routines.
66846 /************** Include hwtime.h in the middle of vdbe.c *********************/
66847 /************** Begin file hwtime.h ******************************************/
66849 ** 2008 May 27
66851 ** The author disclaims copyright to this source code. In place of
66852 ** a legal notice, here is a blessing:
66854 ** May you do good and not evil.
66855 ** May you find forgiveness for yourself and forgive others.
66856 ** May you share freely, never taking more than you give.
66858 ******************************************************************************
66860 ** This file contains inline asm code for retrieving "high-performance"
66861 ** counters for x86 class CPUs.
66863 #ifndef _HWTIME_H_
66864 #define _HWTIME_H_
66867 ** The following routine only works on pentium-class (or newer) processors.
66868 ** It uses the RDTSC opcode to read the cycle count value out of the
66869 ** processor and returns that value. This can be used for high-res
66870 ** profiling.
66872 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
66873 (defined(i386) || defined(__i386__) || defined(_M_IX86))
66875 #if defined(__GNUC__)
66877 __inline__ sqlite_uint64 sqlite3Hwtime(void){
66878 unsigned int lo, hi;
66879 __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
66880 return (sqlite_uint64)hi << 32 | lo;
66883 #elif defined(_MSC_VER)
66885 __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
66886 __asm {
66887 rdtsc
66888 ret ; return value at EDX:EAX
66892 #endif
66894 #elif (defined(__GNUC__) && defined(__x86_64__))
66896 __inline__ sqlite_uint64 sqlite3Hwtime(void){
66897 unsigned long val;
66898 __asm__ __volatile__ ("rdtsc" : "=A" (val));
66899 return val;
66902 #elif (defined(__GNUC__) && defined(__ppc__))
66904 __inline__ sqlite_uint64 sqlite3Hwtime(void){
66905 unsigned long long retval;
66906 unsigned long junk;
66907 __asm__ __volatile__ ("\n\
66908 1: mftbu %1\n\
66909 mftb %L0\n\
66910 mftbu %0\n\
66911 cmpw %0,%1\n\
66912 bne 1b"
66913 : "=r" (retval), "=r" (junk));
66914 return retval;
66917 #else
66919 #error Need implementation of sqlite3Hwtime() for your platform.
66922 ** To compile without implementing sqlite3Hwtime() for your platform,
66923 ** you can remove the above #error and use the following
66924 ** stub function. You will lose timing support for many
66925 ** of the debugging and testing utilities, but it should at
66926 ** least compile and run.
66928 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
66930 #endif
66932 #endif /* !defined(_HWTIME_H_) */
66934 /************** End of hwtime.h **********************************************/
66935 /************** Continuing where we left off in vdbe.c ***********************/
66937 #endif
66940 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
66941 ** sqlite3_interrupt() routine has been called. If it has been, then
66942 ** processing of the VDBE program is interrupted.
66944 ** This macro added to every instruction that does a jump in order to
66945 ** implement a loop. This test used to be on every single instruction,
66946 ** but that meant we more testing than we needed. By only testing the
66947 ** flag on jump instructions, we get a (small) speed improvement.
66949 #define CHECK_FOR_INTERRUPT \
66950 if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
66953 #ifndef NDEBUG
66955 ** This function is only called from within an assert() expression. It
66956 ** checks that the sqlite3.nTransaction variable is correctly set to
66957 ** the number of non-transaction savepoints currently in the
66958 ** linked list starting at sqlite3.pSavepoint.
66960 ** Usage:
66962 ** assert( checkSavepointCount(db) );
66964 static int checkSavepointCount(sqlite3 *db){
66965 int n = 0;
66966 Savepoint *p;
66967 for(p=db->pSavepoint; p; p=p->pNext) n++;
66968 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
66969 return 1;
66971 #endif
66975 ** Execute as much of a VDBE program as we can then return.
66977 ** sqlite3VdbeMakeReady() must be called before this routine in order to
66978 ** close the program with a final OP_Halt and to set up the callbacks
66979 ** and the error message pointer.
66981 ** Whenever a row or result data is available, this routine will either
66982 ** invoke the result callback (if there is one) or return with
66983 ** SQLITE_ROW.
66985 ** If an attempt is made to open a locked database, then this routine
66986 ** will either invoke the busy callback (if there is one) or it will
66987 ** return SQLITE_BUSY.
66989 ** If an error occurs, an error message is written to memory obtained
66990 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
66991 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
66993 ** If the callback ever returns non-zero, then the program exits
66994 ** immediately. There will be no error message but the p->rc field is
66995 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
66997 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
66998 ** routine to return SQLITE_ERROR.
67000 ** Other fatal errors return SQLITE_ERROR.
67002 ** After this routine has finished, sqlite3VdbeFinalize() should be
67003 ** used to clean up the mess that was left behind.
67005 SQLITE_PRIVATE int sqlite3VdbeExec(
67006 Vdbe *p /* The VDBE */
67008 int pc=0; /* The program counter */
67009 Op *aOp = p->aOp; /* Copy of p->aOp */
67010 Op *pOp; /* Current operation */
67011 int rc = SQLITE_OK; /* Value to return */
67012 sqlite3 *db = p->db; /* The database */
67013 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
67014 u8 encoding = ENC(db); /* The database encoding */
67015 int iCompare = 0; /* Result of last OP_Compare operation */
67016 unsigned nVmStep = 0; /* Number of virtual machine steps */
67017 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
67018 unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
67019 #endif
67020 Mem *aMem = p->aMem; /* Copy of p->aMem */
67021 Mem *pIn1 = 0; /* 1st input operand */
67022 Mem *pIn2 = 0; /* 2nd input operand */
67023 Mem *pIn3 = 0; /* 3rd input operand */
67024 Mem *pOut = 0; /* Output operand */
67025 int *aPermute = 0; /* Permutation of columns for OP_Compare */
67026 i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
67027 #ifdef VDBE_PROFILE
67028 u64 start; /* CPU clock count at start of opcode */
67029 int origPc; /* Program counter at start of opcode */
67030 #endif
67031 /*** INSERT STACK UNION HERE ***/
67033 assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
67034 sqlite3VdbeEnter(p);
67035 if( p->rc==SQLITE_NOMEM ){
67036 /* This happens if a malloc() inside a call to sqlite3_column_text() or
67037 ** sqlite3_column_text16() failed. */
67038 goto no_mem;
67040 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
67041 assert( p->bIsReader || p->readOnly!=0 );
67042 p->rc = SQLITE_OK;
67043 p->iCurrentTime = 0;
67044 assert( p->explain==0 );
67045 p->pResultSet = 0;
67046 db->busyHandler.nBusy = 0;
67047 CHECK_FOR_INTERRUPT;
67048 sqlite3VdbeIOTraceSql(p);
67049 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
67050 if( db->xProgress ){
67051 assert( 0 < db->nProgressOps );
67052 nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
67053 if( nProgressLimit==0 ){
67054 nProgressLimit = db->nProgressOps;
67055 }else{
67056 nProgressLimit %= (unsigned)db->nProgressOps;
67059 #endif
67060 #ifdef SQLITE_DEBUG
67061 sqlite3BeginBenignMalloc();
67062 if( p->pc==0
67063 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
67065 int i;
67066 int once = 1;
67067 sqlite3VdbePrintSql(p);
67068 if( p->db->flags & SQLITE_VdbeListing ){
67069 printf("VDBE Program Listing:\n");
67070 for(i=0; i<p->nOp; i++){
67071 sqlite3VdbePrintOp(stdout, i, &aOp[i]);
67074 if( p->db->flags & SQLITE_VdbeEQP ){
67075 for(i=0; i<p->nOp; i++){
67076 if( aOp[i].opcode==OP_Explain ){
67077 if( once ) printf("VDBE Query Plan:\n");
67078 printf("%s\n", aOp[i].p4.z);
67079 once = 0;
67083 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
67085 sqlite3EndBenignMalloc();
67086 #endif
67087 for(pc=p->pc; rc==SQLITE_OK; pc++){
67088 assert( pc>=0 && pc<p->nOp );
67089 if( db->mallocFailed ) goto no_mem;
67090 #ifdef VDBE_PROFILE
67091 origPc = pc;
67092 start = sqlite3Hwtime();
67093 #endif
67094 nVmStep++;
67095 pOp = &aOp[pc];
67097 /* Only allow tracing if SQLITE_DEBUG is defined.
67099 #ifdef SQLITE_DEBUG
67100 if( db->flags & SQLITE_VdbeTrace ){
67101 sqlite3VdbePrintOp(stdout, pc, pOp);
67103 #endif
67106 /* Check to see if we need to simulate an interrupt. This only happens
67107 ** if we have a special test build.
67109 #ifdef SQLITE_TEST
67110 if( sqlite3_interrupt_count>0 ){
67111 sqlite3_interrupt_count--;
67112 if( sqlite3_interrupt_count==0 ){
67113 sqlite3_interrupt(db);
67116 #endif
67118 /* On any opcode with the "out2-prerelease" tag, free any
67119 ** external allocations out of mem[p2] and set mem[p2] to be
67120 ** an undefined integer. Opcodes will either fill in the integer
67121 ** value or convert mem[p2] to a different type.
67123 assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
67124 if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
67125 assert( pOp->p2>0 );
67126 assert( pOp->p2<=(p->nMem-p->nCursor) );
67127 pOut = &aMem[pOp->p2];
67128 memAboutToChange(p, pOut);
67129 VdbeMemRelease(pOut);
67130 pOut->flags = MEM_Int;
67133 /* Sanity checking on other operands */
67134 #ifdef SQLITE_DEBUG
67135 if( (pOp->opflags & OPFLG_IN1)!=0 ){
67136 assert( pOp->p1>0 );
67137 assert( pOp->p1<=(p->nMem-p->nCursor) );
67138 assert( memIsValid(&aMem[pOp->p1]) );
67139 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
67141 if( (pOp->opflags & OPFLG_IN2)!=0 ){
67142 assert( pOp->p2>0 );
67143 assert( pOp->p2<=(p->nMem-p->nCursor) );
67144 assert( memIsValid(&aMem[pOp->p2]) );
67145 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
67147 if( (pOp->opflags & OPFLG_IN3)!=0 ){
67148 assert( pOp->p3>0 );
67149 assert( pOp->p3<=(p->nMem-p->nCursor) );
67150 assert( memIsValid(&aMem[pOp->p3]) );
67151 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
67153 if( (pOp->opflags & OPFLG_OUT2)!=0 ){
67154 assert( pOp->p2>0 );
67155 assert( pOp->p2<=(p->nMem-p->nCursor) );
67156 memAboutToChange(p, &aMem[pOp->p2]);
67158 if( (pOp->opflags & OPFLG_OUT3)!=0 ){
67159 assert( pOp->p3>0 );
67160 assert( pOp->p3<=(p->nMem-p->nCursor) );
67161 memAboutToChange(p, &aMem[pOp->p3]);
67163 #endif
67165 switch( pOp->opcode ){
67167 /*****************************************************************************
67168 ** What follows is a massive switch statement where each case implements a
67169 ** separate instruction in the virtual machine. If we follow the usual
67170 ** indentation conventions, each case should be indented by 6 spaces. But
67171 ** that is a lot of wasted space on the left margin. So the code within
67172 ** the switch statement will break with convention and be flush-left. Another
67173 ** big comment (similar to this one) will mark the point in the code where
67174 ** we transition back to normal indentation.
67176 ** The formatting of each case is important. The makefile for SQLite
67177 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
67178 ** file looking for lines that begin with "case OP_". The opcodes.h files
67179 ** will be filled with #defines that give unique integer values to each
67180 ** opcode and the opcodes.c file is filled with an array of strings where
67181 ** each string is the symbolic name for the corresponding opcode. If the
67182 ** case statement is followed by a comment of the form "/# same as ... #/"
67183 ** that comment is used to determine the particular value of the opcode.
67185 ** Other keywords in the comment that follows each case are used to
67186 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
67187 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
67188 ** the mkopcodeh.awk script for additional information.
67190 ** Documentation about VDBE opcodes is generated by scanning this file
67191 ** for lines of that contain "Opcode:". That line and all subsequent
67192 ** comment lines are used in the generation of the opcode.html documentation
67193 ** file.
67195 ** SUMMARY:
67197 ** Formatting is important to scripts that scan this file.
67198 ** Do not deviate from the formatting style currently in use.
67200 *****************************************************************************/
67202 /* Opcode: Goto * P2 * * *
67204 ** An unconditional jump to address P2.
67205 ** The next instruction executed will be
67206 ** the one at index P2 from the beginning of
67207 ** the program.
67209 case OP_Goto: { /* jump */
67210 pc = pOp->p2 - 1;
67212 /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
67213 ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
67214 ** completion. Check to see if sqlite3_interrupt() has been called
67215 ** or if the progress callback needs to be invoked.
67217 ** This code uses unstructured "goto" statements and does not look clean.
67218 ** But that is not due to sloppy coding habits. The code is written this
67219 ** way for performance, to avoid having to run the interrupt and progress
67220 ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
67221 ** faster according to "valgrind --tool=cachegrind" */
67222 check_for_interrupt:
67223 CHECK_FOR_INTERRUPT;
67224 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
67225 /* Call the progress callback if it is configured and the required number
67226 ** of VDBE ops have been executed (either since this invocation of
67227 ** sqlite3VdbeExec() or since last time the progress callback was called).
67228 ** If the progress callback returns non-zero, exit the virtual machine with
67229 ** a return code SQLITE_ABORT.
67231 if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
67232 assert( db->nProgressOps!=0 );
67233 nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
67234 if( db->xProgress(db->pProgressArg) ){
67235 rc = SQLITE_INTERRUPT;
67236 goto vdbe_error_halt;
67239 #endif
67241 break;
67244 /* Opcode: Gosub P1 P2 * * *
67246 ** Write the current address onto register P1
67247 ** and then jump to address P2.
67249 case OP_Gosub: { /* jump */
67250 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
67251 pIn1 = &aMem[pOp->p1];
67252 assert( (pIn1->flags & MEM_Dyn)==0 );
67253 memAboutToChange(p, pIn1);
67254 pIn1->flags = MEM_Int;
67255 pIn1->u.i = pc;
67256 REGISTER_TRACE(pOp->p1, pIn1);
67257 pc = pOp->p2 - 1;
67258 break;
67261 /* Opcode: Return P1 * * * *
67263 ** Jump to the next instruction after the address in register P1.
67265 case OP_Return: { /* in1 */
67266 pIn1 = &aMem[pOp->p1];
67267 assert( pIn1->flags & MEM_Int );
67268 pc = (int)pIn1->u.i;
67269 break;
67272 /* Opcode: Yield P1 * * * *
67274 ** Swap the program counter with the value in register P1.
67276 case OP_Yield: { /* in1 */
67277 int pcDest;
67278 pIn1 = &aMem[pOp->p1];
67279 assert( (pIn1->flags & MEM_Dyn)==0 );
67280 pIn1->flags = MEM_Int;
67281 pcDest = (int)pIn1->u.i;
67282 pIn1->u.i = pc;
67283 REGISTER_TRACE(pOp->p1, pIn1);
67284 pc = pcDest;
67285 break;
67288 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
67289 ** Synopsis: if r[P3] null then halt
67291 ** Check the value in register P3. If it is NULL then Halt using
67292 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
67293 ** value in register P3 is not NULL, then this routine is a no-op.
67294 ** The P5 parameter should be 1.
67296 case OP_HaltIfNull: { /* in3 */
67297 pIn3 = &aMem[pOp->p3];
67298 if( (pIn3->flags & MEM_Null)==0 ) break;
67299 /* Fall through into OP_Halt */
67302 /* Opcode: Halt P1 P2 * P4 P5
67304 ** Exit immediately. All open cursors, etc are closed
67305 ** automatically.
67307 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
67308 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
67309 ** For errors, it can be some other value. If P1!=0 then P2 will determine
67310 ** whether or not to rollback the current transaction. Do not rollback
67311 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
67312 ** then back out all changes that have occurred during this execution of the
67313 ** VDBE, but do not rollback the transaction.
67315 ** If P4 is not null then it is an error message string.
67317 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
67319 ** 0: (no change)
67320 ** 1: NOT NULL contraint failed: P4
67321 ** 2: UNIQUE constraint failed: P4
67322 ** 3: CHECK constraint failed: P4
67323 ** 4: FOREIGN KEY constraint failed: P4
67325 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
67326 ** omitted.
67328 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
67329 ** every program. So a jump past the last instruction of the program
67330 ** is the same as executing Halt.
67332 case OP_Halt: {
67333 const char *zType;
67334 const char *zLogFmt;
67336 if( pOp->p1==SQLITE_OK && p->pFrame ){
67337 /* Halt the sub-program. Return control to the parent frame. */
67338 VdbeFrame *pFrame = p->pFrame;
67339 p->pFrame = pFrame->pParent;
67340 p->nFrame--;
67341 sqlite3VdbeSetChanges(db, p->nChange);
67342 pc = sqlite3VdbeFrameRestore(pFrame);
67343 lastRowid = db->lastRowid;
67344 if( pOp->p2==OE_Ignore ){
67345 /* Instruction pc is the OP_Program that invoked the sub-program
67346 ** currently being halted. If the p2 instruction of this OP_Halt
67347 ** instruction is set to OE_Ignore, then the sub-program is throwing
67348 ** an IGNORE exception. In this case jump to the address specified
67349 ** as the p2 of the calling OP_Program. */
67350 pc = p->aOp[pc].p2-1;
67352 aOp = p->aOp;
67353 aMem = p->aMem;
67354 break;
67356 p->rc = pOp->p1;
67357 p->errorAction = (u8)pOp->p2;
67358 p->pc = pc;
67359 if( p->rc ){
67360 if( pOp->p5 ){
67361 static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
67362 "FOREIGN KEY" };
67363 assert( pOp->p5>=1 && pOp->p5<=4 );
67364 testcase( pOp->p5==1 );
67365 testcase( pOp->p5==2 );
67366 testcase( pOp->p5==3 );
67367 testcase( pOp->p5==4 );
67368 zType = azType[pOp->p5-1];
67369 }else{
67370 zType = 0;
67372 assert( zType!=0 || pOp->p4.z!=0 );
67373 zLogFmt = "abort at %d in [%s]: %s";
67374 if( zType && pOp->p4.z ){
67375 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
67376 zType, pOp->p4.z);
67377 }else if( pOp->p4.z ){
67378 sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
67379 }else{
67380 sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
67382 sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
67384 rc = sqlite3VdbeHalt(p);
67385 assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
67386 if( rc==SQLITE_BUSY ){
67387 p->rc = rc = SQLITE_BUSY;
67388 }else{
67389 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
67390 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
67391 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
67393 goto vdbe_return;
67396 /* Opcode: Integer P1 P2 * * *
67397 ** Synopsis: r[P2]=P1
67399 ** The 32-bit integer value P1 is written into register P2.
67401 case OP_Integer: { /* out2-prerelease */
67402 pOut->u.i = pOp->p1;
67403 break;
67406 /* Opcode: Int64 * P2 * P4 *
67407 ** Synopsis: r[P2]=P4
67409 ** P4 is a pointer to a 64-bit integer value.
67410 ** Write that value into register P2.
67412 case OP_Int64: { /* out2-prerelease */
67413 assert( pOp->p4.pI64!=0 );
67414 pOut->u.i = *pOp->p4.pI64;
67415 break;
67418 #ifndef SQLITE_OMIT_FLOATING_POINT
67419 /* Opcode: Real * P2 * P4 *
67420 ** Synopsis: r[P2]=P4
67422 ** P4 is a pointer to a 64-bit floating point value.
67423 ** Write that value into register P2.
67425 case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
67426 pOut->flags = MEM_Real;
67427 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
67428 pOut->r = *pOp->p4.pReal;
67429 break;
67431 #endif
67433 /* Opcode: String8 * P2 * P4 *
67434 ** Synopsis: r[P2]='P4'
67436 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
67437 ** into an OP_String before it is executed for the first time.
67439 case OP_String8: { /* same as TK_STRING, out2-prerelease */
67440 assert( pOp->p4.z!=0 );
67441 pOp->opcode = OP_String;
67442 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
67444 #ifndef SQLITE_OMIT_UTF16
67445 if( encoding!=SQLITE_UTF8 ){
67446 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
67447 if( rc==SQLITE_TOOBIG ) goto too_big;
67448 if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
67449 assert( pOut->zMalloc==pOut->z );
67450 assert( pOut->flags & MEM_Dyn );
67451 pOut->zMalloc = 0;
67452 pOut->flags |= MEM_Static;
67453 pOut->flags &= ~MEM_Dyn;
67454 if( pOp->p4type==P4_DYNAMIC ){
67455 sqlite3DbFree(db, pOp->p4.z);
67457 pOp->p4type = P4_DYNAMIC;
67458 pOp->p4.z = pOut->z;
67459 pOp->p1 = pOut->n;
67461 #endif
67462 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67463 goto too_big;
67465 /* Fall through to the next case, OP_String */
67468 /* Opcode: String P1 P2 * P4 *
67469 ** Synopsis: r[P2]='P4' (len=P1)
67471 ** The string value P4 of length P1 (bytes) is stored in register P2.
67473 case OP_String: { /* out2-prerelease */
67474 assert( pOp->p4.z!=0 );
67475 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
67476 pOut->z = pOp->p4.z;
67477 pOut->n = pOp->p1;
67478 pOut->enc = encoding;
67479 UPDATE_MAX_BLOBSIZE(pOut);
67480 break;
67483 /* Opcode: Null P1 P2 P3 * *
67484 ** Synopsis: r[P2..P3]=NULL
67486 ** Write a NULL into registers P2. If P3 greater than P2, then also write
67487 ** NULL into register P3 and every register in between P2 and P3. If P3
67488 ** is less than P2 (typically P3 is zero) then only register P2 is
67489 ** set to NULL.
67491 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
67492 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
67493 ** OP_Ne or OP_Eq.
67495 case OP_Null: { /* out2-prerelease */
67496 int cnt;
67497 u16 nullFlag;
67498 cnt = pOp->p3-pOp->p2;
67499 assert( pOp->p3<=(p->nMem-p->nCursor) );
67500 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
67501 while( cnt>0 ){
67502 pOut++;
67503 memAboutToChange(p, pOut);
67504 VdbeMemRelease(pOut);
67505 pOut->flags = nullFlag;
67506 cnt--;
67508 break;
67512 /* Opcode: Blob P1 P2 * P4
67513 ** Synopsis: r[P2]=P4 (len=P1)
67515 ** P4 points to a blob of data P1 bytes long. Store this
67516 ** blob in register P2.
67518 case OP_Blob: { /* out2-prerelease */
67519 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
67520 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
67521 pOut->enc = encoding;
67522 UPDATE_MAX_BLOBSIZE(pOut);
67523 break;
67526 /* Opcode: Variable P1 P2 * P4 *
67527 ** Synopsis: r[P2]=parameter(P1,P4)
67529 ** Transfer the values of bound parameter P1 into register P2
67531 ** If the parameter is named, then its name appears in P4 and P3==1.
67532 ** The P4 value is used by sqlite3_bind_parameter_name().
67534 case OP_Variable: { /* out2-prerelease */
67535 Mem *pVar; /* Value being transferred */
67537 assert( pOp->p1>0 && pOp->p1<=p->nVar );
67538 assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
67539 pVar = &p->aVar[pOp->p1 - 1];
67540 if( sqlite3VdbeMemTooBig(pVar) ){
67541 goto too_big;
67543 sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
67544 UPDATE_MAX_BLOBSIZE(pOut);
67545 break;
67548 /* Opcode: Move P1 P2 P3 * *
67549 ** Synopsis: r[P2@P3]=r[P1@P3]
67551 ** Move the values in register P1..P1+P3 over into
67552 ** registers P2..P2+P3. Registers P1..P1+P3 are
67553 ** left holding a NULL. It is an error for register ranges
67554 ** P1..P1+P3 and P2..P2+P3 to overlap.
67556 case OP_Move: {
67557 char *zMalloc; /* Holding variable for allocated memory */
67558 int n; /* Number of registers left to copy */
67559 int p1; /* Register to copy from */
67560 int p2; /* Register to copy to */
67562 n = pOp->p3;
67563 p1 = pOp->p1;
67564 p2 = pOp->p2;
67565 assert( n>=0 && p1>0 && p2>0 );
67566 assert( p1+n<=p2 || p2+n<=p1 );
67568 pIn1 = &aMem[p1];
67569 pOut = &aMem[p2];
67571 assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
67572 assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
67573 assert( memIsValid(pIn1) );
67574 memAboutToChange(p, pOut);
67575 zMalloc = pOut->zMalloc;
67576 pOut->zMalloc = 0;
67577 sqlite3VdbeMemMove(pOut, pIn1);
67578 #ifdef SQLITE_DEBUG
67579 if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
67580 pOut->pScopyFrom += p1 - pOp->p2;
67582 #endif
67583 pIn1->zMalloc = zMalloc;
67584 REGISTER_TRACE(p2++, pOut);
67585 pIn1++;
67586 pOut++;
67587 }while( n-- );
67588 break;
67591 /* Opcode: Copy P1 P2 P3 * *
67592 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
67594 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
67596 ** This instruction makes a deep copy of the value. A duplicate
67597 ** is made of any string or blob constant. See also OP_SCopy.
67599 case OP_Copy: {
67600 int n;
67602 n = pOp->p3;
67603 pIn1 = &aMem[pOp->p1];
67604 pOut = &aMem[pOp->p2];
67605 assert( pOut!=pIn1 );
67606 while( 1 ){
67607 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
67608 Deephemeralize(pOut);
67609 #ifdef SQLITE_DEBUG
67610 pOut->pScopyFrom = 0;
67611 #endif
67612 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
67613 if( (n--)==0 ) break;
67614 pOut++;
67615 pIn1++;
67617 break;
67620 /* Opcode: SCopy P1 P2 * * *
67621 ** Synopsis: r[P2]=r[P1]
67623 ** Make a shallow copy of register P1 into register P2.
67625 ** This instruction makes a shallow copy of the value. If the value
67626 ** is a string or blob, then the copy is only a pointer to the
67627 ** original and hence if the original changes so will the copy.
67628 ** Worse, if the original is deallocated, the copy becomes invalid.
67629 ** Thus the program must guarantee that the original will not change
67630 ** during the lifetime of the copy. Use OP_Copy to make a complete
67631 ** copy.
67633 case OP_SCopy: { /* out2 */
67634 pIn1 = &aMem[pOp->p1];
67635 pOut = &aMem[pOp->p2];
67636 assert( pOut!=pIn1 );
67637 sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
67638 #ifdef SQLITE_DEBUG
67639 if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
67640 #endif
67641 break;
67644 /* Opcode: ResultRow P1 P2 * * *
67645 ** Synopsis: output=r[P1@P2]
67647 ** The registers P1 through P1+P2-1 contain a single row of
67648 ** results. This opcode causes the sqlite3_step() call to terminate
67649 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
67650 ** structure to provide access to the top P1 values as the result
67651 ** row.
67653 case OP_ResultRow: {
67654 Mem *pMem;
67655 int i;
67656 assert( p->nResColumn==pOp->p2 );
67657 assert( pOp->p1>0 );
67658 assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
67660 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
67661 /* Run the progress counter just before returning.
67663 if( db->xProgress!=0
67664 && nVmStep>=nProgressLimit
67665 && db->xProgress(db->pProgressArg)!=0
67667 rc = SQLITE_INTERRUPT;
67668 goto vdbe_error_halt;
67670 #endif
67672 /* If this statement has violated immediate foreign key constraints, do
67673 ** not return the number of rows modified. And do not RELEASE the statement
67674 ** transaction. It needs to be rolled back. */
67675 if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
67676 assert( db->flags&SQLITE_CountRows );
67677 assert( p->usesStmtJournal );
67678 break;
67681 /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
67682 ** DML statements invoke this opcode to return the number of rows
67683 ** modified to the user. This is the only way that a VM that
67684 ** opens a statement transaction may invoke this opcode.
67686 ** In case this is such a statement, close any statement transaction
67687 ** opened by this VM before returning control to the user. This is to
67688 ** ensure that statement-transactions are always nested, not overlapping.
67689 ** If the open statement-transaction is not closed here, then the user
67690 ** may step another VM that opens its own statement transaction. This
67691 ** may lead to overlapping statement transactions.
67693 ** The statement transaction is never a top-level transaction. Hence
67694 ** the RELEASE call below can never fail.
67696 assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
67697 rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
67698 if( NEVER(rc!=SQLITE_OK) ){
67699 break;
67702 /* Invalidate all ephemeral cursor row caches */
67703 p->cacheCtr = (p->cacheCtr + 2)|1;
67705 /* Make sure the results of the current row are \000 terminated
67706 ** and have an assigned type. The results are de-ephemeralized as
67707 ** a side effect.
67709 pMem = p->pResultSet = &aMem[pOp->p1];
67710 for(i=0; i<pOp->p2; i++){
67711 assert( memIsValid(&pMem[i]) );
67712 Deephemeralize(&pMem[i]);
67713 assert( (pMem[i].flags & MEM_Ephem)==0
67714 || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
67715 sqlite3VdbeMemNulTerminate(&pMem[i]);
67716 sqlite3VdbeMemStoreType(&pMem[i]);
67717 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
67719 if( db->mallocFailed ) goto no_mem;
67721 /* Return SQLITE_ROW
67723 p->pc = pc + 1;
67724 rc = SQLITE_ROW;
67725 goto vdbe_return;
67728 /* Opcode: Concat P1 P2 P3 * *
67729 ** Synopsis: r[P3]=r[P2]+r[P1]
67731 ** Add the text in register P1 onto the end of the text in
67732 ** register P2 and store the result in register P3.
67733 ** If either the P1 or P2 text are NULL then store NULL in P3.
67735 ** P3 = P2 || P1
67737 ** It is illegal for P1 and P3 to be the same register. Sometimes,
67738 ** if P3 is the same register as P2, the implementation is able
67739 ** to avoid a memcpy().
67741 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
67742 i64 nByte;
67744 pIn1 = &aMem[pOp->p1];
67745 pIn2 = &aMem[pOp->p2];
67746 pOut = &aMem[pOp->p3];
67747 assert( pIn1!=pOut );
67748 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
67749 sqlite3VdbeMemSetNull(pOut);
67750 break;
67752 if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
67753 Stringify(pIn1, encoding);
67754 Stringify(pIn2, encoding);
67755 nByte = pIn1->n + pIn2->n;
67756 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67757 goto too_big;
67759 MemSetTypeFlag(pOut, MEM_Str);
67760 if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
67761 goto no_mem;
67763 if( pOut!=pIn2 ){
67764 memcpy(pOut->z, pIn2->z, pIn2->n);
67766 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
67767 pOut->z[nByte]=0;
67768 pOut->z[nByte+1] = 0;
67769 pOut->flags |= MEM_Term;
67770 pOut->n = (int)nByte;
67771 pOut->enc = encoding;
67772 UPDATE_MAX_BLOBSIZE(pOut);
67773 break;
67776 /* Opcode: Add P1 P2 P3 * *
67777 ** Synopsis: r[P3]=r[P1]+r[P2]
67779 ** Add the value in register P1 to the value in register P2
67780 ** and store the result in register P3.
67781 ** If either input is NULL, the result is NULL.
67783 /* Opcode: Multiply P1 P2 P3 * *
67784 ** Synopsis: r[P3]=r[P1]*r[P2]
67787 ** Multiply the value in register P1 by the value in register P2
67788 ** and store the result in register P3.
67789 ** If either input is NULL, the result is NULL.
67791 /* Opcode: Subtract P1 P2 P3 * *
67792 ** Synopsis: r[P3]=r[P2]-r[P1]
67794 ** Subtract the value in register P1 from the value in register P2
67795 ** and store the result in register P3.
67796 ** If either input is NULL, the result is NULL.
67798 /* Opcode: Divide P1 P2 P3 * *
67799 ** Synopsis: r[P3]=r[P2]/r[P1]
67801 ** Divide the value in register P1 by the value in register P2
67802 ** and store the result in register P3 (P3=P2/P1). If the value in
67803 ** register P1 is zero, then the result is NULL. If either input is
67804 ** NULL, the result is NULL.
67806 /* Opcode: Remainder P1 P2 P3 * *
67807 ** Synopsis: r[P3]=r[P2]%r[P1]
67809 ** Compute the remainder after integer register P2 is divided by
67810 ** register P1 and store the result in register P3.
67811 ** If the value in register P1 is zero the result is NULL.
67812 ** If either operand is NULL, the result is NULL.
67814 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
67815 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
67816 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
67817 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
67818 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
67819 char bIntint; /* Started out as two integer operands */
67820 int flags; /* Combined MEM_* flags from both inputs */
67821 i64 iA; /* Integer value of left operand */
67822 i64 iB; /* Integer value of right operand */
67823 double rA; /* Real value of left operand */
67824 double rB; /* Real value of right operand */
67826 pIn1 = &aMem[pOp->p1];
67827 applyNumericAffinity(pIn1);
67828 pIn2 = &aMem[pOp->p2];
67829 applyNumericAffinity(pIn2);
67830 pOut = &aMem[pOp->p3];
67831 flags = pIn1->flags | pIn2->flags;
67832 if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
67833 if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
67834 iA = pIn1->u.i;
67835 iB = pIn2->u.i;
67836 bIntint = 1;
67837 switch( pOp->opcode ){
67838 case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
67839 case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
67840 case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
67841 case OP_Divide: {
67842 if( iA==0 ) goto arithmetic_result_is_null;
67843 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
67844 iB /= iA;
67845 break;
67847 default: {
67848 if( iA==0 ) goto arithmetic_result_is_null;
67849 if( iA==-1 ) iA = 1;
67850 iB %= iA;
67851 break;
67854 pOut->u.i = iB;
67855 MemSetTypeFlag(pOut, MEM_Int);
67856 }else{
67857 bIntint = 0;
67858 fp_math:
67859 rA = sqlite3VdbeRealValue(pIn1);
67860 rB = sqlite3VdbeRealValue(pIn2);
67861 switch( pOp->opcode ){
67862 case OP_Add: rB += rA; break;
67863 case OP_Subtract: rB -= rA; break;
67864 case OP_Multiply: rB *= rA; break;
67865 case OP_Divide: {
67866 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
67867 if( rA==(double)0 ) goto arithmetic_result_is_null;
67868 rB /= rA;
67869 break;
67871 default: {
67872 iA = (i64)rA;
67873 iB = (i64)rB;
67874 if( iA==0 ) goto arithmetic_result_is_null;
67875 if( iA==-1 ) iA = 1;
67876 rB = (double)(iB % iA);
67877 break;
67880 #ifdef SQLITE_OMIT_FLOATING_POINT
67881 pOut->u.i = rB;
67882 MemSetTypeFlag(pOut, MEM_Int);
67883 #else
67884 if( sqlite3IsNaN(rB) ){
67885 goto arithmetic_result_is_null;
67887 pOut->r = rB;
67888 MemSetTypeFlag(pOut, MEM_Real);
67889 if( (flags & MEM_Real)==0 && !bIntint ){
67890 sqlite3VdbeIntegerAffinity(pOut);
67892 #endif
67894 break;
67896 arithmetic_result_is_null:
67897 sqlite3VdbeMemSetNull(pOut);
67898 break;
67901 /* Opcode: CollSeq P1 * * P4
67903 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
67904 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
67905 ** be returned. This is used by the built-in min(), max() and nullif()
67906 ** functions.
67908 ** If P1 is not zero, then it is a register that a subsequent min() or
67909 ** max() aggregate will set to 1 if the current row is not the minimum or
67910 ** maximum. The P1 register is initialized to 0 by this instruction.
67912 ** The interface used by the implementation of the aforementioned functions
67913 ** to retrieve the collation sequence set by this opcode is not available
67914 ** publicly, only to user functions defined in func.c.
67916 case OP_CollSeq: {
67917 assert( pOp->p4type==P4_COLLSEQ );
67918 if( pOp->p1 ){
67919 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
67921 break;
67924 /* Opcode: Function P1 P2 P3 P4 P5
67925 ** Synopsis: r[P3]=func(r[P2@P5])
67927 ** Invoke a user function (P4 is a pointer to a Function structure that
67928 ** defines the function) with P5 arguments taken from register P2 and
67929 ** successors. The result of the function is stored in register P3.
67930 ** Register P3 must not be one of the function inputs.
67932 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
67933 ** function was determined to be constant at compile time. If the first
67934 ** argument was constant then bit 0 of P1 is set. This is used to determine
67935 ** whether meta data associated with a user function argument using the
67936 ** sqlite3_set_auxdata() API may be safely retained until the next
67937 ** invocation of this opcode.
67939 ** See also: AggStep and AggFinal
67941 case OP_Function: {
67942 int i;
67943 Mem *pArg;
67944 sqlite3_context ctx;
67945 sqlite3_value **apVal;
67946 int n;
67948 n = pOp->p5;
67949 apVal = p->apArg;
67950 assert( apVal || n==0 );
67951 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
67952 pOut = &aMem[pOp->p3];
67953 memAboutToChange(p, pOut);
67955 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
67956 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
67957 pArg = &aMem[pOp->p2];
67958 for(i=0; i<n; i++, pArg++){
67959 assert( memIsValid(pArg) );
67960 apVal[i] = pArg;
67961 Deephemeralize(pArg);
67962 sqlite3VdbeMemStoreType(pArg);
67963 REGISTER_TRACE(pOp->p2+i, pArg);
67966 assert( pOp->p4type==P4_FUNCDEF );
67967 ctx.pFunc = pOp->p4.pFunc;
67968 ctx.iOp = pc;
67969 ctx.pVdbe = p;
67971 /* The output cell may already have a buffer allocated. Move
67972 ** the pointer to ctx.s so in case the user-function can use
67973 ** the already allocated buffer instead of allocating a new one.
67975 memcpy(&ctx.s, pOut, sizeof(Mem));
67976 pOut->flags = MEM_Null;
67977 pOut->xDel = 0;
67978 pOut->zMalloc = 0;
67979 MemSetTypeFlag(&ctx.s, MEM_Null);
67981 ctx.fErrorOrAux = 0;
67982 if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
67983 assert( pOp>aOp );
67984 assert( pOp[-1].p4type==P4_COLLSEQ );
67985 assert( pOp[-1].opcode==OP_CollSeq );
67986 ctx.pColl = pOp[-1].p4.pColl;
67988 db->lastRowid = lastRowid;
67989 (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
67990 lastRowid = db->lastRowid;
67992 if( db->mallocFailed ){
67993 /* Even though a malloc() has failed, the implementation of the
67994 ** user function may have called an sqlite3_result_XXX() function
67995 ** to return a value. The following call releases any resources
67996 ** associated with such a value.
67998 sqlite3VdbeMemRelease(&ctx.s);
67999 goto no_mem;
68002 /* If the function returned an error, throw an exception */
68003 if( ctx.fErrorOrAux ){
68004 if( ctx.isError ){
68005 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
68006 rc = ctx.isError;
68008 sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
68011 /* Copy the result of the function into register P3 */
68012 sqlite3VdbeChangeEncoding(&ctx.s, encoding);
68013 assert( pOut->flags==MEM_Null );
68014 memcpy(pOut, &ctx.s, sizeof(Mem));
68015 if( sqlite3VdbeMemTooBig(pOut) ){
68016 goto too_big;
68019 #if 0
68020 /* The app-defined function has done something that as caused this
68021 ** statement to expire. (Perhaps the function called sqlite3_exec()
68022 ** with a CREATE TABLE statement.)
68024 if( p->expired ) rc = SQLITE_ABORT;
68025 #endif
68027 REGISTER_TRACE(pOp->p3, pOut);
68028 UPDATE_MAX_BLOBSIZE(pOut);
68029 break;
68032 /* Opcode: BitAnd P1 P2 P3 * *
68033 ** Synopsis: r[P3]=r[P1]&r[P2]
68035 ** Take the bit-wise AND of the values in register P1 and P2 and
68036 ** store the result in register P3.
68037 ** If either input is NULL, the result is NULL.
68039 /* Opcode: BitOr P1 P2 P3 * *
68040 ** Synopsis: r[P3]=r[P1]|r[P2]
68042 ** Take the bit-wise OR of the values in register P1 and P2 and
68043 ** store the result in register P3.
68044 ** If either input is NULL, the result is NULL.
68046 /* Opcode: ShiftLeft P1 P2 P3 * *
68047 ** Synopsis: r[P3]=r[P2]<<r[P1]
68049 ** Shift the integer value in register P2 to the left by the
68050 ** number of bits specified by the integer in register P1.
68051 ** Store the result in register P3.
68052 ** If either input is NULL, the result is NULL.
68054 /* Opcode: ShiftRight P1 P2 P3 * *
68055 ** Synopsis: r[P3]=r[P2]>>r[P1]
68057 ** Shift the integer value in register P2 to the right by the
68058 ** number of bits specified by the integer in register P1.
68059 ** Store the result in register P3.
68060 ** If either input is NULL, the result is NULL.
68062 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
68063 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
68064 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
68065 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
68066 i64 iA;
68067 u64 uA;
68068 i64 iB;
68069 u8 op;
68071 pIn1 = &aMem[pOp->p1];
68072 pIn2 = &aMem[pOp->p2];
68073 pOut = &aMem[pOp->p3];
68074 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
68075 sqlite3VdbeMemSetNull(pOut);
68076 break;
68078 iA = sqlite3VdbeIntValue(pIn2);
68079 iB = sqlite3VdbeIntValue(pIn1);
68080 op = pOp->opcode;
68081 if( op==OP_BitAnd ){
68082 iA &= iB;
68083 }else if( op==OP_BitOr ){
68084 iA |= iB;
68085 }else if( iB!=0 ){
68086 assert( op==OP_ShiftRight || op==OP_ShiftLeft );
68088 /* If shifting by a negative amount, shift in the other direction */
68089 if( iB<0 ){
68090 assert( OP_ShiftRight==OP_ShiftLeft+1 );
68091 op = 2*OP_ShiftLeft + 1 - op;
68092 iB = iB>(-64) ? -iB : 64;
68095 if( iB>=64 ){
68096 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
68097 }else{
68098 memcpy(&uA, &iA, sizeof(uA));
68099 if( op==OP_ShiftLeft ){
68100 uA <<= iB;
68101 }else{
68102 uA >>= iB;
68103 /* Sign-extend on a right shift of a negative number */
68104 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
68106 memcpy(&iA, &uA, sizeof(iA));
68109 pOut->u.i = iA;
68110 MemSetTypeFlag(pOut, MEM_Int);
68111 break;
68114 /* Opcode: AddImm P1 P2 * * *
68115 ** Synopsis: r[P1]=r[P1]+P2
68117 ** Add the constant P2 to the value in register P1.
68118 ** The result is always an integer.
68120 ** To force any register to be an integer, just add 0.
68122 case OP_AddImm: { /* in1 */
68123 pIn1 = &aMem[pOp->p1];
68124 memAboutToChange(p, pIn1);
68125 sqlite3VdbeMemIntegerify(pIn1);
68126 pIn1->u.i += pOp->p2;
68127 break;
68130 /* Opcode: MustBeInt P1 P2 * * *
68132 ** Force the value in register P1 to be an integer. If the value
68133 ** in P1 is not an integer and cannot be converted into an integer
68134 ** without data loss, then jump immediately to P2, or if P2==0
68135 ** raise an SQLITE_MISMATCH exception.
68137 case OP_MustBeInt: { /* jump, in1 */
68138 pIn1 = &aMem[pOp->p1];
68139 if( (pIn1->flags & MEM_Int)==0 ){
68140 applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
68141 if( (pIn1->flags & MEM_Int)==0 ){
68142 if( pOp->p2==0 ){
68143 rc = SQLITE_MISMATCH;
68144 goto abort_due_to_error;
68145 }else{
68146 pc = pOp->p2 - 1;
68147 break;
68151 MemSetTypeFlag(pIn1, MEM_Int);
68152 break;
68155 #ifndef SQLITE_OMIT_FLOATING_POINT
68156 /* Opcode: RealAffinity P1 * * * *
68158 ** If register P1 holds an integer convert it to a real value.
68160 ** This opcode is used when extracting information from a column that
68161 ** has REAL affinity. Such column values may still be stored as
68162 ** integers, for space efficiency, but after extraction we want them
68163 ** to have only a real value.
68165 case OP_RealAffinity: { /* in1 */
68166 pIn1 = &aMem[pOp->p1];
68167 if( pIn1->flags & MEM_Int ){
68168 sqlite3VdbeMemRealify(pIn1);
68170 break;
68172 #endif
68174 #ifndef SQLITE_OMIT_CAST
68175 /* Opcode: ToText P1 * * * *
68177 ** Force the value in register P1 to be text.
68178 ** If the value is numeric, convert it to a string using the
68179 ** equivalent of printf(). Blob values are unchanged and
68180 ** are afterwards simply interpreted as text.
68182 ** A NULL value is not changed by this routine. It remains NULL.
68184 case OP_ToText: { /* same as TK_TO_TEXT, in1 */
68185 pIn1 = &aMem[pOp->p1];
68186 memAboutToChange(p, pIn1);
68187 if( pIn1->flags & MEM_Null ) break;
68188 assert( MEM_Str==(MEM_Blob>>3) );
68189 pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
68190 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
68191 rc = ExpandBlob(pIn1);
68192 assert( pIn1->flags & MEM_Str || db->mallocFailed );
68193 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
68194 UPDATE_MAX_BLOBSIZE(pIn1);
68195 break;
68198 /* Opcode: ToBlob P1 * * * *
68200 ** Force the value in register P1 to be a BLOB.
68201 ** If the value is numeric, convert it to a string first.
68202 ** Strings are simply reinterpreted as blobs with no change
68203 ** to the underlying data.
68205 ** A NULL value is not changed by this routine. It remains NULL.
68207 case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
68208 pIn1 = &aMem[pOp->p1];
68209 if( pIn1->flags & MEM_Null ) break;
68210 if( (pIn1->flags & MEM_Blob)==0 ){
68211 applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
68212 assert( pIn1->flags & MEM_Str || db->mallocFailed );
68213 MemSetTypeFlag(pIn1, MEM_Blob);
68214 }else{
68215 pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
68217 UPDATE_MAX_BLOBSIZE(pIn1);
68218 break;
68221 /* Opcode: ToNumeric P1 * * * *
68223 ** Force the value in register P1 to be numeric (either an
68224 ** integer or a floating-point number.)
68225 ** If the value is text or blob, try to convert it to an using the
68226 ** equivalent of atoi() or atof() and store 0 if no such conversion
68227 ** is possible.
68229 ** A NULL value is not changed by this routine. It remains NULL.
68231 case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
68232 pIn1 = &aMem[pOp->p1];
68233 sqlite3VdbeMemNumerify(pIn1);
68234 break;
68236 #endif /* SQLITE_OMIT_CAST */
68238 /* Opcode: ToInt P1 * * * *
68240 ** Force the value in register P1 to be an integer. If
68241 ** The value is currently a real number, drop its fractional part.
68242 ** If the value is text or blob, try to convert it to an integer using the
68243 ** equivalent of atoi() and store 0 if no such conversion is possible.
68245 ** A NULL value is not changed by this routine. It remains NULL.
68247 case OP_ToInt: { /* same as TK_TO_INT, in1 */
68248 pIn1 = &aMem[pOp->p1];
68249 if( (pIn1->flags & MEM_Null)==0 ){
68250 sqlite3VdbeMemIntegerify(pIn1);
68252 break;
68255 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
68256 /* Opcode: ToReal P1 * * * *
68258 ** Force the value in register P1 to be a floating point number.
68259 ** If The value is currently an integer, convert it.
68260 ** If the value is text or blob, try to convert it to an integer using the
68261 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
68263 ** A NULL value is not changed by this routine. It remains NULL.
68265 case OP_ToReal: { /* same as TK_TO_REAL, in1 */
68266 pIn1 = &aMem[pOp->p1];
68267 memAboutToChange(p, pIn1);
68268 if( (pIn1->flags & MEM_Null)==0 ){
68269 sqlite3VdbeMemRealify(pIn1);
68271 break;
68273 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
68275 /* Opcode: Lt P1 P2 P3 P4 P5
68276 ** Synopsis: if r[P1]<r[P3] goto P2
68278 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
68279 ** jump to address P2.
68281 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
68282 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
68283 ** bit is clear then fall through if either operand is NULL.
68285 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
68286 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
68287 ** to coerce both inputs according to this affinity before the
68288 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
68289 ** affinity is used. Note that the affinity conversions are stored
68290 ** back into the input registers P1 and P3. So this opcode can cause
68291 ** persistent changes to registers P1 and P3.
68293 ** Once any conversions have taken place, and neither value is NULL,
68294 ** the values are compared. If both values are blobs then memcmp() is
68295 ** used to determine the results of the comparison. If both values
68296 ** are text, then the appropriate collating function specified in
68297 ** P4 is used to do the comparison. If P4 is not specified then
68298 ** memcmp() is used to compare text string. If both values are
68299 ** numeric, then a numeric comparison is used. If the two values
68300 ** are of different types, then numbers are considered less than
68301 ** strings and strings are considered less than blobs.
68303 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
68304 ** store a boolean result (either 0, or 1, or NULL) in register P2.
68306 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
68307 ** equal to one another, provided that they do not have their MEM_Cleared
68308 ** bit set.
68310 /* Opcode: Ne P1 P2 P3 P4 P5
68311 ** Synopsis: if r[P1]!=r[P3] goto P2
68313 ** This works just like the Lt opcode except that the jump is taken if
68314 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
68315 ** additional information.
68317 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
68318 ** true or false and is never NULL. If both operands are NULL then the result
68319 ** of comparison is false. If either operand is NULL then the result is true.
68320 ** If neither operand is NULL the result is the same as it would be if
68321 ** the SQLITE_NULLEQ flag were omitted from P5.
68323 /* Opcode: Eq P1 P2 P3 P4 P5
68324 ** Synopsis: if r[P1]==r[P3] goto P2
68326 ** This works just like the Lt opcode except that the jump is taken if
68327 ** the operands in registers P1 and P3 are equal.
68328 ** See the Lt opcode for additional information.
68330 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
68331 ** true or false and is never NULL. If both operands are NULL then the result
68332 ** of comparison is true. If either operand is NULL then the result is false.
68333 ** If neither operand is NULL the result is the same as it would be if
68334 ** the SQLITE_NULLEQ flag were omitted from P5.
68336 /* Opcode: Le P1 P2 P3 P4 P5
68337 ** Synopsis: if r[P1]<=r[P3] goto P2
68339 ** This works just like the Lt opcode except that the jump is taken if
68340 ** the content of register P3 is less than or equal to the content of
68341 ** register P1. See the Lt opcode for additional information.
68343 /* Opcode: Gt P1 P2 P3 P4 P5
68344 ** Synopsis: if r[P1]>r[P3] goto P2
68346 ** This works just like the Lt opcode except that the jump is taken if
68347 ** the content of register P3 is greater than the content of
68348 ** register P1. See the Lt opcode for additional information.
68350 /* Opcode: Ge P1 P2 P3 P4 P5
68351 ** Synopsis: if r[P1]>=r[P3] goto P2
68353 ** This works just like the Lt opcode except that the jump is taken if
68354 ** the content of register P3 is greater than or equal to the content of
68355 ** register P1. See the Lt opcode for additional information.
68357 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
68358 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
68359 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
68360 case OP_Le: /* same as TK_LE, jump, in1, in3 */
68361 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
68362 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
68363 int res; /* Result of the comparison of pIn1 against pIn3 */
68364 char affinity; /* Affinity to use for comparison */
68365 u16 flags1; /* Copy of initial value of pIn1->flags */
68366 u16 flags3; /* Copy of initial value of pIn3->flags */
68368 pIn1 = &aMem[pOp->p1];
68369 pIn3 = &aMem[pOp->p3];
68370 flags1 = pIn1->flags;
68371 flags3 = pIn3->flags;
68372 if( (flags1 | flags3)&MEM_Null ){
68373 /* One or both operands are NULL */
68374 if( pOp->p5 & SQLITE_NULLEQ ){
68375 /* If SQLITE_NULLEQ is set (which will only happen if the operator is
68376 ** OP_Eq or OP_Ne) then take the jump or not depending on whether
68377 ** or not both operands are null.
68379 assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
68380 assert( (flags1 & MEM_Cleared)==0 );
68381 if( (flags1&MEM_Null)!=0
68382 && (flags3&MEM_Null)!=0
68383 && (flags3&MEM_Cleared)==0
68385 res = 0; /* Results are equal */
68386 }else{
68387 res = 1; /* Results are not equal */
68389 }else{
68390 /* SQLITE_NULLEQ is clear and at least one operand is NULL,
68391 ** then the result is always NULL.
68392 ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
68394 if( pOp->p5 & SQLITE_JUMPIFNULL ){
68395 pc = pOp->p2-1;
68396 }else if( pOp->p5 & SQLITE_STOREP2 ){
68397 pOut = &aMem[pOp->p2];
68398 MemSetTypeFlag(pOut, MEM_Null);
68399 REGISTER_TRACE(pOp->p2, pOut);
68401 break;
68403 }else{
68404 /* Neither operand is NULL. Do a comparison. */
68405 affinity = pOp->p5 & SQLITE_AFF_MASK;
68406 if( affinity ){
68407 applyAffinity(pIn1, affinity, encoding);
68408 applyAffinity(pIn3, affinity, encoding);
68409 if( db->mallocFailed ) goto no_mem;
68412 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
68413 ExpandBlob(pIn1);
68414 ExpandBlob(pIn3);
68415 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
68417 switch( pOp->opcode ){
68418 case OP_Eq: res = res==0; break;
68419 case OP_Ne: res = res!=0; break;
68420 case OP_Lt: res = res<0; break;
68421 case OP_Le: res = res<=0; break;
68422 case OP_Gt: res = res>0; break;
68423 default: res = res>=0; break;
68426 if( pOp->p5 & SQLITE_STOREP2 ){
68427 pOut = &aMem[pOp->p2];
68428 memAboutToChange(p, pOut);
68429 MemSetTypeFlag(pOut, MEM_Int);
68430 pOut->u.i = res;
68431 REGISTER_TRACE(pOp->p2, pOut);
68432 }else if( res ){
68433 pc = pOp->p2-1;
68436 /* Undo any changes made by applyAffinity() to the input registers. */
68437 pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
68438 pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
68439 break;
68442 /* Opcode: Permutation * * * P4 *
68444 ** Set the permutation used by the OP_Compare operator to be the array
68445 ** of integers in P4.
68447 ** The permutation is only valid until the next OP_Compare that has
68448 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
68449 ** occur immediately prior to the OP_Compare.
68451 case OP_Permutation: {
68452 assert( pOp->p4type==P4_INTARRAY );
68453 assert( pOp->p4.ai );
68454 aPermute = pOp->p4.ai;
68455 break;
68458 /* Opcode: Compare P1 P2 P3 P4 P5
68460 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
68461 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
68462 ** the comparison for use by the next OP_Jump instruct.
68464 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
68465 ** determined by the most recent OP_Permutation operator. If the
68466 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
68467 ** order.
68469 ** P4 is a KeyInfo structure that defines collating sequences and sort
68470 ** orders for the comparison. The permutation applies to registers
68471 ** only. The KeyInfo elements are used sequentially.
68473 ** The comparison is a sort comparison, so NULLs compare equal,
68474 ** NULLs are less than numbers, numbers are less than strings,
68475 ** and strings are less than blobs.
68477 case OP_Compare: {
68478 int n;
68479 int i;
68480 int p1;
68481 int p2;
68482 const KeyInfo *pKeyInfo;
68483 int idx;
68484 CollSeq *pColl; /* Collating sequence to use on this term */
68485 int bRev; /* True for DESCENDING sort order */
68487 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
68488 n = pOp->p3;
68489 pKeyInfo = pOp->p4.pKeyInfo;
68490 assert( n>0 );
68491 assert( pKeyInfo!=0 );
68492 p1 = pOp->p1;
68493 p2 = pOp->p2;
68494 #if SQLITE_DEBUG
68495 if( aPermute ){
68496 int k, mx = 0;
68497 for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
68498 assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
68499 assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
68500 }else{
68501 assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
68502 assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
68504 #endif /* SQLITE_DEBUG */
68505 for(i=0; i<n; i++){
68506 idx = aPermute ? aPermute[i] : i;
68507 assert( memIsValid(&aMem[p1+idx]) );
68508 assert( memIsValid(&aMem[p2+idx]) );
68509 REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
68510 REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
68511 assert( i<pKeyInfo->nField );
68512 pColl = pKeyInfo->aColl[i];
68513 bRev = pKeyInfo->aSortOrder[i];
68514 iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
68515 if( iCompare ){
68516 if( bRev ) iCompare = -iCompare;
68517 break;
68520 aPermute = 0;
68521 break;
68524 /* Opcode: Jump P1 P2 P3 * *
68526 ** Jump to the instruction at address P1, P2, or P3 depending on whether
68527 ** in the most recent OP_Compare instruction the P1 vector was less than
68528 ** equal to, or greater than the P2 vector, respectively.
68530 case OP_Jump: { /* jump */
68531 if( iCompare<0 ){
68532 pc = pOp->p1 - 1;
68533 }else if( iCompare==0 ){
68534 pc = pOp->p2 - 1;
68535 }else{
68536 pc = pOp->p3 - 1;
68538 break;
68541 /* Opcode: And P1 P2 P3 * *
68542 ** Synopsis: r[P3]=(r[P1] && r[P2])
68544 ** Take the logical AND of the values in registers P1 and P2 and
68545 ** write the result into register P3.
68547 ** If either P1 or P2 is 0 (false) then the result is 0 even if
68548 ** the other input is NULL. A NULL and true or two NULLs give
68549 ** a NULL output.
68551 /* Opcode: Or P1 P2 P3 * *
68552 ** Synopsis: r[P3]=(r[P1] || r[P2])
68554 ** Take the logical OR of the values in register P1 and P2 and
68555 ** store the answer in register P3.
68557 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
68558 ** even if the other input is NULL. A NULL and false or two NULLs
68559 ** give a NULL output.
68561 case OP_And: /* same as TK_AND, in1, in2, out3 */
68562 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
68563 int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
68564 int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
68566 pIn1 = &aMem[pOp->p1];
68567 if( pIn1->flags & MEM_Null ){
68568 v1 = 2;
68569 }else{
68570 v1 = sqlite3VdbeIntValue(pIn1)!=0;
68572 pIn2 = &aMem[pOp->p2];
68573 if( pIn2->flags & MEM_Null ){
68574 v2 = 2;
68575 }else{
68576 v2 = sqlite3VdbeIntValue(pIn2)!=0;
68578 if( pOp->opcode==OP_And ){
68579 static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
68580 v1 = and_logic[v1*3+v2];
68581 }else{
68582 static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
68583 v1 = or_logic[v1*3+v2];
68585 pOut = &aMem[pOp->p3];
68586 if( v1==2 ){
68587 MemSetTypeFlag(pOut, MEM_Null);
68588 }else{
68589 pOut->u.i = v1;
68590 MemSetTypeFlag(pOut, MEM_Int);
68592 break;
68595 /* Opcode: Not P1 P2 * * *
68596 ** Synopsis: r[P2]= !r[P1]
68598 ** Interpret the value in register P1 as a boolean value. Store the
68599 ** boolean complement in register P2. If the value in register P1 is
68600 ** NULL, then a NULL is stored in P2.
68602 case OP_Not: { /* same as TK_NOT, in1, out2 */
68603 pIn1 = &aMem[pOp->p1];
68604 pOut = &aMem[pOp->p2];
68605 if( pIn1->flags & MEM_Null ){
68606 sqlite3VdbeMemSetNull(pOut);
68607 }else{
68608 sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
68610 break;
68613 /* Opcode: BitNot P1 P2 * * *
68614 ** Synopsis: r[P1]= ~r[P1]
68616 ** Interpret the content of register P1 as an integer. Store the
68617 ** ones-complement of the P1 value into register P2. If P1 holds
68618 ** a NULL then store a NULL in P2.
68620 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
68621 pIn1 = &aMem[pOp->p1];
68622 pOut = &aMem[pOp->p2];
68623 if( pIn1->flags & MEM_Null ){
68624 sqlite3VdbeMemSetNull(pOut);
68625 }else{
68626 sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
68628 break;
68631 /* Opcode: Once P1 P2 * * *
68633 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
68634 ** set the flag and fall through to the next instruction.
68636 case OP_Once: { /* jump */
68637 assert( pOp->p1<p->nOnceFlag );
68638 if( p->aOnceFlag[pOp->p1] ){
68639 pc = pOp->p2-1;
68640 }else{
68641 p->aOnceFlag[pOp->p1] = 1;
68643 break;
68646 /* Opcode: If P1 P2 P3 * *
68648 ** Jump to P2 if the value in register P1 is true. The value
68649 ** is considered true if it is numeric and non-zero. If the value
68650 ** in P1 is NULL then take the jump if P3 is non-zero.
68652 /* Opcode: IfNot P1 P2 P3 * *
68654 ** Jump to P2 if the value in register P1 is False. The value
68655 ** is considered false if it has a numeric value of zero. If the value
68656 ** in P1 is NULL then take the jump if P3 is zero.
68658 case OP_If: /* jump, in1 */
68659 case OP_IfNot: { /* jump, in1 */
68660 int c;
68661 pIn1 = &aMem[pOp->p1];
68662 if( pIn1->flags & MEM_Null ){
68663 c = pOp->p3;
68664 }else{
68665 #ifdef SQLITE_OMIT_FLOATING_POINT
68666 c = sqlite3VdbeIntValue(pIn1)!=0;
68667 #else
68668 c = sqlite3VdbeRealValue(pIn1)!=0.0;
68669 #endif
68670 if( pOp->opcode==OP_IfNot ) c = !c;
68672 if( c ){
68673 pc = pOp->p2-1;
68675 break;
68678 /* Opcode: IsNull P1 P2 * * *
68679 ** Synopsis: if r[P1]==NULL goto P2
68681 ** Jump to P2 if the value in register P1 is NULL.
68683 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
68684 pIn1 = &aMem[pOp->p1];
68685 if( (pIn1->flags & MEM_Null)!=0 ){
68686 pc = pOp->p2 - 1;
68688 break;
68691 /* Opcode: NotNull P1 P2 * * *
68692 ** Synopsis: if r[P1]!=NULL goto P2
68694 ** Jump to P2 if the value in register P1 is not NULL.
68696 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
68697 pIn1 = &aMem[pOp->p1];
68698 if( (pIn1->flags & MEM_Null)==0 ){
68699 pc = pOp->p2 - 1;
68701 break;
68704 /* Opcode: Column P1 P2 P3 P4 P5
68705 ** Synopsis: r[P3]=PX
68707 ** Interpret the data that cursor P1 points to as a structure built using
68708 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
68709 ** information about the format of the data.) Extract the P2-th column
68710 ** from this record. If there are less that (P2+1)
68711 ** values in the record, extract a NULL.
68713 ** The value extracted is stored in register P3.
68715 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
68716 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
68717 ** the result.
68719 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
68720 ** then the cache of the cursor is reset prior to extracting the column.
68721 ** The first OP_Column against a pseudo-table after the value of the content
68722 ** register has changed should have this bit set.
68724 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
68725 ** the result is guaranteed to only be used as the argument of a length()
68726 ** or typeof() function, respectively. The loading of large blobs can be
68727 ** skipped for length() and all content loading can be skipped for typeof().
68729 case OP_Column: {
68730 i64 payloadSize64; /* Number of bytes in the record */
68731 int p2; /* column number to retrieve */
68732 VdbeCursor *pC; /* The VDBE cursor */
68733 BtCursor *pCrsr; /* The BTree cursor */
68734 u32 *aType; /* aType[i] holds the numeric type of the i-th column */
68735 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
68736 int len; /* The length of the serialized data for the column */
68737 int i; /* Loop counter */
68738 Mem *pDest; /* Where to write the extracted value */
68739 Mem sMem; /* For storing the record being decoded */
68740 const u8 *zData; /* Part of the record being decoded */
68741 const u8 *zHdr; /* Next unparsed byte of the header */
68742 const u8 *zEndHdr; /* Pointer to first byte after the header */
68743 u32 offset; /* Offset into the data */
68744 u32 szField; /* Number of bytes in the content of a field */
68745 u32 avail; /* Number of bytes of available data */
68746 u32 t; /* A type code from the record header */
68747 Mem *pReg; /* PseudoTable input register */
68749 p2 = pOp->p2;
68750 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
68751 pDest = &aMem[pOp->p3];
68752 memAboutToChange(p, pDest);
68753 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68754 pC = p->apCsr[pOp->p1];
68755 assert( pC!=0 );
68756 assert( p2<pC->nField );
68757 aType = pC->aType;
68758 aOffset = aType + pC->nField;
68759 #ifndef SQLITE_OMIT_VIRTUALTABLE
68760 assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
68761 #endif
68762 pCrsr = pC->pCursor;
68763 assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
68764 assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
68766 /* If the cursor cache is stale, bring it up-to-date */
68767 rc = sqlite3VdbeCursorMoveto(pC);
68768 if( rc ) goto abort_due_to_error;
68769 if( pC->cacheStatus!=p->cacheCtr || (pOp->p5&OPFLAG_CLEARCACHE)!=0 ){
68770 if( pC->nullRow ){
68771 if( pCrsr==0 ){
68772 assert( pC->pseudoTableReg>0 );
68773 pReg = &aMem[pC->pseudoTableReg];
68774 if( pC->multiPseudo ){
68775 sqlite3VdbeMemShallowCopy(pDest, pReg+p2, MEM_Ephem);
68776 Deephemeralize(pDest);
68777 goto op_column_out;
68779 assert( pReg->flags & MEM_Blob );
68780 assert( memIsValid(pReg) );
68781 pC->payloadSize = pC->szRow = avail = pReg->n;
68782 pC->aRow = (u8*)pReg->z;
68783 }else{
68784 MemSetTypeFlag(pDest, MEM_Null);
68785 goto op_column_out;
68787 }else{
68788 assert( pCrsr );
68789 if( pC->isTable==0 ){
68790 assert( sqlite3BtreeCursorIsValid(pCrsr) );
68791 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
68792 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
68793 /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
68794 ** payload size, so it is impossible for payloadSize64 to be
68795 ** larger than 32 bits. */
68796 assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
68797 pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
68798 pC->payloadSize = (u32)payloadSize64;
68799 }else{
68800 assert( sqlite3BtreeCursorIsValid(pCrsr) );
68801 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
68802 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
68803 pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
68805 assert( avail<=65536 ); /* Maximum page size is 64KiB */
68806 if( pC->payloadSize <= (u32)avail ){
68807 pC->szRow = pC->payloadSize;
68808 }else{
68809 pC->szRow = avail;
68811 if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
68812 goto too_big;
68815 pC->cacheStatus = p->cacheCtr;
68816 pC->iHdrOffset = getVarint32(pC->aRow, offset);
68817 pC->nHdrParsed = 0;
68818 aOffset[0] = offset;
68819 if( avail<offset ){
68820 /* pC->aRow does not have to hold the entire row, but it does at least
68821 ** need to cover the header of the record. If pC->aRow does not contain
68822 ** the complete header, then set it to zero, forcing the header to be
68823 ** dynamically allocated. */
68824 pC->aRow = 0;
68825 pC->szRow = 0;
68828 /* Make sure a corrupt database has not given us an oversize header.
68829 ** Do this now to avoid an oversize memory allocation.
68831 ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
68832 ** types use so much data space that there can only be 4096 and 32 of
68833 ** them, respectively. So the maximum header length results from a
68834 ** 3-byte type for each of the maximum of 32768 columns plus three
68835 ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
68837 if( offset > 98307 || offset > pC->payloadSize ){
68838 rc = SQLITE_CORRUPT_BKPT;
68839 goto op_column_error;
68843 /* Make sure at least the first p2+1 entries of the header have been
68844 ** parsed and valid information is in aOffset[] and aType[].
68846 if( pC->nHdrParsed<=p2 ){
68847 /* If there is more header available for parsing in the record, try
68848 ** to extract additional fields up through the p2+1-th field
68850 if( pC->iHdrOffset<aOffset[0] ){
68851 /* Make sure zData points to enough of the record to cover the header. */
68852 if( pC->aRow==0 ){
68853 memset(&sMem, 0, sizeof(sMem));
68854 rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
68855 !pC->isTable, &sMem);
68856 if( rc!=SQLITE_OK ){
68857 goto op_column_error;
68859 zData = (u8*)sMem.z;
68860 }else{
68861 zData = pC->aRow;
68864 /* Fill in aType[i] and aOffset[i] values through the p2-th field. */
68865 i = pC->nHdrParsed;
68866 offset = aOffset[i];
68867 zHdr = zData + pC->iHdrOffset;
68868 zEndHdr = zData + aOffset[0];
68869 assert( i<=p2 && zHdr<zEndHdr );
68871 if( zHdr[0]<0x80 ){
68872 t = zHdr[0];
68873 zHdr++;
68874 }else{
68875 zHdr += sqlite3GetVarint32(zHdr, &t);
68877 aType[i] = t;
68878 szField = sqlite3VdbeSerialTypeLen(t);
68879 offset += szField;
68880 if( offset<szField ){ /* True if offset overflows */
68881 zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
68882 break;
68884 i++;
68885 aOffset[i] = offset;
68886 }while( i<=p2 && zHdr<zEndHdr );
68887 pC->nHdrParsed = i;
68888 pC->iHdrOffset = (u32)(zHdr - zData);
68889 if( pC->aRow==0 ){
68890 sqlite3VdbeMemRelease(&sMem);
68891 sMem.flags = MEM_Null;
68894 /* If we have read more header data than was contained in the header,
68895 ** or if the end of the last field appears to be past the end of the
68896 ** record, or if the end of the last field appears to be before the end
68897 ** of the record (when all fields present), then we must be dealing
68898 ** with a corrupt database.
68900 if( (zHdr > zEndHdr)
68901 || (offset > pC->payloadSize)
68902 || (zHdr==zEndHdr && offset!=pC->payloadSize)
68904 rc = SQLITE_CORRUPT_BKPT;
68905 goto op_column_error;
68909 /* If after trying to extra new entries from the header, nHdrParsed is
68910 ** still not up to p2, that means that the record has fewer than p2
68911 ** columns. So the result will be either the default value or a NULL.
68913 if( pC->nHdrParsed<=p2 ){
68914 if( pOp->p4type==P4_MEM ){
68915 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
68916 }else{
68917 MemSetTypeFlag(pDest, MEM_Null);
68919 goto op_column_out;
68923 /* Extract the content for the p2+1-th column. Control can only
68924 ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
68925 ** all valid.
68927 assert( p2<pC->nHdrParsed );
68928 assert( rc==SQLITE_OK );
68929 if( pC->szRow>=aOffset[p2+1] ){
68930 /* This is the common case where the desired content fits on the original
68931 ** page - where the content is not on an overflow page */
68932 VdbeMemRelease(pDest);
68933 sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
68934 }else{
68935 /* This branch happens only when content is on overflow pages */
68936 t = aType[p2];
68937 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
68938 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
68939 || (len = sqlite3VdbeSerialTypeLen(t))==0
68941 /* Content is irrelevant for the typeof() function and for
68942 ** the length(X) function if X is a blob. So we might as well use
68943 ** bogus content rather than reading content from disk. NULL works
68944 ** for text and blob and whatever is in the payloadSize64 variable
68945 ** will work for everything else. Content is also irrelevant if
68946 ** the content length is 0. */
68947 zData = t<=13 ? (u8*)&payloadSize64 : 0;
68948 sMem.zMalloc = 0;
68949 }else{
68950 memset(&sMem, 0, sizeof(sMem));
68951 sqlite3VdbeMemMove(&sMem, pDest);
68952 rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
68953 &sMem);
68954 if( rc!=SQLITE_OK ){
68955 goto op_column_error;
68957 zData = (u8*)sMem.z;
68959 sqlite3VdbeSerialGet(zData, t, pDest);
68960 /* If we dynamically allocated space to hold the data (in the
68961 ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
68962 ** dynamically allocated space over to the pDest structure.
68963 ** This prevents a memory copy. */
68964 if( sMem.zMalloc ){
68965 assert( sMem.z==sMem.zMalloc );
68966 assert( !(pDest->flags & MEM_Dyn) );
68967 assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
68968 pDest->flags &= ~(MEM_Ephem|MEM_Static);
68969 pDest->flags |= MEM_Term;
68970 pDest->z = sMem.z;
68971 pDest->zMalloc = sMem.zMalloc;
68974 pDest->enc = encoding;
68976 op_column_out:
68977 Deephemeralize(pDest);
68978 op_column_error:
68979 UPDATE_MAX_BLOBSIZE(pDest);
68980 REGISTER_TRACE(pOp->p3, pDest);
68981 break;
68984 /* Opcode: Affinity P1 P2 * P4 *
68985 ** Synopsis: affinity(r[P1@P2])
68987 ** Apply affinities to a range of P2 registers starting with P1.
68989 ** P4 is a string that is P2 characters long. The nth character of the
68990 ** string indicates the column affinity that should be used for the nth
68991 ** memory cell in the range.
68993 case OP_Affinity: {
68994 const char *zAffinity; /* The affinity to be applied */
68995 char cAff; /* A single character of affinity */
68997 zAffinity = pOp->p4.z;
68998 assert( zAffinity!=0 );
68999 assert( zAffinity[pOp->p2]==0 );
69000 pIn1 = &aMem[pOp->p1];
69001 while( (cAff = *(zAffinity++))!=0 ){
69002 assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
69003 assert( memIsValid(pIn1) );
69004 ExpandBlob(pIn1);
69005 applyAffinity(pIn1, cAff, encoding);
69006 pIn1++;
69008 break;
69011 /* Opcode: MakeRecord P1 P2 P3 P4 *
69012 ** Synopsis: r[P3]=mkrec(r[P1@P2])
69014 ** Convert P2 registers beginning with P1 into the [record format]
69015 ** use as a data record in a database table or as a key
69016 ** in an index. The OP_Column opcode can decode the record later.
69018 ** P4 may be a string that is P2 characters long. The nth character of the
69019 ** string indicates the column affinity that should be used for the nth
69020 ** field of the index key.
69022 ** The mapping from character to affinity is given by the SQLITE_AFF_
69023 ** macros defined in sqliteInt.h.
69025 ** If P4 is NULL then all index fields have the affinity NONE.
69027 case OP_MakeRecord: {
69028 u8 *zNewRecord; /* A buffer to hold the data for the new record */
69029 Mem *pRec; /* The new record */
69030 u64 nData; /* Number of bytes of data space */
69031 int nHdr; /* Number of bytes of header space */
69032 i64 nByte; /* Data space required for this record */
69033 int nZero; /* Number of zero bytes at the end of the record */
69034 int nVarint; /* Number of bytes in a varint */
69035 u32 serial_type; /* Type field */
69036 Mem *pData0; /* First field to be combined into the record */
69037 Mem *pLast; /* Last field of the record */
69038 int nField; /* Number of fields in the record */
69039 char *zAffinity; /* The affinity string for the record */
69040 int file_format; /* File format to use for encoding */
69041 int i; /* Space used in zNewRecord[] header */
69042 int j; /* Space used in zNewRecord[] content */
69043 int len; /* Length of a field */
69045 /* Assuming the record contains N fields, the record format looks
69046 ** like this:
69048 ** ------------------------------------------------------------------------
69049 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
69050 ** ------------------------------------------------------------------------
69052 ** Data(0) is taken from register P1. Data(1) comes from register P1+1
69053 ** and so froth.
69055 ** Each type field is a varint representing the serial type of the
69056 ** corresponding data element (see sqlite3VdbeSerialType()). The
69057 ** hdr-size field is also a varint which is the offset from the beginning
69058 ** of the record to data0.
69060 nData = 0; /* Number of bytes of data space */
69061 nHdr = 0; /* Number of bytes of header space */
69062 nZero = 0; /* Number of zero bytes at the end of the record */
69063 nField = pOp->p1;
69064 zAffinity = pOp->p4.z;
69065 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
69066 pData0 = &aMem[nField];
69067 nField = pOp->p2;
69068 pLast = &pData0[nField-1];
69069 file_format = p->minWriteFileFormat;
69071 /* Identify the output register */
69072 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
69073 pOut = &aMem[pOp->p3];
69074 memAboutToChange(p, pOut);
69076 /* Apply the requested affinity to all inputs
69078 assert( pData0<=pLast );
69079 if( zAffinity ){
69080 pRec = pData0;
69082 applyAffinity(pRec, *(zAffinity++), encoding);
69083 }while( (++pRec)<=pLast );
69086 /* Loop through the elements that will make up the record to figure
69087 ** out how much space is required for the new record.
69089 pRec = pLast;
69091 assert( memIsValid(pRec) );
69092 serial_type = sqlite3VdbeSerialType(pRec, file_format);
69093 len = sqlite3VdbeSerialTypeLen(serial_type);
69094 if( pRec->flags & MEM_Zero ){
69095 if( nData ){
69096 sqlite3VdbeMemExpandBlob(pRec);
69097 }else{
69098 nZero += pRec->u.nZero;
69099 len -= pRec->u.nZero;
69102 nData += len;
69103 testcase( serial_type==127 );
69104 testcase( serial_type==128 );
69105 nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
69106 }while( (--pRec)>=pData0 );
69108 /* Add the initial header varint and total the size */
69109 testcase( nHdr==126 );
69110 testcase( nHdr==127 );
69111 if( nHdr<=126 ){
69112 /* The common case */
69113 nHdr += 1;
69114 }else{
69115 /* Rare case of a really large header */
69116 nVarint = sqlite3VarintLen(nHdr);
69117 nHdr += nVarint;
69118 if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
69120 nByte = nHdr+nData;
69121 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69122 goto too_big;
69125 /* Make sure the output register has a buffer large enough to store
69126 ** the new record. The output register (pOp->p3) is not allowed to
69127 ** be one of the input registers (because the following call to
69128 ** sqlite3VdbeMemGrow() could clobber the value before it is used).
69130 if( sqlite3VdbeMemGrow(pOut, (int)nByte, 0) ){
69131 goto no_mem;
69133 zNewRecord = (u8 *)pOut->z;
69135 /* Write the record */
69136 i = putVarint32(zNewRecord, nHdr);
69137 j = nHdr;
69138 assert( pData0<=pLast );
69139 pRec = pData0;
69141 serial_type = sqlite3VdbeSerialType(pRec, file_format);
69142 i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
69143 j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
69144 }while( (++pRec)<=pLast );
69145 assert( i==nHdr );
69146 assert( j==nByte );
69148 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
69149 pOut->n = (int)nByte;
69150 pOut->flags = MEM_Blob | MEM_Dyn;
69151 pOut->xDel = 0;
69152 if( nZero ){
69153 pOut->u.nZero = nZero;
69154 pOut->flags |= MEM_Zero;
69156 pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
69157 REGISTER_TRACE(pOp->p3, pOut);
69158 UPDATE_MAX_BLOBSIZE(pOut);
69159 break;
69162 /* Opcode: Count P1 P2 * * *
69163 ** Synopsis: r[P2]=count()
69165 ** Store the number of entries (an integer value) in the table or index
69166 ** opened by cursor P1 in register P2
69168 #ifndef SQLITE_OMIT_BTREECOUNT
69169 case OP_Count: { /* out2-prerelease */
69170 i64 nEntry;
69171 BtCursor *pCrsr;
69173 pCrsr = p->apCsr[pOp->p1]->pCursor;
69174 assert( pCrsr );
69175 nEntry = 0; /* Not needed. Only used to silence a warning. */
69176 rc = sqlite3BtreeCount(pCrsr, &nEntry);
69177 pOut->u.i = nEntry;
69178 break;
69180 #endif
69182 /* Opcode: Savepoint P1 * * P4 *
69184 ** Open, release or rollback the savepoint named by parameter P4, depending
69185 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
69186 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
69188 case OP_Savepoint: {
69189 int p1; /* Value of P1 operand */
69190 char *zName; /* Name of savepoint */
69191 int nName;
69192 Savepoint *pNew;
69193 Savepoint *pSavepoint;
69194 Savepoint *pTmp;
69195 int iSavepoint;
69196 int ii;
69198 p1 = pOp->p1;
69199 zName = pOp->p4.z;
69201 /* Assert that the p1 parameter is valid. Also that if there is no open
69202 ** transaction, then there cannot be any savepoints.
69204 assert( db->pSavepoint==0 || db->autoCommit==0 );
69205 assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
69206 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
69207 assert( checkSavepointCount(db) );
69208 assert( p->bIsReader );
69210 if( p1==SAVEPOINT_BEGIN ){
69211 if( db->nVdbeWrite>0 ){
69212 /* A new savepoint cannot be created if there are active write
69213 ** statements (i.e. open read/write incremental blob handles).
69215 sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
69216 "SQL statements in progress");
69217 rc = SQLITE_BUSY;
69218 }else{
69219 nName = sqlite3Strlen30(zName);
69221 #ifndef SQLITE_OMIT_VIRTUALTABLE
69222 /* This call is Ok even if this savepoint is actually a transaction
69223 ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
69224 ** If this is a transaction savepoint being opened, it is guaranteed
69225 ** that the db->aVTrans[] array is empty. */
69226 assert( db->autoCommit==0 || db->nVTrans==0 );
69227 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
69228 db->nStatement+db->nSavepoint);
69229 if( rc!=SQLITE_OK ) goto abort_due_to_error;
69230 #endif
69232 /* Create a new savepoint structure. */
69233 pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
69234 if( pNew ){
69235 pNew->zName = (char *)&pNew[1];
69236 memcpy(pNew->zName, zName, nName+1);
69238 /* If there is no open transaction, then mark this as a special
69239 ** "transaction savepoint". */
69240 if( db->autoCommit ){
69241 db->autoCommit = 0;
69242 db->isTransactionSavepoint = 1;
69243 }else{
69244 db->nSavepoint++;
69247 /* Link the new savepoint into the database handle's list. */
69248 pNew->pNext = db->pSavepoint;
69249 db->pSavepoint = pNew;
69250 pNew->nDeferredCons = db->nDeferredCons;
69251 pNew->nDeferredImmCons = db->nDeferredImmCons;
69254 }else{
69255 iSavepoint = 0;
69257 /* Find the named savepoint. If there is no such savepoint, then an
69258 ** an error is returned to the user. */
69259 for(
69260 pSavepoint = db->pSavepoint;
69261 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
69262 pSavepoint = pSavepoint->pNext
69264 iSavepoint++;
69266 if( !pSavepoint ){
69267 sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
69268 rc = SQLITE_ERROR;
69269 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
69270 /* It is not possible to release (commit) a savepoint if there are
69271 ** active write statements.
69273 sqlite3SetString(&p->zErrMsg, db,
69274 "cannot release savepoint - SQL statements in progress"
69276 rc = SQLITE_BUSY;
69277 }else{
69279 /* Determine whether or not this is a transaction savepoint. If so,
69280 ** and this is a RELEASE command, then the current transaction
69281 ** is committed.
69283 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
69284 if( isTransaction && p1==SAVEPOINT_RELEASE ){
69285 if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
69286 goto vdbe_return;
69288 db->autoCommit = 1;
69289 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
69290 p->pc = pc;
69291 db->autoCommit = 0;
69292 p->rc = rc = SQLITE_BUSY;
69293 goto vdbe_return;
69295 db->isTransactionSavepoint = 0;
69296 rc = p->rc;
69297 }else{
69298 iSavepoint = db->nSavepoint - iSavepoint - 1;
69299 if( p1==SAVEPOINT_ROLLBACK ){
69300 for(ii=0; ii<db->nDb; ii++){
69301 sqlite3BtreeTripAllCursors(db->aDb[ii].pBt, SQLITE_ABORT);
69304 for(ii=0; ii<db->nDb; ii++){
69305 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
69306 if( rc!=SQLITE_OK ){
69307 goto abort_due_to_error;
69310 if( p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
69311 sqlite3ExpirePreparedStatements(db);
69312 sqlite3ResetAllSchemasOfConnection(db);
69313 db->flags = (db->flags | SQLITE_InternChanges);
69317 /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
69318 ** savepoints nested inside of the savepoint being operated on. */
69319 while( db->pSavepoint!=pSavepoint ){
69320 pTmp = db->pSavepoint;
69321 db->pSavepoint = pTmp->pNext;
69322 sqlite3DbFree(db, pTmp);
69323 db->nSavepoint--;
69326 /* If it is a RELEASE, then destroy the savepoint being operated on
69327 ** too. If it is a ROLLBACK TO, then set the number of deferred
69328 ** constraint violations present in the database to the value stored
69329 ** when the savepoint was created. */
69330 if( p1==SAVEPOINT_RELEASE ){
69331 assert( pSavepoint==db->pSavepoint );
69332 db->pSavepoint = pSavepoint->pNext;
69333 sqlite3DbFree(db, pSavepoint);
69334 if( !isTransaction ){
69335 db->nSavepoint--;
69337 }else{
69338 db->nDeferredCons = pSavepoint->nDeferredCons;
69339 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
69342 if( !isTransaction ){
69343 rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
69344 if( rc!=SQLITE_OK ) goto abort_due_to_error;
69349 break;
69352 /* Opcode: AutoCommit P1 P2 * * *
69354 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
69355 ** back any currently active btree transactions. If there are any active
69356 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
69357 ** there are active writing VMs or active VMs that use shared cache.
69359 ** This instruction causes the VM to halt.
69361 case OP_AutoCommit: {
69362 int desiredAutoCommit;
69363 int iRollback;
69364 int turnOnAC;
69366 desiredAutoCommit = pOp->p1;
69367 iRollback = pOp->p2;
69368 turnOnAC = desiredAutoCommit && !db->autoCommit;
69369 assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
69370 assert( desiredAutoCommit==1 || iRollback==0 );
69371 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
69372 assert( p->bIsReader );
69374 #if 0
69375 if( turnOnAC && iRollback && db->nVdbeActive>1 ){
69376 /* If this instruction implements a ROLLBACK and other VMs are
69377 ** still running, and a transaction is active, return an error indicating
69378 ** that the other VMs must complete first.
69380 sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
69381 "SQL statements in progress");
69382 rc = SQLITE_BUSY;
69383 }else
69384 #endif
69385 if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
69386 /* If this instruction implements a COMMIT and other VMs are writing
69387 ** return an error indicating that the other VMs must complete first.
69389 sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
69390 "SQL statements in progress");
69391 rc = SQLITE_BUSY;
69392 }else if( desiredAutoCommit!=db->autoCommit ){
69393 if( iRollback ){
69394 assert( desiredAutoCommit==1 );
69395 sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
69396 db->autoCommit = 1;
69397 }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
69398 goto vdbe_return;
69399 }else{
69400 db->autoCommit = (u8)desiredAutoCommit;
69401 if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
69402 p->pc = pc;
69403 db->autoCommit = (u8)(1-desiredAutoCommit);
69404 p->rc = rc = SQLITE_BUSY;
69405 goto vdbe_return;
69408 assert( db->nStatement==0 );
69409 sqlite3CloseSavepoints(db);
69410 if( p->rc==SQLITE_OK ){
69411 rc = SQLITE_DONE;
69412 }else{
69413 rc = SQLITE_ERROR;
69415 goto vdbe_return;
69416 }else{
69417 sqlite3SetString(&p->zErrMsg, db,
69418 (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
69419 (iRollback)?"cannot rollback - no transaction is active":
69420 "cannot commit - no transaction is active"));
69422 rc = SQLITE_ERROR;
69424 break;
69427 /* Opcode: Transaction P1 P2 * * *
69429 ** Begin a transaction. The transaction ends when a Commit or Rollback
69430 ** opcode is encountered. Depending on the ON CONFLICT setting, the
69431 ** transaction might also be rolled back if an error is encountered.
69433 ** P1 is the index of the database file on which the transaction is
69434 ** started. Index 0 is the main database file and index 1 is the
69435 ** file used for temporary tables. Indices of 2 or more are used for
69436 ** attached databases.
69438 ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
69439 ** obtained on the database file when a write-transaction is started. No
69440 ** other process can start another write transaction while this transaction is
69441 ** underway. Starting a write transaction also creates a rollback journal. A
69442 ** write transaction must be started before any changes can be made to the
69443 ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
69444 ** also obtained on the file.
69446 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
69447 ** true (this flag is set if the Vdbe may modify more than one row and may
69448 ** throw an ABORT exception), a statement transaction may also be opened.
69449 ** More specifically, a statement transaction is opened iff the database
69450 ** connection is currently not in autocommit mode, or if there are other
69451 ** active statements. A statement transaction allows the changes made by this
69452 ** VDBE to be rolled back after an error without having to roll back the
69453 ** entire transaction. If no error is encountered, the statement transaction
69454 ** will automatically commit when the VDBE halts.
69456 ** If P2 is zero, then a read-lock is obtained on the database file.
69458 case OP_Transaction: {
69459 Btree *pBt;
69461 assert( p->bIsReader );
69462 assert( p->readOnly==0 || pOp->p2==0 );
69463 assert( pOp->p1>=0 && pOp->p1<db->nDb );
69464 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69465 if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
69466 rc = SQLITE_READONLY;
69467 goto abort_due_to_error;
69469 pBt = db->aDb[pOp->p1].pBt;
69471 if( pBt ){
69472 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
69473 if( rc==SQLITE_BUSY ){
69474 p->pc = pc;
69475 p->rc = rc = SQLITE_BUSY;
69476 goto vdbe_return;
69478 if( rc!=SQLITE_OK ){
69479 goto abort_due_to_error;
69482 if( pOp->p2 && p->usesStmtJournal
69483 && (db->autoCommit==0 || db->nVdbeRead>1)
69485 assert( sqlite3BtreeIsInTrans(pBt) );
69486 if( p->iStatement==0 ){
69487 assert( db->nStatement>=0 && db->nSavepoint>=0 );
69488 db->nStatement++;
69489 p->iStatement = db->nSavepoint + db->nStatement;
69492 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
69493 if( rc==SQLITE_OK ){
69494 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
69497 /* Store the current value of the database handles deferred constraint
69498 ** counter. If the statement transaction needs to be rolled back,
69499 ** the value of this counter needs to be restored too. */
69500 p->nStmtDefCons = db->nDeferredCons;
69501 p->nStmtDefImmCons = db->nDeferredImmCons;
69504 break;
69507 /* Opcode: ReadCookie P1 P2 P3 * *
69509 ** Read cookie number P3 from database P1 and write it into register P2.
69510 ** P3==1 is the schema version. P3==2 is the database format.
69511 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
69512 ** the main database file and P1==1 is the database file used to store
69513 ** temporary tables.
69515 ** There must be a read-lock on the database (either a transaction
69516 ** must be started or there must be an open cursor) before
69517 ** executing this instruction.
69519 case OP_ReadCookie: { /* out2-prerelease */
69520 int iMeta;
69521 int iDb;
69522 int iCookie;
69524 assert( p->bIsReader );
69525 iDb = pOp->p1;
69526 iCookie = pOp->p3;
69527 assert( pOp->p3<SQLITE_N_BTREE_META );
69528 assert( iDb>=0 && iDb<db->nDb );
69529 assert( db->aDb[iDb].pBt!=0 );
69530 assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
69532 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
69533 pOut->u.i = iMeta;
69534 break;
69537 /* Opcode: SetCookie P1 P2 P3 * *
69539 ** Write the content of register P3 (interpreted as an integer)
69540 ** into cookie number P2 of database P1. P2==1 is the schema version.
69541 ** P2==2 is the database format. P2==3 is the recommended pager cache
69542 ** size, and so forth. P1==0 is the main database file and P1==1 is the
69543 ** database file used to store temporary tables.
69545 ** A transaction must be started before executing this opcode.
69547 case OP_SetCookie: { /* in3 */
69548 Db *pDb;
69549 assert( pOp->p2<SQLITE_N_BTREE_META );
69550 assert( pOp->p1>=0 && pOp->p1<db->nDb );
69551 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69552 assert( p->readOnly==0 );
69553 pDb = &db->aDb[pOp->p1];
69554 assert( pDb->pBt!=0 );
69555 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
69556 pIn3 = &aMem[pOp->p3];
69557 sqlite3VdbeMemIntegerify(pIn3);
69558 /* See note about index shifting on OP_ReadCookie */
69559 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
69560 if( pOp->p2==BTREE_SCHEMA_VERSION ){
69561 /* When the schema cookie changes, record the new cookie internally */
69562 pDb->pSchema->schema_cookie = (int)pIn3->u.i;
69563 db->flags |= SQLITE_InternChanges;
69564 }else if( pOp->p2==BTREE_FILE_FORMAT ){
69565 /* Record changes in the file format */
69566 pDb->pSchema->file_format = (u8)pIn3->u.i;
69568 if( pOp->p1==1 ){
69569 /* Invalidate all prepared statements whenever the TEMP database
69570 ** schema is changed. Ticket #1644 */
69571 sqlite3ExpirePreparedStatements(db);
69572 p->expired = 0;
69574 break;
69577 /* Opcode: VerifyCookie P1 P2 P3 * *
69579 ** Check the value of global database parameter number 0 (the
69580 ** schema version) and make sure it is equal to P2 and that the
69581 ** generation counter on the local schema parse equals P3.
69583 ** P1 is the database number which is 0 for the main database file
69584 ** and 1 for the file holding temporary tables and some higher number
69585 ** for auxiliary databases.
69587 ** The cookie changes its value whenever the database schema changes.
69588 ** This operation is used to detect when that the cookie has changed
69589 ** and that the current process needs to reread the schema.
69591 ** Either a transaction needs to have been started or an OP_Open needs
69592 ** to be executed (to establish a read lock) before this opcode is
69593 ** invoked.
69595 case OP_VerifyCookie: {
69596 int iMeta;
69597 int iGen;
69598 Btree *pBt;
69600 assert( pOp->p1>=0 && pOp->p1<db->nDb );
69601 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69602 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
69603 assert( p->bIsReader );
69604 pBt = db->aDb[pOp->p1].pBt;
69605 if( pBt ){
69606 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
69607 iGen = db->aDb[pOp->p1].pSchema->iGeneration;
69608 }else{
69609 iGen = iMeta = 0;
69611 if( iMeta!=pOp->p2 || iGen!=pOp->p3 ){
69612 sqlite3DbFree(db, p->zErrMsg);
69613 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
69614 /* If the schema-cookie from the database file matches the cookie
69615 ** stored with the in-memory representation of the schema, do
69616 ** not reload the schema from the database file.
69618 ** If virtual-tables are in use, this is not just an optimization.
69619 ** Often, v-tables store their data in other SQLite tables, which
69620 ** are queried from within xNext() and other v-table methods using
69621 ** prepared queries. If such a query is out-of-date, we do not want to
69622 ** discard the database schema, as the user code implementing the
69623 ** v-table would have to be ready for the sqlite3_vtab structure itself
69624 ** to be invalidated whenever sqlite3_step() is called from within
69625 ** a v-table method.
69627 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
69628 sqlite3ResetOneSchema(db, pOp->p1);
69631 p->expired = 1;
69632 rc = SQLITE_SCHEMA;
69634 break;
69637 /* Opcode: OpenRead P1 P2 P3 P4 P5
69638 ** Synopsis: root=P2 iDb=P3
69640 ** Open a read-only cursor for the database table whose root page is
69641 ** P2 in a database file. The database file is determined by P3.
69642 ** P3==0 means the main database, P3==1 means the database used for
69643 ** temporary tables, and P3>1 means used the corresponding attached
69644 ** database. Give the new cursor an identifier of P1. The P1
69645 ** values need not be contiguous but all P1 values should be small integers.
69646 ** It is an error for P1 to be negative.
69648 ** If P5!=0 then use the content of register P2 as the root page, not
69649 ** the value of P2 itself.
69651 ** There will be a read lock on the database whenever there is an
69652 ** open cursor. If the database was unlocked prior to this instruction
69653 ** then a read lock is acquired as part of this instruction. A read
69654 ** lock allows other processes to read the database but prohibits
69655 ** any other process from modifying the database. The read lock is
69656 ** released when all cursors are closed. If this instruction attempts
69657 ** to get a read lock but fails, the script terminates with an
69658 ** SQLITE_BUSY error code.
69660 ** The P4 value may be either an integer (P4_INT32) or a pointer to
69661 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
69662 ** structure, then said structure defines the content and collating
69663 ** sequence of the index being opened. Otherwise, if P4 is an integer
69664 ** value, it is set to the number of columns in the table.
69666 ** See also OpenWrite.
69668 /* Opcode: OpenWrite P1 P2 P3 P4 P5
69669 ** Synopsis: root=P2 iDb=P3
69671 ** Open a read/write cursor named P1 on the table or index whose root
69672 ** page is P2. Or if P5!=0 use the content of register P2 to find the
69673 ** root page.
69675 ** The P4 value may be either an integer (P4_INT32) or a pointer to
69676 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
69677 ** structure, then said structure defines the content and collating
69678 ** sequence of the index being opened. Otherwise, if P4 is an integer
69679 ** value, it is set to the number of columns in the table, or to the
69680 ** largest index of any column of the table that is actually used.
69682 ** This instruction works just like OpenRead except that it opens the cursor
69683 ** in read/write mode. For a given table, there can be one or more read-only
69684 ** cursors or a single read/write cursor but not both.
69686 ** See also OpenRead.
69688 case OP_OpenRead:
69689 case OP_OpenWrite: {
69690 int nField;
69691 KeyInfo *pKeyInfo;
69692 int p2;
69693 int iDb;
69694 int wrFlag;
69695 Btree *pX;
69696 VdbeCursor *pCur;
69697 Db *pDb;
69699 assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
69700 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
69701 assert( p->bIsReader );
69702 assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
69704 if( p->expired ){
69705 rc = SQLITE_ABORT;
69706 break;
69709 nField = 0;
69710 pKeyInfo = 0;
69711 p2 = pOp->p2;
69712 iDb = pOp->p3;
69713 assert( iDb>=0 && iDb<db->nDb );
69714 assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
69715 pDb = &db->aDb[iDb];
69716 pX = pDb->pBt;
69717 assert( pX!=0 );
69718 if( pOp->opcode==OP_OpenWrite ){
69719 wrFlag = 1;
69720 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
69721 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
69722 p->minWriteFileFormat = pDb->pSchema->file_format;
69724 }else{
69725 wrFlag = 0;
69727 if( pOp->p5 & OPFLAG_P2ISREG ){
69728 assert( p2>0 );
69729 assert( p2<=(p->nMem-p->nCursor) );
69730 pIn2 = &aMem[p2];
69731 assert( memIsValid(pIn2) );
69732 assert( (pIn2->flags & MEM_Int)!=0 );
69733 sqlite3VdbeMemIntegerify(pIn2);
69734 p2 = (int)pIn2->u.i;
69735 /* The p2 value always comes from a prior OP_CreateTable opcode and
69736 ** that opcode will always set the p2 value to 2 or more or else fail.
69737 ** If there were a failure, the prepared statement would have halted
69738 ** before reaching this instruction. */
69739 if( NEVER(p2<2) ) {
69740 rc = SQLITE_CORRUPT_BKPT;
69741 goto abort_due_to_error;
69744 if( pOp->p4type==P4_KEYINFO ){
69745 pKeyInfo = pOp->p4.pKeyInfo;
69746 assert( pKeyInfo->enc==ENC(db) );
69747 assert( pKeyInfo->db==db );
69748 nField = pKeyInfo->nField+pKeyInfo->nXField;
69749 }else if( pOp->p4type==P4_INT32 ){
69750 nField = pOp->p4.i;
69752 assert( pOp->p1>=0 );
69753 assert( nField>=0 );
69754 testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
69755 pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
69756 if( pCur==0 ) goto no_mem;
69757 pCur->nullRow = 1;
69758 pCur->isOrdered = 1;
69759 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
69760 pCur->pKeyInfo = pKeyInfo;
69761 assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
69762 sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
69764 /* Since it performs no memory allocation or IO, the only value that
69765 ** sqlite3BtreeCursor() may return is SQLITE_OK. */
69766 assert( rc==SQLITE_OK );
69768 /* Set the VdbeCursor.isTable variable. Previous versions of
69769 ** SQLite used to check if the root-page flags were sane at this point
69770 ** and report database corruption if they were not, but this check has
69771 ** since moved into the btree layer. */
69772 pCur->isTable = pOp->p4type!=P4_KEYINFO;
69773 break;
69776 /* Opcode: OpenEphemeral P1 P2 * P4 P5
69777 ** Synopsis: nColumn=P2
69779 ** Open a new cursor P1 to a transient table.
69780 ** The cursor is always opened read/write even if
69781 ** the main database is read-only. The ephemeral
69782 ** table is deleted automatically when the cursor is closed.
69784 ** P2 is the number of columns in the ephemeral table.
69785 ** The cursor points to a BTree table if P4==0 and to a BTree index
69786 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
69787 ** that defines the format of keys in the index.
69789 ** The P5 parameter can be a mask of the BTREE_* flags defined
69790 ** in btree.h. These flags control aspects of the operation of
69791 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
69792 ** added automatically.
69794 /* Opcode: OpenAutoindex P1 P2 * P4 *
69795 ** Synopsis: nColumn=P2
69797 ** This opcode works the same as OP_OpenEphemeral. It has a
69798 ** different name to distinguish its use. Tables created using
69799 ** by this opcode will be used for automatically created transient
69800 ** indices in joins.
69802 case OP_OpenAutoindex:
69803 case OP_OpenEphemeral: {
69804 VdbeCursor *pCx;
69805 KeyInfo *pKeyInfo;
69807 static const int vfsFlags =
69808 SQLITE_OPEN_READWRITE |
69809 SQLITE_OPEN_CREATE |
69810 SQLITE_OPEN_EXCLUSIVE |
69811 SQLITE_OPEN_DELETEONCLOSE |
69812 SQLITE_OPEN_TRANSIENT_DB;
69813 assert( pOp->p1>=0 );
69814 assert( pOp->p2>=0 );
69815 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
69816 if( pCx==0 ) goto no_mem;
69817 pCx->nullRow = 1;
69818 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
69819 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
69820 if( rc==SQLITE_OK ){
69821 rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
69823 if( rc==SQLITE_OK ){
69824 /* If a transient index is required, create it by calling
69825 ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
69826 ** opening it. If a transient table is required, just use the
69827 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
69829 if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
69830 int pgno;
69831 assert( pOp->p4type==P4_KEYINFO );
69832 rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
69833 if( rc==SQLITE_OK ){
69834 assert( pgno==MASTER_ROOT+1 );
69835 assert( pKeyInfo->db==db );
69836 assert( pKeyInfo->enc==ENC(db) );
69837 pCx->pKeyInfo = pKeyInfo;
69838 rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
69840 pCx->isTable = 0;
69841 }else{
69842 rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
69843 pCx->isTable = 1;
69846 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
69847 break;
69850 /* Opcode: SorterOpen P1 * * P4 *
69852 ** This opcode works like OP_OpenEphemeral except that it opens
69853 ** a transient index that is specifically designed to sort large
69854 ** tables using an external merge-sort algorithm.
69856 case OP_SorterOpen: {
69857 VdbeCursor *pCx;
69859 assert( pOp->p1>=0 );
69860 assert( pOp->p2>=0 );
69861 pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
69862 if( pCx==0 ) goto no_mem;
69863 pCx->pKeyInfo = pOp->p4.pKeyInfo;
69864 assert( pCx->pKeyInfo->db==db );
69865 assert( pCx->pKeyInfo->enc==ENC(db) );
69866 rc = sqlite3VdbeSorterInit(db, pCx);
69867 break;
69870 /* Opcode: OpenPseudo P1 P2 P3 * P5
69871 ** Synopsis: content in r[P2@P3]
69873 ** Open a new cursor that points to a fake table that contains a single
69874 ** row of data. The content of that one row in the content of memory
69875 ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
69876 ** MEM_Blob content contained in register P2. When P5==1, then the
69877 ** row is represented by P3 consecutive registers beginning with P2.
69879 ** A pseudo-table created by this opcode is used to hold a single
69880 ** row output from the sorter so that the row can be decomposed into
69881 ** individual columns using the OP_Column opcode. The OP_Column opcode
69882 ** is the only cursor opcode that works with a pseudo-table.
69884 ** P3 is the number of fields in the records that will be stored by
69885 ** the pseudo-table.
69887 case OP_OpenPseudo: {
69888 VdbeCursor *pCx;
69890 assert( pOp->p1>=0 );
69891 assert( pOp->p3>=0 );
69892 pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
69893 if( pCx==0 ) goto no_mem;
69894 pCx->nullRow = 1;
69895 pCx->pseudoTableReg = pOp->p2;
69896 pCx->isTable = 1;
69897 pCx->multiPseudo = pOp->p5;
69898 break;
69901 /* Opcode: Close P1 * * * *
69903 ** Close a cursor previously opened as P1. If P1 is not
69904 ** currently open, this instruction is a no-op.
69906 case OP_Close: {
69907 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69908 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
69909 p->apCsr[pOp->p1] = 0;
69910 break;
69913 /* Opcode: SeekGe P1 P2 P3 P4 *
69914 ** Synopsis: key=r[P3@P4]
69916 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69917 ** use the value in register P3 as the key. If cursor P1 refers
69918 ** to an SQL index, then P3 is the first in an array of P4 registers
69919 ** that are used as an unpacked index key.
69921 ** Reposition cursor P1 so that it points to the smallest entry that
69922 ** is greater than or equal to the key value. If there are no records
69923 ** greater than or equal to the key and P2 is not zero, then jump to P2.
69925 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
69927 /* Opcode: SeekGt P1 P2 P3 P4 *
69928 ** Synopsis: key=r[P3@P4]
69930 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69931 ** use the value in register P3 as a key. If cursor P1 refers
69932 ** to an SQL index, then P3 is the first in an array of P4 registers
69933 ** that are used as an unpacked index key.
69935 ** Reposition cursor P1 so that it points to the smallest entry that
69936 ** is greater than the key value. If there are no records greater than
69937 ** the key and P2 is not zero, then jump to P2.
69939 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
69941 /* Opcode: SeekLt P1 P2 P3 P4 *
69942 ** Synopsis: key=r[P3@P4]
69944 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69945 ** use the value in register P3 as a key. If cursor P1 refers
69946 ** to an SQL index, then P3 is the first in an array of P4 registers
69947 ** that are used as an unpacked index key.
69949 ** Reposition cursor P1 so that it points to the largest entry that
69950 ** is less than the key value. If there are no records less than
69951 ** the key and P2 is not zero, then jump to P2.
69953 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
69955 /* Opcode: SeekLe P1 P2 P3 P4 *
69956 ** Synopsis: key=r[P3@P4]
69958 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
69959 ** use the value in register P3 as a key. If cursor P1 refers
69960 ** to an SQL index, then P3 is the first in an array of P4 registers
69961 ** that are used as an unpacked index key.
69963 ** Reposition cursor P1 so that it points to the largest entry that
69964 ** is less than or equal to the key value. If there are no records
69965 ** less than or equal to the key and P2 is not zero, then jump to P2.
69967 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
69969 case OP_SeekLt: /* jump, in3 */
69970 case OP_SeekLe: /* jump, in3 */
69971 case OP_SeekGe: /* jump, in3 */
69972 case OP_SeekGt: { /* jump, in3 */
69973 int res;
69974 int oc;
69975 VdbeCursor *pC;
69976 UnpackedRecord r;
69977 int nField;
69978 i64 iKey; /* The rowid we are to seek to */
69980 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69981 assert( pOp->p2!=0 );
69982 pC = p->apCsr[pOp->p1];
69983 assert( pC!=0 );
69984 assert( pC->pseudoTableReg==0 );
69985 assert( OP_SeekLe == OP_SeekLt+1 );
69986 assert( OP_SeekGe == OP_SeekLt+2 );
69987 assert( OP_SeekGt == OP_SeekLt+3 );
69988 assert( pC->isOrdered );
69989 assert( pC->pCursor!=0 );
69990 oc = pOp->opcode;
69991 pC->nullRow = 0;
69992 if( pC->isTable ){
69993 /* The input value in P3 might be of any type: integer, real, string,
69994 ** blob, or NULL. But it needs to be an integer before we can do
69995 ** the seek, so covert it. */
69996 pIn3 = &aMem[pOp->p3];
69997 applyNumericAffinity(pIn3);
69998 iKey = sqlite3VdbeIntValue(pIn3);
69999 pC->rowidIsValid = 0;
70001 /* If the P3 value could not be converted into an integer without
70002 ** loss of information, then special processing is required... */
70003 if( (pIn3->flags & MEM_Int)==0 ){
70004 if( (pIn3->flags & MEM_Real)==0 ){
70005 /* If the P3 value cannot be converted into any kind of a number,
70006 ** then the seek is not possible, so jump to P2 */
70007 pc = pOp->p2 - 1;
70008 break;
70011 /* If the approximation iKey is larger than the actual real search
70012 ** term, substitute >= for > and < for <=. e.g. if the search term
70013 ** is 4.9 and the integer approximation 5:
70015 ** (x > 4.9) -> (x >= 5)
70016 ** (x <= 4.9) -> (x < 5)
70018 if( pIn3->r<(double)iKey ){
70019 assert( OP_SeekGe==(OP_SeekGt-1) );
70020 assert( OP_SeekLt==(OP_SeekLe-1) );
70021 assert( (OP_SeekLe & 0x0001)==(OP_SeekGt & 0x0001) );
70022 if( (oc & 0x0001)==(OP_SeekGt & 0x0001) ) oc--;
70025 /* If the approximation iKey is smaller than the actual real search
70026 ** term, substitute <= for < and > for >=. */
70027 else if( pIn3->r>(double)iKey ){
70028 assert( OP_SeekLe==(OP_SeekLt+1) );
70029 assert( OP_SeekGt==(OP_SeekGe+1) );
70030 assert( (OP_SeekLt & 0x0001)==(OP_SeekGe & 0x0001) );
70031 if( (oc & 0x0001)==(OP_SeekLt & 0x0001) ) oc++;
70034 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
70035 if( rc!=SQLITE_OK ){
70036 goto abort_due_to_error;
70038 if( res==0 ){
70039 pC->rowidIsValid = 1;
70040 pC->lastRowid = iKey;
70042 }else{
70043 nField = pOp->p4.i;
70044 assert( pOp->p4type==P4_INT32 );
70045 assert( nField>0 );
70046 r.pKeyInfo = pC->pKeyInfo;
70047 r.nField = (u16)nField;
70049 /* The next line of code computes as follows, only faster:
70050 ** if( oc==OP_SeekGt || oc==OP_SeekLe ){
70051 ** r.flags = UNPACKED_INCRKEY;
70052 ** }else{
70053 ** r.flags = 0;
70054 ** }
70056 r.flags = (u8)(UNPACKED_INCRKEY * (1 & (oc - OP_SeekLt)));
70057 assert( oc!=OP_SeekGt || r.flags==UNPACKED_INCRKEY );
70058 assert( oc!=OP_SeekLe || r.flags==UNPACKED_INCRKEY );
70059 assert( oc!=OP_SeekGe || r.flags==0 );
70060 assert( oc!=OP_SeekLt || r.flags==0 );
70062 r.aMem = &aMem[pOp->p3];
70063 #ifdef SQLITE_DEBUG
70064 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
70065 #endif
70066 ExpandBlob(r.aMem);
70067 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
70068 if( rc!=SQLITE_OK ){
70069 goto abort_due_to_error;
70071 pC->rowidIsValid = 0;
70073 pC->deferredMoveto = 0;
70074 pC->cacheStatus = CACHE_STALE;
70075 #ifdef SQLITE_TEST
70076 sqlite3_search_count++;
70077 #endif
70078 if( oc>=OP_SeekGe ){ assert( oc==OP_SeekGe || oc==OP_SeekGt );
70079 if( res<0 || (res==0 && oc==OP_SeekGt) ){
70080 rc = sqlite3BtreeNext(pC->pCursor, &res);
70081 if( rc!=SQLITE_OK ) goto abort_due_to_error;
70082 pC->rowidIsValid = 0;
70083 }else{
70084 res = 0;
70086 }else{
70087 assert( oc==OP_SeekLt || oc==OP_SeekLe );
70088 if( res>0 || (res==0 && oc==OP_SeekLt) ){
70089 rc = sqlite3BtreePrevious(pC->pCursor, &res);
70090 if( rc!=SQLITE_OK ) goto abort_due_to_error;
70091 pC->rowidIsValid = 0;
70092 }else{
70093 /* res might be negative because the table is empty. Check to
70094 ** see if this is the case.
70096 res = sqlite3BtreeEof(pC->pCursor);
70099 assert( pOp->p2>0 );
70100 if( res ){
70101 pc = pOp->p2 - 1;
70103 break;
70106 /* Opcode: Seek P1 P2 * * *
70107 ** Synopsis: intkey=r[P2]
70109 ** P1 is an open table cursor and P2 is a rowid integer. Arrange
70110 ** for P1 to move so that it points to the rowid given by P2.
70112 ** This is actually a deferred seek. Nothing actually happens until
70113 ** the cursor is used to read a record. That way, if no reads
70114 ** occur, no unnecessary I/O happens.
70116 case OP_Seek: { /* in2 */
70117 VdbeCursor *pC;
70119 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70120 pC = p->apCsr[pOp->p1];
70121 assert( pC!=0 );
70122 assert( pC->pCursor!=0 );
70123 assert( pC->isTable );
70124 pC->nullRow = 0;
70125 pIn2 = &aMem[pOp->p2];
70126 pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
70127 pC->rowidIsValid = 0;
70128 pC->deferredMoveto = 1;
70129 break;
70133 /* Opcode: Found P1 P2 P3 P4 *
70134 ** Synopsis: key=r[P3@P4]
70136 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
70137 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
70138 ** record.
70140 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
70141 ** is a prefix of any entry in P1 then a jump is made to P2 and
70142 ** P1 is left pointing at the matching entry.
70144 ** See also: NotFound, NoConflict, NotExists. SeekGe
70146 /* Opcode: NotFound P1 P2 P3 P4 *
70147 ** Synopsis: key=r[P3@P4]
70149 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
70150 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
70151 ** record.
70153 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
70154 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
70155 ** does contain an entry whose prefix matches the P3/P4 record then control
70156 ** falls through to the next instruction and P1 is left pointing at the
70157 ** matching entry.
70159 ** See also: Found, NotExists, NoConflict
70161 /* Opcode: NoConflict P1 P2 P3 P4 *
70162 ** Synopsis: key=r[P3@P4]
70164 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
70165 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
70166 ** record.
70168 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
70169 ** contains any NULL value, jump immediately to P2. If all terms of the
70170 ** record are not-NULL then a check is done to determine if any row in the
70171 ** P1 index btree has a matching key prefix. If there are no matches, jump
70172 ** immediately to P2. If there is a match, fall through and leave the P1
70173 ** cursor pointing to the matching row.
70175 ** This opcode is similar to OP_NotFound with the exceptions that the
70176 ** branch is always taken if any part of the search key input is NULL.
70178 ** See also: NotFound, Found, NotExists
70180 case OP_NoConflict: /* jump, in3 */
70181 case OP_NotFound: /* jump, in3 */
70182 case OP_Found: { /* jump, in3 */
70183 int alreadyExists;
70184 int ii;
70185 VdbeCursor *pC;
70186 int res;
70187 char *pFree;
70188 UnpackedRecord *pIdxKey;
70189 UnpackedRecord r;
70190 char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
70192 #ifdef SQLITE_TEST
70193 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
70194 #endif
70196 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70197 assert( pOp->p4type==P4_INT32 );
70198 pC = p->apCsr[pOp->p1];
70199 assert( pC!=0 );
70200 pIn3 = &aMem[pOp->p3];
70201 assert( pC->pCursor!=0 );
70202 assert( pC->isTable==0 );
70203 pFree = 0; /* Not needed. Only used to suppress a compiler warning. */
70204 if( pOp->p4.i>0 ){
70205 r.pKeyInfo = pC->pKeyInfo;
70206 r.nField = (u16)pOp->p4.i;
70207 r.aMem = pIn3;
70208 #ifdef SQLITE_DEBUG
70210 int i;
70211 for(i=0; i<r.nField; i++){
70212 assert( memIsValid(&r.aMem[i]) );
70213 if( i ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
70216 #endif
70217 r.flags = UNPACKED_PREFIX_MATCH;
70218 pIdxKey = &r;
70219 }else{
70220 pIdxKey = sqlite3VdbeAllocUnpackedRecord(
70221 pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
70223 if( pIdxKey==0 ) goto no_mem;
70224 assert( pIn3->flags & MEM_Blob );
70225 assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
70226 sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
70227 pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
70229 if( pOp->opcode==OP_NoConflict ){
70230 /* For the OP_NoConflict opcode, take the jump if any of the
70231 ** input fields are NULL, since any key with a NULL will not
70232 ** conflict */
70233 for(ii=0; ii<r.nField; ii++){
70234 if( r.aMem[ii].flags & MEM_Null ){
70235 pc = pOp->p2 - 1;
70236 break;
70240 rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
70241 if( pOp->p4.i==0 ){
70242 sqlite3DbFree(db, pFree);
70244 if( rc!=SQLITE_OK ){
70245 break;
70247 pC->seekResult = res;
70248 alreadyExists = (res==0);
70249 pC->nullRow = 1-alreadyExists;
70250 pC->deferredMoveto = 0;
70251 pC->cacheStatus = CACHE_STALE;
70252 if( pOp->opcode==OP_Found ){
70253 if( alreadyExists ) pc = pOp->p2 - 1;
70254 }else{
70255 if( !alreadyExists ) pc = pOp->p2 - 1;
70257 break;
70260 /* Opcode: NotExists P1 P2 P3 * *
70261 ** Synopsis: intkey=r[P3]
70263 ** P1 is the index of a cursor open on an SQL table btree (with integer
70264 ** keys). P3 is an integer rowid. If P1 does not contain a record with
70265 ** rowid P3 then jump immediately to P2. If P1 does contain a record
70266 ** with rowid P3 then leave the cursor pointing at that record and fall
70267 ** through to the next instruction.
70269 ** The OP_NotFound opcode performs the same operation on index btrees
70270 ** (with arbitrary multi-value keys).
70272 ** See also: Found, NotFound, NoConflict
70274 case OP_NotExists: { /* jump, in3 */
70275 VdbeCursor *pC;
70276 BtCursor *pCrsr;
70277 int res;
70278 u64 iKey;
70280 pIn3 = &aMem[pOp->p3];
70281 assert( pIn3->flags & MEM_Int );
70282 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70283 pC = p->apCsr[pOp->p1];
70284 assert( pC!=0 );
70285 assert( pC->isTable );
70286 assert( pC->pseudoTableReg==0 );
70287 pCrsr = pC->pCursor;
70288 assert( pCrsr!=0 );
70289 res = 0;
70290 iKey = pIn3->u.i;
70291 rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
70292 pC->lastRowid = pIn3->u.i;
70293 pC->rowidIsValid = res==0 ?1:0;
70294 pC->nullRow = 0;
70295 pC->cacheStatus = CACHE_STALE;
70296 pC->deferredMoveto = 0;
70297 if( res!=0 ){
70298 pc = pOp->p2 - 1;
70299 assert( pC->rowidIsValid==0 );
70301 pC->seekResult = res;
70302 break;
70305 /* Opcode: Sequence P1 P2 * * *
70306 ** Synopsis: r[P2]=rowid
70308 ** Find the next available sequence number for cursor P1.
70309 ** Write the sequence number into register P2.
70310 ** The sequence number on the cursor is incremented after this
70311 ** instruction.
70313 case OP_Sequence: { /* out2-prerelease */
70314 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70315 assert( p->apCsr[pOp->p1]!=0 );
70316 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
70317 break;
70321 /* Opcode: NewRowid P1 P2 P3 * *
70322 ** Synopsis: r[P2]=rowid
70324 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
70325 ** The record number is not previously used as a key in the database
70326 ** table that cursor P1 points to. The new record number is written
70327 ** written to register P2.
70329 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
70330 ** the largest previously generated record number. No new record numbers are
70331 ** allowed to be less than this value. When this value reaches its maximum,
70332 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
70333 ** generated record number. This P3 mechanism is used to help implement the
70334 ** AUTOINCREMENT feature.
70336 case OP_NewRowid: { /* out2-prerelease */
70337 i64 v; /* The new rowid */
70338 VdbeCursor *pC; /* Cursor of table to get the new rowid */
70339 int res; /* Result of an sqlite3BtreeLast() */
70340 int cnt; /* Counter to limit the number of searches */
70341 Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
70342 VdbeFrame *pFrame; /* Root frame of VDBE */
70344 v = 0;
70345 res = 0;
70346 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70347 pC = p->apCsr[pOp->p1];
70348 assert( pC!=0 );
70349 if( NEVER(pC->pCursor==0) ){
70350 /* The zero initialization above is all that is needed */
70351 }else{
70352 /* The next rowid or record number (different terms for the same
70353 ** thing) is obtained in a two-step algorithm.
70355 ** First we attempt to find the largest existing rowid and add one
70356 ** to that. But if the largest existing rowid is already the maximum
70357 ** positive integer, we have to fall through to the second
70358 ** probabilistic algorithm
70360 ** The second algorithm is to select a rowid at random and see if
70361 ** it already exists in the table. If it does not exist, we have
70362 ** succeeded. If the random rowid does exist, we select a new one
70363 ** and try again, up to 100 times.
70365 assert( pC->isTable );
70367 #ifdef SQLITE_32BIT_ROWID
70368 # define MAX_ROWID 0x7fffffff
70369 #else
70370 /* Some compilers complain about constants of the form 0x7fffffffffffffff.
70371 ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
70372 ** to provide the constant while making all compilers happy.
70374 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
70375 #endif
70377 if( !pC->useRandomRowid ){
70378 v = sqlite3BtreeGetCachedRowid(pC->pCursor);
70379 if( v==0 ){
70380 rc = sqlite3BtreeLast(pC->pCursor, &res);
70381 if( rc!=SQLITE_OK ){
70382 goto abort_due_to_error;
70384 if( res ){
70385 v = 1; /* IMP: R-61914-48074 */
70386 }else{
70387 assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
70388 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
70389 assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
70390 if( v>=MAX_ROWID ){
70391 pC->useRandomRowid = 1;
70392 }else{
70393 v++; /* IMP: R-29538-34987 */
70398 #ifndef SQLITE_OMIT_AUTOINCREMENT
70399 if( pOp->p3 ){
70400 /* Assert that P3 is a valid memory cell. */
70401 assert( pOp->p3>0 );
70402 if( p->pFrame ){
70403 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
70404 /* Assert that P3 is a valid memory cell. */
70405 assert( pOp->p3<=pFrame->nMem );
70406 pMem = &pFrame->aMem[pOp->p3];
70407 }else{
70408 /* Assert that P3 is a valid memory cell. */
70409 assert( pOp->p3<=(p->nMem-p->nCursor) );
70410 pMem = &aMem[pOp->p3];
70411 memAboutToChange(p, pMem);
70413 assert( memIsValid(pMem) );
70415 REGISTER_TRACE(pOp->p3, pMem);
70416 sqlite3VdbeMemIntegerify(pMem);
70417 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
70418 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
70419 rc = SQLITE_FULL; /* IMP: R-12275-61338 */
70420 goto abort_due_to_error;
70422 if( v<pMem->u.i+1 ){
70423 v = pMem->u.i + 1;
70425 pMem->u.i = v;
70427 #endif
70429 sqlite3BtreeSetCachedRowid(pC->pCursor, v<MAX_ROWID ? v+1 : 0);
70431 if( pC->useRandomRowid ){
70432 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
70433 ** largest possible integer (9223372036854775807) then the database
70434 ** engine starts picking positive candidate ROWIDs at random until
70435 ** it finds one that is not previously used. */
70436 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
70437 ** an AUTOINCREMENT table. */
70438 /* on the first attempt, simply do one more than previous */
70439 v = lastRowid;
70440 v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
70441 v++; /* ensure non-zero */
70442 cnt = 0;
70443 while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
70444 0, &res))==SQLITE_OK)
70445 && (res==0)
70446 && (++cnt<100)){
70447 /* collision - try another random rowid */
70448 sqlite3_randomness(sizeof(v), &v);
70449 if( cnt<5 ){
70450 /* try "small" random rowids for the initial attempts */
70451 v &= 0xffffff;
70452 }else{
70453 v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
70455 v++; /* ensure non-zero */
70457 if( rc==SQLITE_OK && res==0 ){
70458 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
70459 goto abort_due_to_error;
70461 assert( v>0 ); /* EV: R-40812-03570 */
70463 pC->rowidIsValid = 0;
70464 pC->deferredMoveto = 0;
70465 pC->cacheStatus = CACHE_STALE;
70467 pOut->u.i = v;
70468 break;
70471 /* Opcode: Insert P1 P2 P3 P4 P5
70472 ** Synopsis: intkey=r[P3] data=r[P2]
70474 ** Write an entry into the table of cursor P1. A new entry is
70475 ** created if it doesn't already exist or the data for an existing
70476 ** entry is overwritten. The data is the value MEM_Blob stored in register
70477 ** number P2. The key is stored in register P3. The key must
70478 ** be a MEM_Int.
70480 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
70481 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
70482 ** then rowid is stored for subsequent return by the
70483 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
70485 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
70486 ** the last seek operation (OP_NotExists) was a success, then this
70487 ** operation will not attempt to find the appropriate row before doing
70488 ** the insert but will instead overwrite the row that the cursor is
70489 ** currently pointing to. Presumably, the prior OP_NotExists opcode
70490 ** has already positioned the cursor correctly. This is an optimization
70491 ** that boosts performance by avoiding redundant seeks.
70493 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
70494 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
70495 ** is part of an INSERT operation. The difference is only important to
70496 ** the update hook.
70498 ** Parameter P4 may point to a string containing the table-name, or
70499 ** may be NULL. If it is not NULL, then the update-hook
70500 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
70502 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
70503 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
70504 ** and register P2 becomes ephemeral. If the cursor is changed, the
70505 ** value of register P2 will then change. Make sure this does not
70506 ** cause any problems.)
70508 ** This instruction only works on tables. The equivalent instruction
70509 ** for indices is OP_IdxInsert.
70511 /* Opcode: InsertInt P1 P2 P3 P4 P5
70512 ** Synopsis: intkey=P3 data=r[P2]
70514 ** This works exactly like OP_Insert except that the key is the
70515 ** integer value P3, not the value of the integer stored in register P3.
70517 case OP_Insert:
70518 case OP_InsertInt: {
70519 Mem *pData; /* MEM cell holding data for the record to be inserted */
70520 Mem *pKey; /* MEM cell holding key for the record */
70521 i64 iKey; /* The integer ROWID or key for the record to be inserted */
70522 VdbeCursor *pC; /* Cursor to table into which insert is written */
70523 int nZero; /* Number of zero-bytes to append */
70524 int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
70525 const char *zDb; /* database name - used by the update hook */
70526 const char *zTbl; /* Table name - used by the opdate hook */
70527 int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
70529 pData = &aMem[pOp->p2];
70530 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70531 assert( memIsValid(pData) );
70532 pC = p->apCsr[pOp->p1];
70533 assert( pC!=0 );
70534 assert( pC->pCursor!=0 );
70535 assert( pC->pseudoTableReg==0 );
70536 assert( pC->isTable );
70537 REGISTER_TRACE(pOp->p2, pData);
70539 if( pOp->opcode==OP_Insert ){
70540 pKey = &aMem[pOp->p3];
70541 assert( pKey->flags & MEM_Int );
70542 assert( memIsValid(pKey) );
70543 REGISTER_TRACE(pOp->p3, pKey);
70544 iKey = pKey->u.i;
70545 }else{
70546 assert( pOp->opcode==OP_InsertInt );
70547 iKey = pOp->p3;
70550 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
70551 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
70552 if( pData->flags & MEM_Null ){
70553 pData->z = 0;
70554 pData->n = 0;
70555 }else{
70556 assert( pData->flags & (MEM_Blob|MEM_Str) );
70558 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
70559 if( pData->flags & MEM_Zero ){
70560 nZero = pData->u.nZero;
70561 }else{
70562 nZero = 0;
70564 sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
70565 rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
70566 pData->z, pData->n, nZero,
70567 (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
70569 pC->rowidIsValid = 0;
70570 pC->deferredMoveto = 0;
70571 pC->cacheStatus = CACHE_STALE;
70573 /* Invoke the update-hook if required. */
70574 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
70575 zDb = db->aDb[pC->iDb].zName;
70576 zTbl = pOp->p4.z;
70577 op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
70578 assert( pC->isTable );
70579 db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
70580 assert( pC->iDb>=0 );
70582 break;
70585 /* Opcode: Delete P1 P2 * P4 *
70587 ** Delete the record at which the P1 cursor is currently pointing.
70589 ** The cursor will be left pointing at either the next or the previous
70590 ** record in the table. If it is left pointing at the next record, then
70591 ** the next Next instruction will be a no-op. Hence it is OK to delete
70592 ** a record from within an Next loop.
70594 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
70595 ** incremented (otherwise not).
70597 ** P1 must not be pseudo-table. It has to be a real table with
70598 ** multiple rows.
70600 ** If P4 is not NULL, then it is the name of the table that P1 is
70601 ** pointing to. The update hook will be invoked, if it exists.
70602 ** If P4 is not NULL then the P1 cursor must have been positioned
70603 ** using OP_NotFound prior to invoking this opcode.
70605 case OP_Delete: {
70606 i64 iKey;
70607 VdbeCursor *pC;
70609 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70610 pC = p->apCsr[pOp->p1];
70611 assert( pC!=0 );
70612 assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
70613 iKey = pC->lastRowid; /* Only used for the update hook */
70615 /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
70616 ** OP_Column on the same table without any intervening operations that
70617 ** might move or invalidate the cursor. Hence cursor pC is always pointing
70618 ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
70619 ** below is always a no-op and cannot fail. We will run it anyhow, though,
70620 ** to guard against future changes to the code generator.
70622 assert( pC->deferredMoveto==0 );
70623 rc = sqlite3VdbeCursorMoveto(pC);
70624 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
70626 sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
70627 rc = sqlite3BtreeDelete(pC->pCursor);
70628 pC->cacheStatus = CACHE_STALE;
70630 /* Invoke the update-hook if required. */
70631 if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
70632 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
70633 db->aDb[pC->iDb].zName, pOp->p4.z, iKey);
70634 assert( pC->iDb>=0 );
70636 if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
70637 break;
70639 /* Opcode: ResetCount * * * * *
70641 ** The value of the change counter is copied to the database handle
70642 ** change counter (returned by subsequent calls to sqlite3_changes()).
70643 ** Then the VMs internal change counter resets to 0.
70644 ** This is used by trigger programs.
70646 case OP_ResetCount: {
70647 sqlite3VdbeSetChanges(db, p->nChange);
70648 p->nChange = 0;
70649 break;
70652 /* Opcode: SorterCompare P1 P2 P3 P4
70653 ** Synopsis: if key(P1)!=rtrim(r[P3],P4) goto P2
70655 ** P1 is a sorter cursor. This instruction compares a prefix of the
70656 ** the record blob in register P3 against a prefix of the entry that
70657 ** the sorter cursor currently points to. The final P4 fields of both
70658 ** the P3 and sorter record are ignored.
70660 ** If either P3 or the sorter contains a NULL in one of their significant
70661 ** fields (not counting the P4 fields at the end which are ignored) then
70662 ** the comparison is assumed to be equal.
70664 ** Fall through to next instruction if the two records compare equal to
70665 ** each other. Jump to P2 if they are different.
70667 case OP_SorterCompare: {
70668 VdbeCursor *pC;
70669 int res;
70670 int nIgnore;
70672 pC = p->apCsr[pOp->p1];
70673 assert( isSorter(pC) );
70674 assert( pOp->p4type==P4_INT32 );
70675 pIn3 = &aMem[pOp->p3];
70676 nIgnore = pOp->p4.i;
70677 rc = sqlite3VdbeSorterCompare(pC, pIn3, nIgnore, &res);
70678 if( res ){
70679 pc = pOp->p2-1;
70681 break;
70684 /* Opcode: SorterData P1 P2 * * *
70685 ** Synopsis: r[P2]=data
70687 ** Write into register P2 the current sorter data for sorter cursor P1.
70689 case OP_SorterData: {
70690 VdbeCursor *pC;
70692 pOut = &aMem[pOp->p2];
70693 pC = p->apCsr[pOp->p1];
70694 assert( isSorter(pC) );
70695 rc = sqlite3VdbeSorterRowkey(pC, pOut);
70696 break;
70699 /* Opcode: RowData P1 P2 * * *
70700 ** Synopsis: r[P2]=data
70702 ** Write into register P2 the complete row data for cursor P1.
70703 ** There is no interpretation of the data.
70704 ** It is just copied onto the P2 register exactly as
70705 ** it is found in the database file.
70707 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
70708 ** of a real table, not a pseudo-table.
70710 /* Opcode: RowKey P1 P2 * * *
70711 ** Synopsis: r[P2]=key
70713 ** Write into register P2 the complete row key for cursor P1.
70714 ** There is no interpretation of the data.
70715 ** The key is copied onto the P3 register exactly as
70716 ** it is found in the database file.
70718 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
70719 ** of a real table, not a pseudo-table.
70721 case OP_RowKey:
70722 case OP_RowData: {
70723 VdbeCursor *pC;
70724 BtCursor *pCrsr;
70725 u32 n;
70726 i64 n64;
70728 pOut = &aMem[pOp->p2];
70729 memAboutToChange(p, pOut);
70731 /* Note that RowKey and RowData are really exactly the same instruction */
70732 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70733 pC = p->apCsr[pOp->p1];
70734 assert( isSorter(pC)==0 );
70735 assert( pC->isTable || pOp->opcode!=OP_RowData );
70736 assert( pC->isTable==0 || pOp->opcode==OP_RowData );
70737 assert( pC!=0 );
70738 assert( pC->nullRow==0 );
70739 assert( pC->pseudoTableReg==0 );
70740 assert( pC->pCursor!=0 );
70741 pCrsr = pC->pCursor;
70742 assert( sqlite3BtreeCursorIsValid(pCrsr) );
70744 /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
70745 ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
70746 ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
70747 ** a no-op and can never fail. But we leave it in place as a safety.
70749 assert( pC->deferredMoveto==0 );
70750 rc = sqlite3VdbeCursorMoveto(pC);
70751 if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
70753 if( pC->isTable==0 ){
70754 assert( !pC->isTable );
70755 VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
70756 assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
70757 if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
70758 goto too_big;
70760 n = (u32)n64;
70761 }else{
70762 VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
70763 assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
70764 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
70765 goto too_big;
70768 if( sqlite3VdbeMemGrow(pOut, n, 0) ){
70769 goto no_mem;
70771 pOut->n = n;
70772 MemSetTypeFlag(pOut, MEM_Blob);
70773 if( pC->isTable==0 ){
70774 rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
70775 }else{
70776 rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
70778 pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
70779 UPDATE_MAX_BLOBSIZE(pOut);
70780 REGISTER_TRACE(pOp->p2, pOut);
70781 break;
70784 /* Opcode: Rowid P1 P2 * * *
70785 ** Synopsis: r[P2]=rowid
70787 ** Store in register P2 an integer which is the key of the table entry that
70788 ** P1 is currently point to.
70790 ** P1 can be either an ordinary table or a virtual table. There used to
70791 ** be a separate OP_VRowid opcode for use with virtual tables, but this
70792 ** one opcode now works for both table types.
70794 case OP_Rowid: { /* out2-prerelease */
70795 VdbeCursor *pC;
70796 i64 v;
70797 sqlite3_vtab *pVtab;
70798 const sqlite3_module *pModule;
70800 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70801 pC = p->apCsr[pOp->p1];
70802 assert( pC!=0 );
70803 assert( pC->pseudoTableReg==0 || pC->nullRow );
70804 if( pC->nullRow ){
70805 pOut->flags = MEM_Null;
70806 break;
70807 }else if( pC->deferredMoveto ){
70808 v = pC->movetoTarget;
70809 #ifndef SQLITE_OMIT_VIRTUALTABLE
70810 }else if( pC->pVtabCursor ){
70811 pVtab = pC->pVtabCursor->pVtab;
70812 pModule = pVtab->pModule;
70813 assert( pModule->xRowid );
70814 rc = pModule->xRowid(pC->pVtabCursor, &v);
70815 sqlite3VtabImportErrmsg(p, pVtab);
70816 #endif /* SQLITE_OMIT_VIRTUALTABLE */
70817 }else{
70818 assert( pC->pCursor!=0 );
70819 rc = sqlite3VdbeCursorMoveto(pC);
70820 if( rc ) goto abort_due_to_error;
70821 if( pC->rowidIsValid ){
70822 v = pC->lastRowid;
70823 }else{
70824 rc = sqlite3BtreeKeySize(pC->pCursor, &v);
70825 assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
70828 pOut->u.i = v;
70829 break;
70832 /* Opcode: NullRow P1 * * * *
70834 ** Move the cursor P1 to a null row. Any OP_Column operations
70835 ** that occur while the cursor is on the null row will always
70836 ** write a NULL.
70838 case OP_NullRow: {
70839 VdbeCursor *pC;
70841 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70842 pC = p->apCsr[pOp->p1];
70843 assert( pC!=0 );
70844 pC->nullRow = 1;
70845 pC->rowidIsValid = 0;
70846 pC->cacheStatus = CACHE_STALE;
70847 if( pC->pCursor ){
70848 sqlite3BtreeClearCursor(pC->pCursor);
70850 break;
70853 /* Opcode: Last P1 P2 * * *
70855 ** The next use of the Rowid or Column or Next instruction for P1
70856 ** will refer to the last entry in the database table or index.
70857 ** If the table or index is empty and P2>0, then jump immediately to P2.
70858 ** If P2 is 0 or if the table or index is not empty, fall through
70859 ** to the following instruction.
70861 case OP_Last: { /* jump */
70862 VdbeCursor *pC;
70863 BtCursor *pCrsr;
70864 int res;
70866 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70867 pC = p->apCsr[pOp->p1];
70868 assert( pC!=0 );
70869 pCrsr = pC->pCursor;
70870 res = 0;
70871 assert( pCrsr!=0 );
70872 rc = sqlite3BtreeLast(pCrsr, &res);
70873 pC->nullRow = (u8)res;
70874 pC->deferredMoveto = 0;
70875 pC->rowidIsValid = 0;
70876 pC->cacheStatus = CACHE_STALE;
70877 if( pOp->p2>0 && res ){
70878 pc = pOp->p2 - 1;
70880 break;
70884 /* Opcode: Sort P1 P2 * * *
70886 ** This opcode does exactly the same thing as OP_Rewind except that
70887 ** it increments an undocumented global variable used for testing.
70889 ** Sorting is accomplished by writing records into a sorting index,
70890 ** then rewinding that index and playing it back from beginning to
70891 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
70892 ** rewinding so that the global variable will be incremented and
70893 ** regression tests can determine whether or not the optimizer is
70894 ** correctly optimizing out sorts.
70896 case OP_SorterSort: /* jump */
70897 case OP_Sort: { /* jump */
70898 #ifdef SQLITE_TEST
70899 sqlite3_sort_count++;
70900 sqlite3_search_count--;
70901 #endif
70902 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
70903 /* Fall through into OP_Rewind */
70905 /* Opcode: Rewind P1 P2 * * *
70907 ** The next use of the Rowid or Column or Next instruction for P1
70908 ** will refer to the first entry in the database table or index.
70909 ** If the table or index is empty and P2>0, then jump immediately to P2.
70910 ** If P2 is 0 or if the table or index is not empty, fall through
70911 ** to the following instruction.
70913 case OP_Rewind: { /* jump */
70914 VdbeCursor *pC;
70915 BtCursor *pCrsr;
70916 int res;
70918 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70919 pC = p->apCsr[pOp->p1];
70920 assert( pC!=0 );
70921 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
70922 res = 1;
70923 if( isSorter(pC) ){
70924 rc = sqlite3VdbeSorterRewind(db, pC, &res);
70925 }else{
70926 pCrsr = pC->pCursor;
70927 assert( pCrsr );
70928 rc = sqlite3BtreeFirst(pCrsr, &res);
70929 pC->deferredMoveto = 0;
70930 pC->cacheStatus = CACHE_STALE;
70931 pC->rowidIsValid = 0;
70933 pC->nullRow = (u8)res;
70934 assert( pOp->p2>0 && pOp->p2<p->nOp );
70935 if( res ){
70936 pc = pOp->p2 - 1;
70938 break;
70941 /* Opcode: Next P1 P2 * * P5
70943 ** Advance cursor P1 so that it points to the next key/data pair in its
70944 ** table or index. If there are no more key/value pairs then fall through
70945 ** to the following instruction. But if the cursor advance was successful,
70946 ** jump immediately to P2.
70948 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
70949 ** been opened prior to this opcode or the program will segfault.
70951 ** P4 is always of type P4_ADVANCE. The function pointer points to
70952 ** sqlite3BtreeNext().
70954 ** If P5 is positive and the jump is taken, then event counter
70955 ** number P5-1 in the prepared statement is incremented.
70957 ** See also: Prev, NextIfOpen
70959 /* Opcode: NextIfOpen P1 P2 * * P5
70961 ** This opcode works just like OP_Next except that if cursor P1 is not
70962 ** open it behaves a no-op.
70964 /* Opcode: Prev P1 P2 * * P5
70966 ** Back up cursor P1 so that it points to the previous key/data pair in its
70967 ** table or index. If there is no previous key/value pairs then fall through
70968 ** to the following instruction. But if the cursor backup was successful,
70969 ** jump immediately to P2.
70971 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
70972 ** not open then the behavior is undefined.
70974 ** P4 is always of type P4_ADVANCE. The function pointer points to
70975 ** sqlite3BtreePrevious().
70977 ** If P5 is positive and the jump is taken, then event counter
70978 ** number P5-1 in the prepared statement is incremented.
70980 /* Opcode: PrevIfOpen P1 P2 * * P5
70982 ** This opcode works just like OP_Prev except that if cursor P1 is not
70983 ** open it behaves a no-op.
70985 case OP_SorterNext: { /* jump */
70986 VdbeCursor *pC;
70987 int res;
70989 pC = p->apCsr[pOp->p1];
70990 assert( isSorter(pC) );
70991 rc = sqlite3VdbeSorterNext(db, pC, &res);
70992 goto next_tail;
70993 case OP_PrevIfOpen: /* jump */
70994 case OP_NextIfOpen: /* jump */
70995 if( p->apCsr[pOp->p1]==0 ) break;
70996 /* Fall through */
70997 case OP_Prev: /* jump */
70998 case OP_Next: /* jump */
70999 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71000 assert( pOp->p5<ArraySize(p->aCounter) );
71001 pC = p->apCsr[pOp->p1];
71002 assert( pC!=0 );
71003 assert( pC->deferredMoveto==0 );
71004 assert( pC->pCursor );
71005 assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
71006 assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
71007 assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
71008 assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
71009 rc = pOp->p4.xAdvance(pC->pCursor, &res);
71010 next_tail:
71011 pC->cacheStatus = CACHE_STALE;
71012 if( res==0 ){
71013 pC->nullRow = 0;
71014 pc = pOp->p2 - 1;
71015 p->aCounter[pOp->p5]++;
71016 #ifdef SQLITE_TEST
71017 sqlite3_search_count++;
71018 #endif
71019 }else{
71020 pC->nullRow = 1;
71022 pC->rowidIsValid = 0;
71023 goto check_for_interrupt;
71026 /* Opcode: IdxInsert P1 P2 P3 * P5
71027 ** Synopsis: key=r[P2]
71029 ** Register P2 holds an SQL index key made using the
71030 ** MakeRecord instructions. This opcode writes that key
71031 ** into the index P1. Data for the entry is nil.
71033 ** P3 is a flag that provides a hint to the b-tree layer that this
71034 ** insert is likely to be an append.
71036 ** This instruction only works for indices. The equivalent instruction
71037 ** for tables is OP_Insert.
71039 case OP_SorterInsert: /* in2 */
71040 case OP_IdxInsert: { /* in2 */
71041 VdbeCursor *pC;
71042 BtCursor *pCrsr;
71043 int nKey;
71044 const char *zKey;
71046 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71047 pC = p->apCsr[pOp->p1];
71048 assert( pC!=0 );
71049 assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
71050 pIn2 = &aMem[pOp->p2];
71051 assert( pIn2->flags & MEM_Blob );
71052 pCrsr = pC->pCursor;
71053 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
71054 assert( pCrsr!=0 );
71055 assert( pC->isTable==0 );
71056 rc = ExpandBlob(pIn2);
71057 if( rc==SQLITE_OK ){
71058 if( isSorter(pC) ){
71059 rc = sqlite3VdbeSorterWrite(db, pC, pIn2);
71060 }else{
71061 nKey = pIn2->n;
71062 zKey = pIn2->z;
71063 rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
71064 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
71066 assert( pC->deferredMoveto==0 );
71067 pC->cacheStatus = CACHE_STALE;
71070 break;
71073 /* Opcode: IdxDelete P1 P2 P3 * *
71074 ** Synopsis: key=r[P2@P3]
71076 ** The content of P3 registers starting at register P2 form
71077 ** an unpacked index key. This opcode removes that entry from the
71078 ** index opened by cursor P1.
71080 case OP_IdxDelete: {
71081 VdbeCursor *pC;
71082 BtCursor *pCrsr;
71083 int res;
71084 UnpackedRecord r;
71086 assert( pOp->p3>0 );
71087 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
71088 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71089 pC = p->apCsr[pOp->p1];
71090 assert( pC!=0 );
71091 pCrsr = pC->pCursor;
71092 assert( pCrsr!=0 );
71093 assert( pOp->p5==0 );
71094 r.pKeyInfo = pC->pKeyInfo;
71095 r.nField = (u16)pOp->p3;
71096 r.flags = UNPACKED_PREFIX_MATCH;
71097 r.aMem = &aMem[pOp->p2];
71098 #ifdef SQLITE_DEBUG
71099 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
71100 #endif
71101 rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
71102 if( rc==SQLITE_OK && res==0 ){
71103 rc = sqlite3BtreeDelete(pCrsr);
71105 assert( pC->deferredMoveto==0 );
71106 pC->cacheStatus = CACHE_STALE;
71107 break;
71110 /* Opcode: IdxRowid P1 P2 * * *
71111 ** Synopsis: r[P2]=rowid
71113 ** Write into register P2 an integer which is the last entry in the record at
71114 ** the end of the index key pointed to by cursor P1. This integer should be
71115 ** the rowid of the table entry to which this index entry points.
71117 ** See also: Rowid, MakeRecord.
71119 case OP_IdxRowid: { /* out2-prerelease */
71120 BtCursor *pCrsr;
71121 VdbeCursor *pC;
71122 i64 rowid;
71124 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71125 pC = p->apCsr[pOp->p1];
71126 assert( pC!=0 );
71127 pCrsr = pC->pCursor;
71128 assert( pCrsr!=0 );
71129 pOut->flags = MEM_Null;
71130 rc = sqlite3VdbeCursorMoveto(pC);
71131 if( NEVER(rc) ) goto abort_due_to_error;
71132 assert( pC->deferredMoveto==0 );
71133 assert( pC->isTable==0 );
71134 if( !pC->nullRow ){
71135 rowid = 0; /* Not needed. Only used to silence a warning. */
71136 rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
71137 if( rc!=SQLITE_OK ){
71138 goto abort_due_to_error;
71140 pOut->u.i = rowid;
71141 pOut->flags = MEM_Int;
71143 break;
71146 /* Opcode: IdxGE P1 P2 P3 P4 P5
71147 ** Synopsis: key=r[P3@P4]
71149 ** The P4 register values beginning with P3 form an unpacked index
71150 ** key that omits the ROWID. Compare this key value against the index
71151 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
71153 ** If the P1 index entry is greater than or equal to the key value
71154 ** then jump to P2. Otherwise fall through to the next instruction.
71156 ** If P5 is non-zero then the key value is increased by an epsilon
71157 ** prior to the comparison. This make the opcode work like IdxGT except
71158 ** that if the key from register P3 is a prefix of the key in the cursor,
71159 ** the result is false whereas it would be true with IdxGT.
71161 /* Opcode: IdxLT P1 P2 P3 P4 P5
71162 ** Synopsis: key=r[P3@P4]
71164 ** The P4 register values beginning with P3 form an unpacked index
71165 ** key that omits the ROWID. Compare this key value against the index
71166 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
71168 ** If the P1 index entry is less than the key value then jump to P2.
71169 ** Otherwise fall through to the next instruction.
71171 ** If P5 is non-zero then the key value is increased by an epsilon prior
71172 ** to the comparison. This makes the opcode work like IdxLE.
71174 case OP_IdxLT: /* jump */
71175 case OP_IdxGE: { /* jump */
71176 VdbeCursor *pC;
71177 int res;
71178 UnpackedRecord r;
71180 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
71181 pC = p->apCsr[pOp->p1];
71182 assert( pC!=0 );
71183 assert( pC->isOrdered );
71184 assert( pC->pCursor!=0);
71185 assert( pC->deferredMoveto==0 );
71186 assert( pOp->p5==0 || pOp->p5==1 );
71187 assert( pOp->p4type==P4_INT32 );
71188 r.pKeyInfo = pC->pKeyInfo;
71189 r.nField = (u16)pOp->p4.i;
71190 if( pOp->p5 ){
71191 r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
71192 }else{
71193 r.flags = UNPACKED_PREFIX_MATCH;
71195 r.aMem = &aMem[pOp->p3];
71196 #ifdef SQLITE_DEBUG
71197 { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
71198 #endif
71199 res = 0; /* Not needed. Only used to silence a warning. */
71200 rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
71201 if( pOp->opcode==OP_IdxLT ){
71202 res = -res;
71203 }else{
71204 assert( pOp->opcode==OP_IdxGE );
71205 res++;
71207 if( res>0 ){
71208 pc = pOp->p2 - 1 ;
71210 break;
71213 /* Opcode: Destroy P1 P2 P3 * *
71215 ** Delete an entire database table or index whose root page in the database
71216 ** file is given by P1.
71218 ** The table being destroyed is in the main database file if P3==0. If
71219 ** P3==1 then the table to be clear is in the auxiliary database file
71220 ** that is used to store tables create using CREATE TEMPORARY TABLE.
71222 ** If AUTOVACUUM is enabled then it is possible that another root page
71223 ** might be moved into the newly deleted root page in order to keep all
71224 ** root pages contiguous at the beginning of the database. The former
71225 ** value of the root page that moved - its value before the move occurred -
71226 ** is stored in register P2. If no page
71227 ** movement was required (because the table being dropped was already
71228 ** the last one in the database) then a zero is stored in register P2.
71229 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
71231 ** See also: Clear
71233 case OP_Destroy: { /* out2-prerelease */
71234 int iMoved;
71235 int iCnt;
71236 Vdbe *pVdbe;
71237 int iDb;
71239 assert( p->readOnly==0 );
71240 #ifndef SQLITE_OMIT_VIRTUALTABLE
71241 iCnt = 0;
71242 for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
71243 if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
71244 && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
71246 iCnt++;
71249 #else
71250 iCnt = db->nVdbeRead;
71251 #endif
71252 pOut->flags = MEM_Null;
71253 if( iCnt>1 ){
71254 rc = SQLITE_LOCKED;
71255 p->errorAction = OE_Abort;
71256 }else{
71257 iDb = pOp->p3;
71258 assert( iCnt==1 );
71259 assert( (p->btreeMask & (((yDbMask)1)<<iDb))!=0 );
71260 iMoved = 0; /* Not needed. Only to silence a warning. */
71261 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
71262 pOut->flags = MEM_Int;
71263 pOut->u.i = iMoved;
71264 #ifndef SQLITE_OMIT_AUTOVACUUM
71265 if( rc==SQLITE_OK && iMoved!=0 ){
71266 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
71267 /* All OP_Destroy operations occur on the same btree */
71268 assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
71269 resetSchemaOnFault = iDb+1;
71271 #endif
71273 break;
71276 /* Opcode: Clear P1 P2 P3
71278 ** Delete all contents of the database table or index whose root page
71279 ** in the database file is given by P1. But, unlike Destroy, do not
71280 ** remove the table or index from the database file.
71282 ** The table being clear is in the main database file if P2==0. If
71283 ** P2==1 then the table to be clear is in the auxiliary database file
71284 ** that is used to store tables create using CREATE TEMPORARY TABLE.
71286 ** If the P3 value is non-zero, then the table referred to must be an
71287 ** intkey table (an SQL table, not an index). In this case the row change
71288 ** count is incremented by the number of rows in the table being cleared.
71289 ** If P3 is greater than zero, then the value stored in register P3 is
71290 ** also incremented by the number of rows in the table being cleared.
71292 ** See also: Destroy
71294 case OP_Clear: {
71295 int nChange;
71297 nChange = 0;
71298 assert( p->readOnly==0 );
71299 assert( pOp->p1!=1 );
71300 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
71301 rc = sqlite3BtreeClearTable(
71302 db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
71304 if( pOp->p3 ){
71305 p->nChange += nChange;
71306 if( pOp->p3>0 ){
71307 assert( memIsValid(&aMem[pOp->p3]) );
71308 memAboutToChange(p, &aMem[pOp->p3]);
71309 aMem[pOp->p3].u.i += nChange;
71312 break;
71315 /* Opcode: CreateTable P1 P2 * * *
71316 ** Synopsis: r[P2]=root iDb=P1
71318 ** Allocate a new table in the main database file if P1==0 or in the
71319 ** auxiliary database file if P1==1 or in an attached database if
71320 ** P1>1. Write the root page number of the new table into
71321 ** register P2
71323 ** The difference between a table and an index is this: A table must
71324 ** have a 4-byte integer key and can have arbitrary data. An index
71325 ** has an arbitrary key but no data.
71327 ** See also: CreateIndex
71329 /* Opcode: CreateIndex P1 P2 * * *
71330 ** Synopsis: r[P2]=root iDb=P1
71332 ** Allocate a new index in the main database file if P1==0 or in the
71333 ** auxiliary database file if P1==1 or in an attached database if
71334 ** P1>1. Write the root page number of the new table into
71335 ** register P2.
71337 ** See documentation on OP_CreateTable for additional information.
71339 case OP_CreateIndex: /* out2-prerelease */
71340 case OP_CreateTable: { /* out2-prerelease */
71341 int pgno;
71342 int flags;
71343 Db *pDb;
71345 pgno = 0;
71346 assert( pOp->p1>=0 && pOp->p1<db->nDb );
71347 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
71348 assert( p->readOnly==0 );
71349 pDb = &db->aDb[pOp->p1];
71350 assert( pDb->pBt!=0 );
71351 if( pOp->opcode==OP_CreateTable ){
71352 /* flags = BTREE_INTKEY; */
71353 flags = BTREE_INTKEY;
71354 }else{
71355 flags = BTREE_BLOBKEY;
71357 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
71358 pOut->u.i = pgno;
71359 break;
71362 /* Opcode: ParseSchema P1 * * P4 *
71364 ** Read and parse all entries from the SQLITE_MASTER table of database P1
71365 ** that match the WHERE clause P4.
71367 ** This opcode invokes the parser to create a new virtual machine,
71368 ** then runs the new virtual machine. It is thus a re-entrant opcode.
71370 case OP_ParseSchema: {
71371 int iDb;
71372 const char *zMaster;
71373 char *zSql;
71374 InitData initData;
71376 /* Any prepared statement that invokes this opcode will hold mutexes
71377 ** on every btree. This is a prerequisite for invoking
71378 ** sqlite3InitCallback().
71380 #ifdef SQLITE_DEBUG
71381 for(iDb=0; iDb<db->nDb; iDb++){
71382 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
71384 #endif
71386 iDb = pOp->p1;
71387 assert( iDb>=0 && iDb<db->nDb );
71388 assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
71389 /* Used to be a conditional */ {
71390 zMaster = SCHEMA_TABLE(iDb);
71391 initData.db = db;
71392 initData.iDb = pOp->p1;
71393 initData.pzErrMsg = &p->zErrMsg;
71394 zSql = sqlite3MPrintf(db,
71395 "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
71396 db->aDb[iDb].zName, zMaster, pOp->p4.z);
71397 if( zSql==0 ){
71398 rc = SQLITE_NOMEM;
71399 }else{
71400 assert( db->init.busy==0 );
71401 db->init.busy = 1;
71402 initData.rc = SQLITE_OK;
71403 assert( !db->mallocFailed );
71404 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
71405 if( rc==SQLITE_OK ) rc = initData.rc;
71406 sqlite3DbFree(db, zSql);
71407 db->init.busy = 0;
71410 if( rc ) sqlite3ResetAllSchemasOfConnection(db);
71411 if( rc==SQLITE_NOMEM ){
71412 goto no_mem;
71414 break;
71417 #if !defined(SQLITE_OMIT_ANALYZE)
71418 /* Opcode: LoadAnalysis P1 * * * *
71420 ** Read the sqlite_stat1 table for database P1 and load the content
71421 ** of that table into the internal index hash table. This will cause
71422 ** the analysis to be used when preparing all subsequent queries.
71424 case OP_LoadAnalysis: {
71425 assert( pOp->p1>=0 && pOp->p1<db->nDb );
71426 rc = sqlite3AnalysisLoad(db, pOp->p1);
71427 break;
71429 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
71431 /* Opcode: DropTable P1 * * P4 *
71433 ** Remove the internal (in-memory) data structures that describe
71434 ** the table named P4 in database P1. This is called after a table
71435 ** is dropped in order to keep the internal representation of the
71436 ** schema consistent with what is on disk.
71438 case OP_DropTable: {
71439 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
71440 break;
71443 /* Opcode: DropIndex P1 * * P4 *
71445 ** Remove the internal (in-memory) data structures that describe
71446 ** the index named P4 in database P1. This is called after an index
71447 ** is dropped in order to keep the internal representation of the
71448 ** schema consistent with what is on disk.
71450 case OP_DropIndex: {
71451 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
71452 break;
71455 /* Opcode: DropTrigger P1 * * P4 *
71457 ** Remove the internal (in-memory) data structures that describe
71458 ** the trigger named P4 in database P1. This is called after a trigger
71459 ** is dropped in order to keep the internal representation of the
71460 ** schema consistent with what is on disk.
71462 case OP_DropTrigger: {
71463 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
71464 break;
71468 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
71469 /* Opcode: IntegrityCk P1 P2 P3 * P5
71471 ** Do an analysis of the currently open database. Store in
71472 ** register P1 the text of an error message describing any problems.
71473 ** If no problems are found, store a NULL in register P1.
71475 ** The register P3 contains the maximum number of allowed errors.
71476 ** At most reg(P3) errors will be reported.
71477 ** In other words, the analysis stops as soon as reg(P1) errors are
71478 ** seen. Reg(P1) is updated with the number of errors remaining.
71480 ** The root page numbers of all tables in the database are integer
71481 ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
71482 ** total.
71484 ** If P5 is not zero, the check is done on the auxiliary database
71485 ** file, not the main database file.
71487 ** This opcode is used to implement the integrity_check pragma.
71489 case OP_IntegrityCk: {
71490 int nRoot; /* Number of tables to check. (Number of root pages.) */
71491 int *aRoot; /* Array of rootpage numbers for tables to be checked */
71492 int j; /* Loop counter */
71493 int nErr; /* Number of errors reported */
71494 char *z; /* Text of the error report */
71495 Mem *pnErr; /* Register keeping track of errors remaining */
71497 assert( p->bIsReader );
71498 nRoot = pOp->p2;
71499 assert( nRoot>0 );
71500 aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
71501 if( aRoot==0 ) goto no_mem;
71502 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71503 pnErr = &aMem[pOp->p3];
71504 assert( (pnErr->flags & MEM_Int)!=0 );
71505 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
71506 pIn1 = &aMem[pOp->p1];
71507 for(j=0; j<nRoot; j++){
71508 aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
71510 aRoot[j] = 0;
71511 assert( pOp->p5<db->nDb );
71512 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
71513 z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
71514 (int)pnErr->u.i, &nErr);
71515 sqlite3DbFree(db, aRoot);
71516 pnErr->u.i -= nErr;
71517 sqlite3VdbeMemSetNull(pIn1);
71518 if( nErr==0 ){
71519 assert( z==0 );
71520 }else if( z==0 ){
71521 goto no_mem;
71522 }else{
71523 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
71525 UPDATE_MAX_BLOBSIZE(pIn1);
71526 sqlite3VdbeChangeEncoding(pIn1, encoding);
71527 break;
71529 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
71531 /* Opcode: RowSetAdd P1 P2 * * *
71532 ** Synopsis: rowset(P1)=r[P2]
71534 ** Insert the integer value held by register P2 into a boolean index
71535 ** held in register P1.
71537 ** An assertion fails if P2 is not an integer.
71539 case OP_RowSetAdd: { /* in1, in2 */
71540 pIn1 = &aMem[pOp->p1];
71541 pIn2 = &aMem[pOp->p2];
71542 assert( (pIn2->flags & MEM_Int)!=0 );
71543 if( (pIn1->flags & MEM_RowSet)==0 ){
71544 sqlite3VdbeMemSetRowSet(pIn1);
71545 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
71547 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
71548 break;
71551 /* Opcode: RowSetRead P1 P2 P3 * *
71552 ** Synopsis: r[P3]=rowset(P1)
71554 ** Extract the smallest value from boolean index P1 and put that value into
71555 ** register P3. Or, if boolean index P1 is initially empty, leave P3
71556 ** unchanged and jump to instruction P2.
71558 case OP_RowSetRead: { /* jump, in1, out3 */
71559 i64 val;
71561 pIn1 = &aMem[pOp->p1];
71562 if( (pIn1->flags & MEM_RowSet)==0
71563 || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
71565 /* The boolean index is empty */
71566 sqlite3VdbeMemSetNull(pIn1);
71567 pc = pOp->p2 - 1;
71568 }else{
71569 /* A value was pulled from the index */
71570 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
71572 goto check_for_interrupt;
71575 /* Opcode: RowSetTest P1 P2 P3 P4
71576 ** Synopsis: if r[P3] in rowset(P1) goto P2
71578 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
71579 ** contains a RowSet object and that RowSet object contains
71580 ** the value held in P3, jump to register P2. Otherwise, insert the
71581 ** integer in P3 into the RowSet and continue on to the
71582 ** next opcode.
71584 ** The RowSet object is optimized for the case where successive sets
71585 ** of integers, where each set contains no duplicates. Each set
71586 ** of values is identified by a unique P4 value. The first set
71587 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
71588 ** non-negative. For non-negative values of P4 only the lower 4
71589 ** bits are significant.
71591 ** This allows optimizations: (a) when P4==0 there is no need to test
71592 ** the rowset object for P3, as it is guaranteed not to contain it,
71593 ** (b) when P4==-1 there is no need to insert the value, as it will
71594 ** never be tested for, and (c) when a value that is part of set X is
71595 ** inserted, there is no need to search to see if the same value was
71596 ** previously inserted as part of set X (only if it was previously
71597 ** inserted as part of some other set).
71599 case OP_RowSetTest: { /* jump, in1, in3 */
71600 int iSet;
71601 int exists;
71603 pIn1 = &aMem[pOp->p1];
71604 pIn3 = &aMem[pOp->p3];
71605 iSet = pOp->p4.i;
71606 assert( pIn3->flags&MEM_Int );
71608 /* If there is anything other than a rowset object in memory cell P1,
71609 ** delete it now and initialize P1 with an empty rowset
71611 if( (pIn1->flags & MEM_RowSet)==0 ){
71612 sqlite3VdbeMemSetRowSet(pIn1);
71613 if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
71616 assert( pOp->p4type==P4_INT32 );
71617 assert( iSet==-1 || iSet>=0 );
71618 if( iSet ){
71619 exists = sqlite3RowSetTest(pIn1->u.pRowSet,
71620 (u8)(iSet>=0 ? iSet & 0xf : 0xff),
71621 pIn3->u.i);
71622 if( exists ){
71623 pc = pOp->p2 - 1;
71624 break;
71627 if( iSet>=0 ){
71628 sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
71630 break;
71634 #ifndef SQLITE_OMIT_TRIGGER
71636 /* Opcode: Program P1 P2 P3 P4 *
71638 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
71640 ** P1 contains the address of the memory cell that contains the first memory
71641 ** cell in an array of values used as arguments to the sub-program. P2
71642 ** contains the address to jump to if the sub-program throws an IGNORE
71643 ** exception using the RAISE() function. Register P3 contains the address
71644 ** of a memory cell in this (the parent) VM that is used to allocate the
71645 ** memory required by the sub-vdbe at runtime.
71647 ** P4 is a pointer to the VM containing the trigger program.
71649 case OP_Program: { /* jump */
71650 int nMem; /* Number of memory registers for sub-program */
71651 int nByte; /* Bytes of runtime space required for sub-program */
71652 Mem *pRt; /* Register to allocate runtime space */
71653 Mem *pMem; /* Used to iterate through memory cells */
71654 Mem *pEnd; /* Last memory cell in new array */
71655 VdbeFrame *pFrame; /* New vdbe frame to execute in */
71656 SubProgram *pProgram; /* Sub-program to execute */
71657 void *t; /* Token identifying trigger */
71659 pProgram = pOp->p4.pProgram;
71660 pRt = &aMem[pOp->p3];
71661 assert( pProgram->nOp>0 );
71663 /* If the p5 flag is clear, then recursive invocation of triggers is
71664 ** disabled for backwards compatibility (p5 is set if this sub-program
71665 ** is really a trigger, not a foreign key action, and the flag set
71666 ** and cleared by the "PRAGMA recursive_triggers" command is clear).
71668 ** It is recursive invocation of triggers, at the SQL level, that is
71669 ** disabled. In some cases a single trigger may generate more than one
71670 ** SubProgram (if the trigger may be executed with more than one different
71671 ** ON CONFLICT algorithm). SubProgram structures associated with a
71672 ** single trigger all have the same value for the SubProgram.token
71673 ** variable. */
71674 if( pOp->p5 ){
71675 t = pProgram->token;
71676 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
71677 if( pFrame ) break;
71680 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
71681 rc = SQLITE_ERROR;
71682 sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
71683 break;
71686 /* Register pRt is used to store the memory required to save the state
71687 ** of the current program, and the memory required at runtime to execute
71688 ** the trigger program. If this trigger has been fired before, then pRt
71689 ** is already allocated. Otherwise, it must be initialized. */
71690 if( (pRt->flags&MEM_Frame)==0 ){
71691 /* SubProgram.nMem is set to the number of memory cells used by the
71692 ** program stored in SubProgram.aOp. As well as these, one memory
71693 ** cell is required for each cursor used by the program. Set local
71694 ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
71696 nMem = pProgram->nMem + pProgram->nCsr;
71697 nByte = ROUND8(sizeof(VdbeFrame))
71698 + nMem * sizeof(Mem)
71699 + pProgram->nCsr * sizeof(VdbeCursor *)
71700 + pProgram->nOnce * sizeof(u8);
71701 pFrame = sqlite3DbMallocZero(db, nByte);
71702 if( !pFrame ){
71703 goto no_mem;
71705 sqlite3VdbeMemRelease(pRt);
71706 pRt->flags = MEM_Frame;
71707 pRt->u.pFrame = pFrame;
71709 pFrame->v = p;
71710 pFrame->nChildMem = nMem;
71711 pFrame->nChildCsr = pProgram->nCsr;
71712 pFrame->pc = pc;
71713 pFrame->aMem = p->aMem;
71714 pFrame->nMem = p->nMem;
71715 pFrame->apCsr = p->apCsr;
71716 pFrame->nCursor = p->nCursor;
71717 pFrame->aOp = p->aOp;
71718 pFrame->nOp = p->nOp;
71719 pFrame->token = pProgram->token;
71720 pFrame->aOnceFlag = p->aOnceFlag;
71721 pFrame->nOnceFlag = p->nOnceFlag;
71723 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
71724 for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
71725 pMem->flags = MEM_Invalid;
71726 pMem->db = db;
71728 }else{
71729 pFrame = pRt->u.pFrame;
71730 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
71731 assert( pProgram->nCsr==pFrame->nChildCsr );
71732 assert( pc==pFrame->pc );
71735 p->nFrame++;
71736 pFrame->pParent = p->pFrame;
71737 pFrame->lastRowid = lastRowid;
71738 pFrame->nChange = p->nChange;
71739 p->nChange = 0;
71740 p->pFrame = pFrame;
71741 p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
71742 p->nMem = pFrame->nChildMem;
71743 p->nCursor = (u16)pFrame->nChildCsr;
71744 p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
71745 p->aOp = aOp = pProgram->aOp;
71746 p->nOp = pProgram->nOp;
71747 p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
71748 p->nOnceFlag = pProgram->nOnce;
71749 pc = -1;
71750 memset(p->aOnceFlag, 0, p->nOnceFlag);
71752 break;
71755 /* Opcode: Param P1 P2 * * *
71757 ** This opcode is only ever present in sub-programs called via the
71758 ** OP_Program instruction. Copy a value currently stored in a memory
71759 ** cell of the calling (parent) frame to cell P2 in the current frames
71760 ** address space. This is used by trigger programs to access the new.*
71761 ** and old.* values.
71763 ** The address of the cell in the parent frame is determined by adding
71764 ** the value of the P1 argument to the value of the P1 argument to the
71765 ** calling OP_Program instruction.
71767 case OP_Param: { /* out2-prerelease */
71768 VdbeFrame *pFrame;
71769 Mem *pIn;
71770 pFrame = p->pFrame;
71771 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
71772 sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
71773 break;
71776 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
71778 #ifndef SQLITE_OMIT_FOREIGN_KEY
71779 /* Opcode: FkCounter P1 P2 * * *
71780 ** Synopsis: fkctr[P1]+=P2
71782 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
71783 ** If P1 is non-zero, the database constraint counter is incremented
71784 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
71785 ** statement counter is incremented (immediate foreign key constraints).
71787 case OP_FkCounter: {
71788 if( db->flags & SQLITE_DeferFKs ){
71789 db->nDeferredImmCons += pOp->p2;
71790 }else if( pOp->p1 ){
71791 db->nDeferredCons += pOp->p2;
71792 }else{
71793 p->nFkConstraint += pOp->p2;
71795 break;
71798 /* Opcode: FkIfZero P1 P2 * * *
71799 ** Synopsis: if fkctr[P1]==0 goto P2
71801 ** This opcode tests if a foreign key constraint-counter is currently zero.
71802 ** If so, jump to instruction P2. Otherwise, fall through to the next
71803 ** instruction.
71805 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
71806 ** is zero (the one that counts deferred constraint violations). If P1 is
71807 ** zero, the jump is taken if the statement constraint-counter is zero
71808 ** (immediate foreign key constraint violations).
71810 case OP_FkIfZero: { /* jump */
71811 if( pOp->p1 ){
71812 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
71813 }else{
71814 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
71816 break;
71818 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
71820 #ifndef SQLITE_OMIT_AUTOINCREMENT
71821 /* Opcode: MemMax P1 P2 * * *
71822 ** Synopsis: r[P1]=max(r[P1],r[P2])
71824 ** P1 is a register in the root frame of this VM (the root frame is
71825 ** different from the current frame if this instruction is being executed
71826 ** within a sub-program). Set the value of register P1 to the maximum of
71827 ** its current value and the value in register P2.
71829 ** This instruction throws an error if the memory cell is not initially
71830 ** an integer.
71832 case OP_MemMax: { /* in2 */
71833 VdbeFrame *pFrame;
71834 if( p->pFrame ){
71835 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
71836 pIn1 = &pFrame->aMem[pOp->p1];
71837 }else{
71838 pIn1 = &aMem[pOp->p1];
71840 assert( memIsValid(pIn1) );
71841 sqlite3VdbeMemIntegerify(pIn1);
71842 pIn2 = &aMem[pOp->p2];
71843 sqlite3VdbeMemIntegerify(pIn2);
71844 if( pIn1->u.i<pIn2->u.i){
71845 pIn1->u.i = pIn2->u.i;
71847 break;
71849 #endif /* SQLITE_OMIT_AUTOINCREMENT */
71851 /* Opcode: IfPos P1 P2 * * *
71852 ** Synopsis: if r[P1]>0 goto P2
71854 ** If the value of register P1 is 1 or greater, jump to P2.
71856 ** It is illegal to use this instruction on a register that does
71857 ** not contain an integer. An assertion fault will result if you try.
71859 case OP_IfPos: { /* jump, in1 */
71860 pIn1 = &aMem[pOp->p1];
71861 assert( pIn1->flags&MEM_Int );
71862 if( pIn1->u.i>0 ){
71863 pc = pOp->p2 - 1;
71865 break;
71868 /* Opcode: IfNeg P1 P2 * * *
71869 ** Synopsis: if r[P1]<0 goto P2
71871 ** If the value of register P1 is less than zero, jump to P2.
71873 ** It is illegal to use this instruction on a register that does
71874 ** not contain an integer. An assertion fault will result if you try.
71876 case OP_IfNeg: { /* jump, in1 */
71877 pIn1 = &aMem[pOp->p1];
71878 assert( pIn1->flags&MEM_Int );
71879 if( pIn1->u.i<0 ){
71880 pc = pOp->p2 - 1;
71882 break;
71885 /* Opcode: IfZero P1 P2 P3 * *
71886 ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
71888 ** The register P1 must contain an integer. Add literal P3 to the
71889 ** value in register P1. If the result is exactly 0, jump to P2.
71891 ** It is illegal to use this instruction on a register that does
71892 ** not contain an integer. An assertion fault will result if you try.
71894 case OP_IfZero: { /* jump, in1 */
71895 pIn1 = &aMem[pOp->p1];
71896 assert( pIn1->flags&MEM_Int );
71897 pIn1->u.i += pOp->p3;
71898 if( pIn1->u.i==0 ){
71899 pc = pOp->p2 - 1;
71901 break;
71904 /* Opcode: AggStep * P2 P3 P4 P5
71905 ** Synopsis: accum=r[P3] step(r[P2@P5])
71907 ** Execute the step function for an aggregate. The
71908 ** function has P5 arguments. P4 is a pointer to the FuncDef
71909 ** structure that specifies the function. Use register
71910 ** P3 as the accumulator.
71912 ** The P5 arguments are taken from register P2 and its
71913 ** successors.
71915 case OP_AggStep: {
71916 int n;
71917 int i;
71918 Mem *pMem;
71919 Mem *pRec;
71920 sqlite3_context ctx;
71921 sqlite3_value **apVal;
71923 n = pOp->p5;
71924 assert( n>=0 );
71925 pRec = &aMem[pOp->p2];
71926 apVal = p->apArg;
71927 assert( apVal || n==0 );
71928 for(i=0; i<n; i++, pRec++){
71929 assert( memIsValid(pRec) );
71930 apVal[i] = pRec;
71931 memAboutToChange(p, pRec);
71932 sqlite3VdbeMemStoreType(pRec);
71934 ctx.pFunc = pOp->p4.pFunc;
71935 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
71936 ctx.pMem = pMem = &aMem[pOp->p3];
71937 pMem->n++;
71938 ctx.s.flags = MEM_Null;
71939 ctx.s.z = 0;
71940 ctx.s.zMalloc = 0;
71941 ctx.s.xDel = 0;
71942 ctx.s.db = db;
71943 ctx.isError = 0;
71944 ctx.pColl = 0;
71945 ctx.skipFlag = 0;
71946 if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
71947 assert( pOp>p->aOp );
71948 assert( pOp[-1].p4type==P4_COLLSEQ );
71949 assert( pOp[-1].opcode==OP_CollSeq );
71950 ctx.pColl = pOp[-1].p4.pColl;
71952 (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
71953 if( ctx.isError ){
71954 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&ctx.s));
71955 rc = ctx.isError;
71957 if( ctx.skipFlag ){
71958 assert( pOp[-1].opcode==OP_CollSeq );
71959 i = pOp[-1].p1;
71960 if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
71963 sqlite3VdbeMemRelease(&ctx.s);
71965 break;
71968 /* Opcode: AggFinal P1 P2 * P4 *
71969 ** Synopsis: accum=r[P1] N=P2
71971 ** Execute the finalizer function for an aggregate. P1 is
71972 ** the memory location that is the accumulator for the aggregate.
71974 ** P2 is the number of arguments that the step function takes and
71975 ** P4 is a pointer to the FuncDef for this function. The P2
71976 ** argument is not used by this opcode. It is only there to disambiguate
71977 ** functions that can take varying numbers of arguments. The
71978 ** P4 argument is only needed for the degenerate case where
71979 ** the step function was not previously called.
71981 case OP_AggFinal: {
71982 Mem *pMem;
71983 assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
71984 pMem = &aMem[pOp->p1];
71985 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
71986 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
71987 if( rc ){
71988 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
71990 sqlite3VdbeChangeEncoding(pMem, encoding);
71991 UPDATE_MAX_BLOBSIZE(pMem);
71992 if( sqlite3VdbeMemTooBig(pMem) ){
71993 goto too_big;
71995 break;
71998 #ifndef SQLITE_OMIT_WAL
71999 /* Opcode: Checkpoint P1 P2 P3 * *
72001 ** Checkpoint database P1. This is a no-op if P1 is not currently in
72002 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
72003 ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
72004 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
72005 ** WAL after the checkpoint into mem[P3+1] and the number of pages
72006 ** in the WAL that have been checkpointed after the checkpoint
72007 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
72008 ** mem[P3+2] are initialized to -1.
72010 case OP_Checkpoint: {
72011 int i; /* Loop counter */
72012 int aRes[3]; /* Results */
72013 Mem *pMem; /* Write results here */
72015 assert( p->readOnly==0 );
72016 aRes[0] = 0;
72017 aRes[1] = aRes[2] = -1;
72018 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
72019 || pOp->p2==SQLITE_CHECKPOINT_FULL
72020 || pOp->p2==SQLITE_CHECKPOINT_RESTART
72022 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
72023 if( rc==SQLITE_BUSY ){
72024 rc = SQLITE_OK;
72025 aRes[0] = 1;
72027 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
72028 sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
72030 break;
72032 #endif
72034 #ifndef SQLITE_OMIT_PRAGMA
72035 /* Opcode: JournalMode P1 P2 P3 * P5
72037 ** Change the journal mode of database P1 to P3. P3 must be one of the
72038 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
72039 ** modes (delete, truncate, persist, off and memory), this is a simple
72040 ** operation. No IO is required.
72042 ** If changing into or out of WAL mode the procedure is more complicated.
72044 ** Write a string containing the final journal-mode to register P2.
72046 case OP_JournalMode: { /* out2-prerelease */
72047 Btree *pBt; /* Btree to change journal mode of */
72048 Pager *pPager; /* Pager associated with pBt */
72049 int eNew; /* New journal mode */
72050 int eOld; /* The old journal mode */
72051 #ifndef SQLITE_OMIT_WAL
72052 const char *zFilename; /* Name of database file for pPager */
72053 #endif
72055 eNew = pOp->p3;
72056 assert( eNew==PAGER_JOURNALMODE_DELETE
72057 || eNew==PAGER_JOURNALMODE_TRUNCATE
72058 || eNew==PAGER_JOURNALMODE_PERSIST
72059 || eNew==PAGER_JOURNALMODE_OFF
72060 || eNew==PAGER_JOURNALMODE_MEMORY
72061 || eNew==PAGER_JOURNALMODE_WAL
72062 || eNew==PAGER_JOURNALMODE_QUERY
72064 assert( pOp->p1>=0 && pOp->p1<db->nDb );
72065 assert( p->readOnly==0 );
72067 pBt = db->aDb[pOp->p1].pBt;
72068 pPager = sqlite3BtreePager(pBt);
72069 eOld = sqlite3PagerGetJournalMode(pPager);
72070 if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
72071 if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
72073 #ifndef SQLITE_OMIT_WAL
72074 zFilename = sqlite3PagerFilename(pPager, 1);
72076 /* Do not allow a transition to journal_mode=WAL for a database
72077 ** in temporary storage or if the VFS does not support shared memory
72079 if( eNew==PAGER_JOURNALMODE_WAL
72080 && (sqlite3Strlen30(zFilename)==0 /* Temp file */
72081 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
72083 eNew = eOld;
72086 if( (eNew!=eOld)
72087 && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
72089 if( !db->autoCommit || db->nVdbeRead>1 ){
72090 rc = SQLITE_ERROR;
72091 sqlite3SetString(&p->zErrMsg, db,
72092 "cannot change %s wal mode from within a transaction",
72093 (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
72095 break;
72096 }else{
72098 if( eOld==PAGER_JOURNALMODE_WAL ){
72099 /* If leaving WAL mode, close the log file. If successful, the call
72100 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
72101 ** file. An EXCLUSIVE lock may still be held on the database file
72102 ** after a successful return.
72104 rc = sqlite3PagerCloseWal(pPager);
72105 if( rc==SQLITE_OK ){
72106 sqlite3PagerSetJournalMode(pPager, eNew);
72108 }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
72109 /* Cannot transition directly from MEMORY to WAL. Use mode OFF
72110 ** as an intermediate */
72111 sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
72114 /* Open a transaction on the database file. Regardless of the journal
72115 ** mode, this transaction always uses a rollback journal.
72117 assert( sqlite3BtreeIsInTrans(pBt)==0 );
72118 if( rc==SQLITE_OK ){
72119 rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
72123 #endif /* ifndef SQLITE_OMIT_WAL */
72125 if( rc ){
72126 eNew = eOld;
72128 eNew = sqlite3PagerSetJournalMode(pPager, eNew);
72130 pOut = &aMem[pOp->p2];
72131 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
72132 pOut->z = (char *)sqlite3JournalModename(eNew);
72133 pOut->n = sqlite3Strlen30(pOut->z);
72134 pOut->enc = SQLITE_UTF8;
72135 sqlite3VdbeChangeEncoding(pOut, encoding);
72136 break;
72138 #endif /* SQLITE_OMIT_PRAGMA */
72140 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
72141 /* Opcode: Vacuum * * * * *
72143 ** Vacuum the entire database. This opcode will cause other virtual
72144 ** machines to be created and run. It may not be called from within
72145 ** a transaction.
72147 case OP_Vacuum: {
72148 assert( p->readOnly==0 );
72149 rc = sqlite3RunVacuum(&p->zErrMsg, db);
72150 break;
72152 #endif
72154 #if !defined(SQLITE_OMIT_AUTOVACUUM)
72155 /* Opcode: IncrVacuum P1 P2 * * *
72157 ** Perform a single step of the incremental vacuum procedure on
72158 ** the P1 database. If the vacuum has finished, jump to instruction
72159 ** P2. Otherwise, fall through to the next instruction.
72161 case OP_IncrVacuum: { /* jump */
72162 Btree *pBt;
72164 assert( pOp->p1>=0 && pOp->p1<db->nDb );
72165 assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
72166 assert( p->readOnly==0 );
72167 pBt = db->aDb[pOp->p1].pBt;
72168 rc = sqlite3BtreeIncrVacuum(pBt);
72169 if( rc==SQLITE_DONE ){
72170 pc = pOp->p2 - 1;
72171 rc = SQLITE_OK;
72173 break;
72175 #endif
72177 /* Opcode: Expire P1 * * * *
72179 ** Cause precompiled statements to become expired. An expired statement
72180 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
72181 ** (via sqlite3_step()).
72183 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
72184 ** then only the currently executing statement is affected.
72186 case OP_Expire: {
72187 if( !pOp->p1 ){
72188 sqlite3ExpirePreparedStatements(db);
72189 }else{
72190 p->expired = 1;
72192 break;
72195 #ifndef SQLITE_OMIT_SHARED_CACHE
72196 /* Opcode: TableLock P1 P2 P3 P4 *
72197 ** Synopsis: iDb=P1 root=P2 write=P3
72199 ** Obtain a lock on a particular table. This instruction is only used when
72200 ** the shared-cache feature is enabled.
72202 ** P1 is the index of the database in sqlite3.aDb[] of the database
72203 ** on which the lock is acquired. A readlock is obtained if P3==0 or
72204 ** a write lock if P3==1.
72206 ** P2 contains the root-page of the table to lock.
72208 ** P4 contains a pointer to the name of the table being locked. This is only
72209 ** used to generate an error message if the lock cannot be obtained.
72211 case OP_TableLock: {
72212 u8 isWriteLock = (u8)pOp->p3;
72213 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
72214 int p1 = pOp->p1;
72215 assert( p1>=0 && p1<db->nDb );
72216 assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
72217 assert( isWriteLock==0 || isWriteLock==1 );
72218 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
72219 if( (rc&0xFF)==SQLITE_LOCKED ){
72220 const char *z = pOp->p4.z;
72221 sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
72224 break;
72226 #endif /* SQLITE_OMIT_SHARED_CACHE */
72228 #ifndef SQLITE_OMIT_VIRTUALTABLE
72229 /* Opcode: VBegin * * * P4 *
72231 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
72232 ** xBegin method for that table.
72234 ** Also, whether or not P4 is set, check that this is not being called from
72235 ** within a callback to a virtual table xSync() method. If it is, the error
72236 ** code will be set to SQLITE_LOCKED.
72238 case OP_VBegin: {
72239 VTable *pVTab;
72240 pVTab = pOp->p4.pVtab;
72241 rc = sqlite3VtabBegin(db, pVTab);
72242 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
72243 break;
72245 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72247 #ifndef SQLITE_OMIT_VIRTUALTABLE
72248 /* Opcode: VCreate P1 * * P4 *
72250 ** P4 is the name of a virtual table in database P1. Call the xCreate method
72251 ** for that table.
72253 case OP_VCreate: {
72254 rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
72255 break;
72257 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72259 #ifndef SQLITE_OMIT_VIRTUALTABLE
72260 /* Opcode: VDestroy P1 * * P4 *
72262 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
72263 ** of that table.
72265 case OP_VDestroy: {
72266 p->inVtabMethod = 2;
72267 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
72268 p->inVtabMethod = 0;
72269 break;
72271 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72273 #ifndef SQLITE_OMIT_VIRTUALTABLE
72274 /* Opcode: VOpen P1 * * P4 *
72276 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
72277 ** P1 is a cursor number. This opcode opens a cursor to the virtual
72278 ** table and stores that cursor in P1.
72280 case OP_VOpen: {
72281 VdbeCursor *pCur;
72282 sqlite3_vtab_cursor *pVtabCursor;
72283 sqlite3_vtab *pVtab;
72284 sqlite3_module *pModule;
72286 assert( p->bIsReader );
72287 pCur = 0;
72288 pVtabCursor = 0;
72289 pVtab = pOp->p4.pVtab->pVtab;
72290 pModule = (sqlite3_module *)pVtab->pModule;
72291 assert(pVtab && pModule);
72292 rc = pModule->xOpen(pVtab, &pVtabCursor);
72293 sqlite3VtabImportErrmsg(p, pVtab);
72294 if( SQLITE_OK==rc ){
72295 /* Initialize sqlite3_vtab_cursor base class */
72296 pVtabCursor->pVtab = pVtab;
72298 /* Initialize vdbe cursor object */
72299 pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
72300 if( pCur ){
72301 pCur->pVtabCursor = pVtabCursor;
72302 }else{
72303 db->mallocFailed = 1;
72304 pModule->xClose(pVtabCursor);
72307 break;
72309 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72311 #ifndef SQLITE_OMIT_VIRTUALTABLE
72312 /* Opcode: VFilter P1 P2 P3 P4 *
72313 ** Synopsis: iPlan=r[P3] zPlan='P4'
72315 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
72316 ** the filtered result set is empty.
72318 ** P4 is either NULL or a string that was generated by the xBestIndex
72319 ** method of the module. The interpretation of the P4 string is left
72320 ** to the module implementation.
72322 ** This opcode invokes the xFilter method on the virtual table specified
72323 ** by P1. The integer query plan parameter to xFilter is stored in register
72324 ** P3. Register P3+1 stores the argc parameter to be passed to the
72325 ** xFilter method. Registers P3+2..P3+1+argc are the argc
72326 ** additional parameters which are passed to
72327 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
72329 ** A jump is made to P2 if the result set after filtering would be empty.
72331 case OP_VFilter: { /* jump */
72332 int nArg;
72333 int iQuery;
72334 const sqlite3_module *pModule;
72335 Mem *pQuery;
72336 Mem *pArgc;
72337 sqlite3_vtab_cursor *pVtabCursor;
72338 sqlite3_vtab *pVtab;
72339 VdbeCursor *pCur;
72340 int res;
72341 int i;
72342 Mem **apArg;
72344 pQuery = &aMem[pOp->p3];
72345 pArgc = &pQuery[1];
72346 pCur = p->apCsr[pOp->p1];
72347 assert( memIsValid(pQuery) );
72348 REGISTER_TRACE(pOp->p3, pQuery);
72349 assert( pCur->pVtabCursor );
72350 pVtabCursor = pCur->pVtabCursor;
72351 pVtab = pVtabCursor->pVtab;
72352 pModule = pVtab->pModule;
72354 /* Grab the index number and argc parameters */
72355 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
72356 nArg = (int)pArgc->u.i;
72357 iQuery = (int)pQuery->u.i;
72359 /* Invoke the xFilter method */
72361 res = 0;
72362 apArg = p->apArg;
72363 for(i = 0; i<nArg; i++){
72364 apArg[i] = &pArgc[i+1];
72365 sqlite3VdbeMemStoreType(apArg[i]);
72368 p->inVtabMethod = 1;
72369 rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
72370 p->inVtabMethod = 0;
72371 sqlite3VtabImportErrmsg(p, pVtab);
72372 if( rc==SQLITE_OK ){
72373 res = pModule->xEof(pVtabCursor);
72376 if( res ){
72377 pc = pOp->p2 - 1;
72380 pCur->nullRow = 0;
72382 break;
72384 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72386 #ifndef SQLITE_OMIT_VIRTUALTABLE
72387 /* Opcode: VColumn P1 P2 P3 * *
72388 ** Synopsis: r[P3]=vcolumn(P2)
72390 ** Store the value of the P2-th column of
72391 ** the row of the virtual-table that the
72392 ** P1 cursor is pointing to into register P3.
72394 case OP_VColumn: {
72395 sqlite3_vtab *pVtab;
72396 const sqlite3_module *pModule;
72397 Mem *pDest;
72398 sqlite3_context sContext;
72400 VdbeCursor *pCur = p->apCsr[pOp->p1];
72401 assert( pCur->pVtabCursor );
72402 assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
72403 pDest = &aMem[pOp->p3];
72404 memAboutToChange(p, pDest);
72405 if( pCur->nullRow ){
72406 sqlite3VdbeMemSetNull(pDest);
72407 break;
72409 pVtab = pCur->pVtabCursor->pVtab;
72410 pModule = pVtab->pModule;
72411 assert( pModule->xColumn );
72412 memset(&sContext, 0, sizeof(sContext));
72414 /* The output cell may already have a buffer allocated. Move
72415 ** the current contents to sContext.s so in case the user-function
72416 ** can use the already allocated buffer instead of allocating a
72417 ** new one.
72419 sqlite3VdbeMemMove(&sContext.s, pDest);
72420 MemSetTypeFlag(&sContext.s, MEM_Null);
72422 rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
72423 sqlite3VtabImportErrmsg(p, pVtab);
72424 if( sContext.isError ){
72425 rc = sContext.isError;
72428 /* Copy the result of the function to the P3 register. We
72429 ** do this regardless of whether or not an error occurred to ensure any
72430 ** dynamic allocation in sContext.s (a Mem struct) is released.
72432 sqlite3VdbeChangeEncoding(&sContext.s, encoding);
72433 sqlite3VdbeMemMove(pDest, &sContext.s);
72434 REGISTER_TRACE(pOp->p3, pDest);
72435 UPDATE_MAX_BLOBSIZE(pDest);
72437 if( sqlite3VdbeMemTooBig(pDest) ){
72438 goto too_big;
72440 break;
72442 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72444 #ifndef SQLITE_OMIT_VIRTUALTABLE
72445 /* Opcode: VNext P1 P2 * * *
72447 ** Advance virtual table P1 to the next row in its result set and
72448 ** jump to instruction P2. Or, if the virtual table has reached
72449 ** the end of its result set, then fall through to the next instruction.
72451 case OP_VNext: { /* jump */
72452 sqlite3_vtab *pVtab;
72453 const sqlite3_module *pModule;
72454 int res;
72455 VdbeCursor *pCur;
72457 res = 0;
72458 pCur = p->apCsr[pOp->p1];
72459 assert( pCur->pVtabCursor );
72460 if( pCur->nullRow ){
72461 break;
72463 pVtab = pCur->pVtabCursor->pVtab;
72464 pModule = pVtab->pModule;
72465 assert( pModule->xNext );
72467 /* Invoke the xNext() method of the module. There is no way for the
72468 ** underlying implementation to return an error if one occurs during
72469 ** xNext(). Instead, if an error occurs, true is returned (indicating that
72470 ** data is available) and the error code returned when xColumn or
72471 ** some other method is next invoked on the save virtual table cursor.
72473 p->inVtabMethod = 1;
72474 rc = pModule->xNext(pCur->pVtabCursor);
72475 p->inVtabMethod = 0;
72476 sqlite3VtabImportErrmsg(p, pVtab);
72477 if( rc==SQLITE_OK ){
72478 res = pModule->xEof(pCur->pVtabCursor);
72481 if( !res ){
72482 /* If there is data, jump to P2 */
72483 pc = pOp->p2 - 1;
72485 goto check_for_interrupt;
72487 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72489 #ifndef SQLITE_OMIT_VIRTUALTABLE
72490 /* Opcode: VRename P1 * * P4 *
72492 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
72493 ** This opcode invokes the corresponding xRename method. The value
72494 ** in register P1 is passed as the zName argument to the xRename method.
72496 case OP_VRename: {
72497 sqlite3_vtab *pVtab;
72498 Mem *pName;
72500 pVtab = pOp->p4.pVtab->pVtab;
72501 pName = &aMem[pOp->p1];
72502 assert( pVtab->pModule->xRename );
72503 assert( memIsValid(pName) );
72504 assert( p->readOnly==0 );
72505 REGISTER_TRACE(pOp->p1, pName);
72506 assert( pName->flags & MEM_Str );
72507 testcase( pName->enc==SQLITE_UTF8 );
72508 testcase( pName->enc==SQLITE_UTF16BE );
72509 testcase( pName->enc==SQLITE_UTF16LE );
72510 rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
72511 if( rc==SQLITE_OK ){
72512 rc = pVtab->pModule->xRename(pVtab, pName->z);
72513 sqlite3VtabImportErrmsg(p, pVtab);
72514 p->expired = 0;
72516 break;
72518 #endif
72520 #ifndef SQLITE_OMIT_VIRTUALTABLE
72521 /* Opcode: VUpdate P1 P2 P3 P4 *
72522 ** Synopsis: data=r[P3@P2]
72524 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
72525 ** This opcode invokes the corresponding xUpdate method. P2 values
72526 ** are contiguous memory cells starting at P3 to pass to the xUpdate
72527 ** invocation. The value in register (P3+P2-1) corresponds to the
72528 ** p2th element of the argv array passed to xUpdate.
72530 ** The xUpdate method will do a DELETE or an INSERT or both.
72531 ** The argv[0] element (which corresponds to memory cell P3)
72532 ** is the rowid of a row to delete. If argv[0] is NULL then no
72533 ** deletion occurs. The argv[1] element is the rowid of the new
72534 ** row. This can be NULL to have the virtual table select the new
72535 ** rowid for itself. The subsequent elements in the array are
72536 ** the values of columns in the new row.
72538 ** If P2==1 then no insert is performed. argv[0] is the rowid of
72539 ** a row to delete.
72541 ** P1 is a boolean flag. If it is set to true and the xUpdate call
72542 ** is successful, then the value returned by sqlite3_last_insert_rowid()
72543 ** is set to the value of the rowid for the row just inserted.
72545 case OP_VUpdate: {
72546 sqlite3_vtab *pVtab;
72547 sqlite3_module *pModule;
72548 int nArg;
72549 int i;
72550 sqlite_int64 rowid;
72551 Mem **apArg;
72552 Mem *pX;
72554 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
72555 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
72557 assert( p->readOnly==0 );
72558 pVtab = pOp->p4.pVtab->pVtab;
72559 pModule = (sqlite3_module *)pVtab->pModule;
72560 nArg = pOp->p2;
72561 assert( pOp->p4type==P4_VTAB );
72562 if( ALWAYS(pModule->xUpdate) ){
72563 u8 vtabOnConflict = db->vtabOnConflict;
72564 apArg = p->apArg;
72565 pX = &aMem[pOp->p3];
72566 for(i=0; i<nArg; i++){
72567 assert( memIsValid(pX) );
72568 memAboutToChange(p, pX);
72569 sqlite3VdbeMemStoreType(pX);
72570 apArg[i] = pX;
72571 pX++;
72573 db->vtabOnConflict = pOp->p5;
72574 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
72575 db->vtabOnConflict = vtabOnConflict;
72576 sqlite3VtabImportErrmsg(p, pVtab);
72577 if( rc==SQLITE_OK && pOp->p1 ){
72578 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
72579 db->lastRowid = lastRowid = rowid;
72581 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
72582 if( pOp->p5==OE_Ignore ){
72583 rc = SQLITE_OK;
72584 }else{
72585 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
72587 }else{
72588 p->nChange++;
72591 break;
72593 #endif /* SQLITE_OMIT_VIRTUALTABLE */
72595 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
72596 /* Opcode: Pagecount P1 P2 * * *
72598 ** Write the current number of pages in database P1 to memory cell P2.
72600 case OP_Pagecount: { /* out2-prerelease */
72601 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
72602 break;
72604 #endif
72607 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
72608 /* Opcode: MaxPgcnt P1 P2 P3 * *
72610 ** Try to set the maximum page count for database P1 to the value in P3.
72611 ** Do not let the maximum page count fall below the current page count and
72612 ** do not change the maximum page count value if P3==0.
72614 ** Store the maximum page count after the change in register P2.
72616 case OP_MaxPgcnt: { /* out2-prerelease */
72617 unsigned int newMax;
72618 Btree *pBt;
72620 pBt = db->aDb[pOp->p1].pBt;
72621 newMax = 0;
72622 if( pOp->p3 ){
72623 newMax = sqlite3BtreeLastPage(pBt);
72624 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
72626 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
72627 break;
72629 #endif
72632 #ifndef SQLITE_OMIT_TRACE
72633 /* Opcode: Trace * * * P4 *
72635 ** If tracing is enabled (by the sqlite3_trace()) interface, then
72636 ** the UTF-8 string contained in P4 is emitted on the trace callback.
72638 case OP_Trace: {
72639 char *zTrace;
72640 char *z;
72642 if( db->xTrace
72643 && !p->doingRerun
72644 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
72646 z = sqlite3VdbeExpandSql(p, zTrace);
72647 db->xTrace(db->pTraceArg, z);
72648 sqlite3DbFree(db, z);
72650 #ifdef SQLITE_USE_FCNTL_TRACE
72651 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
72652 if( zTrace ){
72653 int i;
72654 for(i=0; i<db->nDb; i++){
72655 if( MASKBIT(i) & p->btreeMask)==0 ) continue;
72656 sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
72659 #endif /* SQLITE_USE_FCNTL_TRACE */
72660 #ifdef SQLITE_DEBUG
72661 if( (db->flags & SQLITE_SqlTrace)!=0
72662 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
72664 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
72666 #endif /* SQLITE_DEBUG */
72667 break;
72669 #endif
72672 /* Opcode: Noop * * * * *
72674 ** Do nothing. This instruction is often useful as a jump
72675 ** destination.
72678 ** The magic Explain opcode are only inserted when explain==2 (which
72679 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
72680 ** This opcode records information from the optimizer. It is the
72681 ** the same as a no-op. This opcodesnever appears in a real VM program.
72683 default: { /* This is really OP_Noop and OP_Explain */
72684 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
72685 break;
72688 /*****************************************************************************
72689 ** The cases of the switch statement above this line should all be indented
72690 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
72691 ** readability. From this point on down, the normal indentation rules are
72692 ** restored.
72693 *****************************************************************************/
72696 #ifdef VDBE_PROFILE
72698 u64 elapsed = sqlite3Hwtime() - start;
72699 pOp->cycles += elapsed;
72700 pOp->cnt++;
72701 #if 0
72702 fprintf(stdout, "%10llu ", elapsed);
72703 sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
72704 #endif
72706 #endif
72708 /* The following code adds nothing to the actual functionality
72709 ** of the program. It is only here for testing and debugging.
72710 ** On the other hand, it does burn CPU cycles every time through
72711 ** the evaluator loop. So we can leave it out when NDEBUG is defined.
72713 #ifndef NDEBUG
72714 assert( pc>=-1 && pc<p->nOp );
72716 #ifdef SQLITE_DEBUG
72717 if( db->flags & SQLITE_VdbeTrace ){
72718 if( rc!=0 ) printf("rc=%d\n",rc);
72719 if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
72720 registerTrace(pOp->p2, &aMem[pOp->p2]);
72722 if( pOp->opflags & OPFLG_OUT3 ){
72723 registerTrace(pOp->p3, &aMem[pOp->p3]);
72726 #endif /* SQLITE_DEBUG */
72727 #endif /* NDEBUG */
72728 } /* The end of the for(;;) loop the loops through opcodes */
72730 /* If we reach this point, it means that execution is finished with
72731 ** an error of some kind.
72733 vdbe_error_halt:
72734 assert( rc );
72735 p->rc = rc;
72736 testcase( sqlite3GlobalConfig.xLog!=0 );
72737 sqlite3_log(rc, "statement aborts at %d: [%s] %s",
72738 pc, p->zSql, p->zErrMsg);
72739 sqlite3VdbeHalt(p);
72740 if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
72741 rc = SQLITE_ERROR;
72742 if( resetSchemaOnFault>0 ){
72743 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
72746 /* This is the only way out of this procedure. We have to
72747 ** release the mutexes on btrees that were acquired at the
72748 ** top. */
72749 vdbe_return:
72750 db->lastRowid = lastRowid;
72751 testcase( nVmStep>0 );
72752 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
72753 sqlite3VdbeLeave(p);
72754 return rc;
72756 /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
72757 ** is encountered.
72759 too_big:
72760 sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
72761 rc = SQLITE_TOOBIG;
72762 goto vdbe_error_halt;
72764 /* Jump to here if a malloc() fails.
72766 no_mem:
72767 db->mallocFailed = 1;
72768 sqlite3SetString(&p->zErrMsg, db, "out of memory");
72769 rc = SQLITE_NOMEM;
72770 goto vdbe_error_halt;
72772 /* Jump to here for any other kind of fatal error. The "rc" variable
72773 ** should hold the error number.
72775 abort_due_to_error:
72776 assert( p->zErrMsg==0 );
72777 if( db->mallocFailed ) rc = SQLITE_NOMEM;
72778 if( rc!=SQLITE_IOERR_NOMEM ){
72779 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
72781 goto vdbe_error_halt;
72783 /* Jump to here if the sqlite3_interrupt() API sets the interrupt
72784 ** flag.
72786 abort_due_to_interrupt:
72787 assert( db->u1.isInterrupted );
72788 rc = SQLITE_INTERRUPT;
72789 p->rc = rc;
72790 sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
72791 goto vdbe_error_halt;
72795 /************** End of vdbe.c ************************************************/
72796 /************** Begin file vdbeblob.c ****************************************/
72798 ** 2007 May 1
72800 ** The author disclaims copyright to this source code. In place of
72801 ** a legal notice, here is a blessing:
72803 ** May you do good and not evil.
72804 ** May you find forgiveness for yourself and forgive others.
72805 ** May you share freely, never taking more than you give.
72807 *************************************************************************
72809 ** This file contains code used to implement incremental BLOB I/O.
72813 #ifndef SQLITE_OMIT_INCRBLOB
72816 ** Valid sqlite3_blob* handles point to Incrblob structures.
72818 typedef struct Incrblob Incrblob;
72819 struct Incrblob {
72820 int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
72821 int nByte; /* Size of open blob, in bytes */
72822 int iOffset; /* Byte offset of blob in cursor data */
72823 int iCol; /* Table column this handle is open on */
72824 BtCursor *pCsr; /* Cursor pointing at blob row */
72825 sqlite3_stmt *pStmt; /* Statement holding cursor open */
72826 sqlite3 *db; /* The associated database */
72831 ** This function is used by both blob_open() and blob_reopen(). It seeks
72832 ** the b-tree cursor associated with blob handle p to point to row iRow.
72833 ** If successful, SQLITE_OK is returned and subsequent calls to
72834 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
72836 ** If an error occurs, or if the specified row does not exist or does not
72837 ** contain a value of type TEXT or BLOB in the column nominated when the
72838 ** blob handle was opened, then an error code is returned and *pzErr may
72839 ** be set to point to a buffer containing an error message. It is the
72840 ** responsibility of the caller to free the error message buffer using
72841 ** sqlite3DbFree().
72843 ** If an error does occur, then the b-tree cursor is closed. All subsequent
72844 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
72845 ** immediately return SQLITE_ABORT.
72847 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
72848 int rc; /* Error code */
72849 char *zErr = 0; /* Error message */
72850 Vdbe *v = (Vdbe *)p->pStmt;
72852 /* Set the value of the SQL statements only variable to integer iRow.
72853 ** This is done directly instead of using sqlite3_bind_int64() to avoid
72854 ** triggering asserts related to mutexes.
72856 assert( v->aVar[0].flags&MEM_Int );
72857 v->aVar[0].u.i = iRow;
72859 rc = sqlite3_step(p->pStmt);
72860 if( rc==SQLITE_ROW ){
72861 VdbeCursor *pC = v->apCsr[0];
72862 u32 type = pC->aType[p->iCol];
72863 if( type<12 ){
72864 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
72865 type==0?"null": type==7?"real": "integer"
72867 rc = SQLITE_ERROR;
72868 sqlite3_finalize(p->pStmt);
72869 p->pStmt = 0;
72870 }else{
72871 p->iOffset = pC->aType[p->iCol + pC->nField];
72872 p->nByte = sqlite3VdbeSerialTypeLen(type);
72873 p->pCsr = pC->pCursor;
72874 sqlite3BtreeEnterCursor(p->pCsr);
72875 sqlite3BtreeCacheOverflow(p->pCsr);
72876 sqlite3BtreeLeaveCursor(p->pCsr);
72880 if( rc==SQLITE_ROW ){
72881 rc = SQLITE_OK;
72882 }else if( p->pStmt ){
72883 rc = sqlite3_finalize(p->pStmt);
72884 p->pStmt = 0;
72885 if( rc==SQLITE_OK ){
72886 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
72887 rc = SQLITE_ERROR;
72888 }else{
72889 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
72893 assert( rc!=SQLITE_OK || zErr==0 );
72894 assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
72896 *pzErr = zErr;
72897 return rc;
72901 ** Open a blob handle.
72903 SQLITE_API int sqlite3_blob_open(
72904 sqlite3* db, /* The database connection */
72905 const char *zDb, /* The attached database containing the blob */
72906 const char *zTable, /* The table containing the blob */
72907 const char *zColumn, /* The column containing the blob */
72908 sqlite_int64 iRow, /* The row containing the glob */
72909 int flags, /* True -> read/write access, false -> read-only */
72910 sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
72912 int nAttempt = 0;
72913 int iCol; /* Index of zColumn in row-record */
72915 /* This VDBE program seeks a btree cursor to the identified
72916 ** db/table/row entry. The reason for using a vdbe program instead
72917 ** of writing code to use the b-tree layer directly is that the
72918 ** vdbe program will take advantage of the various transaction,
72919 ** locking and error handling infrastructure built into the vdbe.
72921 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
72922 ** Code external to the Vdbe then "borrows" the b-tree cursor and
72923 ** uses it to implement the blob_read(), blob_write() and
72924 ** blob_bytes() functions.
72926 ** The sqlite3_blob_close() function finalizes the vdbe program,
72927 ** which closes the b-tree cursor and (possibly) commits the
72928 ** transaction.
72930 static const VdbeOpList openBlob[] = {
72931 {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
72932 {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
72933 {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
72935 /* One of the following two instructions is replaced by an OP_Noop. */
72936 {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
72937 {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
72939 {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
72940 {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
72941 {OP_Column, 0, 0, 1}, /* 7 */
72942 {OP_ResultRow, 1, 0, 0}, /* 8 */
72943 {OP_Goto, 0, 5, 0}, /* 9 */
72944 {OP_Close, 0, 0, 0}, /* 10 */
72945 {OP_Halt, 0, 0, 0}, /* 11 */
72948 int rc = SQLITE_OK;
72949 char *zErr = 0;
72950 Table *pTab;
72951 Parse *pParse = 0;
72952 Incrblob *pBlob = 0;
72954 flags = !!flags; /* flags = (flags ? 1 : 0); */
72955 *ppBlob = 0;
72957 sqlite3_mutex_enter(db->mutex);
72959 pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
72960 if( !pBlob ) goto blob_open_out;
72961 pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
72962 if( !pParse ) goto blob_open_out;
72964 do {
72965 memset(pParse, 0, sizeof(Parse));
72966 pParse->db = db;
72967 sqlite3DbFree(db, zErr);
72968 zErr = 0;
72970 sqlite3BtreeEnterAll(db);
72971 pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
72972 if( pTab && IsVirtual(pTab) ){
72973 pTab = 0;
72974 sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
72976 if( pTab && !HasRowid(pTab) ){
72977 pTab = 0;
72978 sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
72980 #ifndef SQLITE_OMIT_VIEW
72981 if( pTab && pTab->pSelect ){
72982 pTab = 0;
72983 sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
72985 #endif
72986 if( !pTab ){
72987 if( pParse->zErrMsg ){
72988 sqlite3DbFree(db, zErr);
72989 zErr = pParse->zErrMsg;
72990 pParse->zErrMsg = 0;
72992 rc = SQLITE_ERROR;
72993 sqlite3BtreeLeaveAll(db);
72994 goto blob_open_out;
72997 /* Now search pTab for the exact column. */
72998 for(iCol=0; iCol<pTab->nCol; iCol++) {
72999 if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
73000 break;
73003 if( iCol==pTab->nCol ){
73004 sqlite3DbFree(db, zErr);
73005 zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
73006 rc = SQLITE_ERROR;
73007 sqlite3BtreeLeaveAll(db);
73008 goto blob_open_out;
73011 /* If the value is being opened for writing, check that the
73012 ** column is not indexed, and that it is not part of a foreign key.
73013 ** It is against the rules to open a column to which either of these
73014 ** descriptions applies for writing. */
73015 if( flags ){
73016 const char *zFault = 0;
73017 Index *pIdx;
73018 #ifndef SQLITE_OMIT_FOREIGN_KEY
73019 if( db->flags&SQLITE_ForeignKeys ){
73020 /* Check that the column is not part of an FK child key definition. It
73021 ** is not necessary to check if it is part of a parent key, as parent
73022 ** key columns must be indexed. The check below will pick up this
73023 ** case. */
73024 FKey *pFKey;
73025 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
73026 int j;
73027 for(j=0; j<pFKey->nCol; j++){
73028 if( pFKey->aCol[j].iFrom==iCol ){
73029 zFault = "foreign key";
73034 #endif
73035 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
73036 int j;
73037 for(j=0; j<pIdx->nKeyCol; j++){
73038 if( pIdx->aiColumn[j]==iCol ){
73039 zFault = "indexed";
73043 if( zFault ){
73044 sqlite3DbFree(db, zErr);
73045 zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
73046 rc = SQLITE_ERROR;
73047 sqlite3BtreeLeaveAll(db);
73048 goto blob_open_out;
73052 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
73053 assert( pBlob->pStmt || db->mallocFailed );
73054 if( pBlob->pStmt ){
73055 Vdbe *v = (Vdbe *)pBlob->pStmt;
73056 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73058 sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
73061 /* Configure the OP_Transaction */
73062 sqlite3VdbeChangeP1(v, 0, iDb);
73063 sqlite3VdbeChangeP2(v, 0, flags);
73065 /* Configure the OP_VerifyCookie */
73066 sqlite3VdbeChangeP1(v, 1, iDb);
73067 sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
73068 sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
73070 /* Make sure a mutex is held on the table to be accessed */
73071 sqlite3VdbeUsesBtree(v, iDb);
73073 /* Configure the OP_TableLock instruction */
73074 #ifdef SQLITE_OMIT_SHARED_CACHE
73075 sqlite3VdbeChangeToNoop(v, 2);
73076 #else
73077 sqlite3VdbeChangeP1(v, 2, iDb);
73078 sqlite3VdbeChangeP2(v, 2, pTab->tnum);
73079 sqlite3VdbeChangeP3(v, 2, flags);
73080 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
73081 #endif
73083 /* Remove either the OP_OpenWrite or OpenRead. Set the P2
73084 ** parameter of the other to pTab->tnum. */
73085 sqlite3VdbeChangeToNoop(v, 4 - flags);
73086 sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
73087 sqlite3VdbeChangeP3(v, 3 + flags, iDb);
73089 /* Configure the number of columns. Configure the cursor to
73090 ** think that the table has one more column than it really
73091 ** does. An OP_Column to retrieve this imaginary column will
73092 ** always return an SQL NULL. This is useful because it means
73093 ** we can invoke OP_Column to fill in the vdbe cursors type
73094 ** and offset cache without causing any IO.
73096 sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
73097 sqlite3VdbeChangeP2(v, 7, pTab->nCol);
73098 if( !db->mallocFailed ){
73099 pParse->nVar = 1;
73100 pParse->nMem = 1;
73101 pParse->nTab = 1;
73102 sqlite3VdbeMakeReady(v, pParse);
73106 pBlob->flags = flags;
73107 pBlob->iCol = iCol;
73108 pBlob->db = db;
73109 sqlite3BtreeLeaveAll(db);
73110 if( db->mallocFailed ){
73111 goto blob_open_out;
73113 sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
73114 rc = blobSeekToRow(pBlob, iRow, &zErr);
73115 } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
73117 blob_open_out:
73118 if( rc==SQLITE_OK && db->mallocFailed==0 ){
73119 *ppBlob = (sqlite3_blob *)pBlob;
73120 }else{
73121 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
73122 sqlite3DbFree(db, pBlob);
73124 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
73125 sqlite3DbFree(db, zErr);
73126 sqlite3ParserReset(pParse);
73127 sqlite3StackFree(db, pParse);
73128 rc = sqlite3ApiExit(db, rc);
73129 sqlite3_mutex_leave(db->mutex);
73130 return rc;
73134 ** Close a blob handle that was previously created using
73135 ** sqlite3_blob_open().
73137 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
73138 Incrblob *p = (Incrblob *)pBlob;
73139 int rc;
73140 sqlite3 *db;
73142 if( p ){
73143 db = p->db;
73144 sqlite3_mutex_enter(db->mutex);
73145 rc = sqlite3_finalize(p->pStmt);
73146 sqlite3DbFree(db, p);
73147 sqlite3_mutex_leave(db->mutex);
73148 }else{
73149 rc = SQLITE_OK;
73151 return rc;
73155 ** Perform a read or write operation on a blob
73157 static int blobReadWrite(
73158 sqlite3_blob *pBlob,
73159 void *z,
73160 int n,
73161 int iOffset,
73162 int (*xCall)(BtCursor*, u32, u32, void*)
73164 int rc;
73165 Incrblob *p = (Incrblob *)pBlob;
73166 Vdbe *v;
73167 sqlite3 *db;
73169 if( p==0 ) return SQLITE_MISUSE_BKPT;
73170 db = p->db;
73171 sqlite3_mutex_enter(db->mutex);
73172 v = (Vdbe*)p->pStmt;
73174 if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
73175 /* Request is out of range. Return a transient error. */
73176 rc = SQLITE_ERROR;
73177 sqlite3Error(db, SQLITE_ERROR, 0);
73178 }else if( v==0 ){
73179 /* If there is no statement handle, then the blob-handle has
73180 ** already been invalidated. Return SQLITE_ABORT in this case.
73182 rc = SQLITE_ABORT;
73183 }else{
73184 /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
73185 ** returned, clean-up the statement handle.
73187 assert( db == v->db );
73188 sqlite3BtreeEnterCursor(p->pCsr);
73189 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
73190 sqlite3BtreeLeaveCursor(p->pCsr);
73191 if( rc==SQLITE_ABORT ){
73192 sqlite3VdbeFinalize(v);
73193 p->pStmt = 0;
73194 }else{
73195 db->errCode = rc;
73196 v->rc = rc;
73199 rc = sqlite3ApiExit(db, rc);
73200 sqlite3_mutex_leave(db->mutex);
73201 return rc;
73205 ** Read data from a blob handle.
73207 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
73208 return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
73212 ** Write data to a blob handle.
73214 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
73215 return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
73219 ** Query a blob handle for the size of the data.
73221 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
73222 ** so no mutex is required for access.
73224 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
73225 Incrblob *p = (Incrblob *)pBlob;
73226 return (p && p->pStmt) ? p->nByte : 0;
73230 ** Move an existing blob handle to point to a different row of the same
73231 ** database table.
73233 ** If an error occurs, or if the specified row does not exist or does not
73234 ** contain a blob or text value, then an error code is returned and the
73235 ** database handle error code and message set. If this happens, then all
73236 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
73237 ** immediately return SQLITE_ABORT.
73239 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
73240 int rc;
73241 Incrblob *p = (Incrblob *)pBlob;
73242 sqlite3 *db;
73244 if( p==0 ) return SQLITE_MISUSE_BKPT;
73245 db = p->db;
73246 sqlite3_mutex_enter(db->mutex);
73248 if( p->pStmt==0 ){
73249 /* If there is no statement handle, then the blob-handle has
73250 ** already been invalidated. Return SQLITE_ABORT in this case.
73252 rc = SQLITE_ABORT;
73253 }else{
73254 char *zErr;
73255 rc = blobSeekToRow(p, iRow, &zErr);
73256 if( rc!=SQLITE_OK ){
73257 sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
73258 sqlite3DbFree(db, zErr);
73260 assert( rc!=SQLITE_SCHEMA );
73263 rc = sqlite3ApiExit(db, rc);
73264 assert( rc==SQLITE_OK || p->pStmt==0 );
73265 sqlite3_mutex_leave(db->mutex);
73266 return rc;
73269 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
73271 /************** End of vdbeblob.c ********************************************/
73272 /************** Begin file vdbesort.c ****************************************/
73274 ** 2011 July 9
73276 ** The author disclaims copyright to this source code. In place of
73277 ** a legal notice, here is a blessing:
73279 ** May you do good and not evil.
73280 ** May you find forgiveness for yourself and forgive others.
73281 ** May you share freely, never taking more than you give.
73283 *************************************************************************
73284 ** This file contains code for the VdbeSorter object, used in concert with
73285 ** a VdbeCursor to sort large numbers of keys (as may be required, for
73286 ** example, by CREATE INDEX statements on tables too large to fit in main
73287 ** memory).
73292 typedef struct VdbeSorterIter VdbeSorterIter;
73293 typedef struct SorterRecord SorterRecord;
73294 typedef struct FileWriter FileWriter;
73297 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
73299 ** As keys are added to the sorter, they are written to disk in a series
73300 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
73301 ** the same as the cache-size allowed for temporary databases. In order
73302 ** to allow the caller to extract keys from the sorter in sorted order,
73303 ** all PMAs currently stored on disk must be merged together. This comment
73304 ** describes the data structure used to do so. The structure supports
73305 ** merging any number of arrays in a single pass with no redundant comparison
73306 ** operations.
73308 ** The aIter[] array contains an iterator for each of the PMAs being merged.
73309 ** An aIter[] iterator either points to a valid key or else is at EOF. For
73310 ** the purposes of the paragraphs below, we assume that the array is actually
73311 ** N elements in size, where N is the smallest power of 2 greater to or equal
73312 ** to the number of iterators being merged. The extra aIter[] elements are
73313 ** treated as if they are empty (always at EOF).
73315 ** The aTree[] array is also N elements in size. The value of N is stored in
73316 ** the VdbeSorter.nTree variable.
73318 ** The final (N/2) elements of aTree[] contain the results of comparing
73319 ** pairs of iterator keys together. Element i contains the result of
73320 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
73321 ** aTree element is set to the index of it.
73323 ** For the purposes of this comparison, EOF is considered greater than any
73324 ** other key value. If the keys are equal (only possible with two EOF
73325 ** values), it doesn't matter which index is stored.
73327 ** The (N/4) elements of aTree[] that precede the final (N/2) described
73328 ** above contains the index of the smallest of each block of 4 iterators.
73329 ** And so on. So that aTree[1] contains the index of the iterator that
73330 ** currently points to the smallest key value. aTree[0] is unused.
73332 ** Example:
73334 ** aIter[0] -> Banana
73335 ** aIter[1] -> Feijoa
73336 ** aIter[2] -> Elderberry
73337 ** aIter[3] -> Currant
73338 ** aIter[4] -> Grapefruit
73339 ** aIter[5] -> Apple
73340 ** aIter[6] -> Durian
73341 ** aIter[7] -> EOF
73343 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
73345 ** The current element is "Apple" (the value of the key indicated by
73346 ** iterator 5). When the Next() operation is invoked, iterator 5 will
73347 ** be advanced to the next key in its segment. Say the next key is
73348 ** "Eggplant":
73350 ** aIter[5] -> Eggplant
73352 ** The contents of aTree[] are updated first by comparing the new iterator
73353 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
73354 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
73355 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
73356 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
73357 ** so the value written into element 1 of the array is 0. As follows:
73359 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
73361 ** In other words, each time we advance to the next sorter element, log2(N)
73362 ** key comparison operations are required, where N is the number of segments
73363 ** being merged (rounded up to the next power of 2).
73365 struct VdbeSorter {
73366 i64 iWriteOff; /* Current write offset within file pTemp1 */
73367 i64 iReadOff; /* Current read offset within file pTemp1 */
73368 int nInMemory; /* Current size of pRecord list as PMA */
73369 int nTree; /* Used size of aTree/aIter (power of 2) */
73370 int nPMA; /* Number of PMAs stored in pTemp1 */
73371 int mnPmaSize; /* Minimum PMA size, in bytes */
73372 int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
73373 VdbeSorterIter *aIter; /* Array of iterators to merge */
73374 int *aTree; /* Current state of incremental merge */
73375 sqlite3_file *pTemp1; /* PMA file 1 */
73376 SorterRecord *pRecord; /* Head of in-memory record list */
73377 UnpackedRecord *pUnpacked; /* Used to unpack keys */
73381 ** The following type is an iterator for a PMA. It caches the current key in
73382 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
73384 struct VdbeSorterIter {
73385 i64 iReadOff; /* Current read offset */
73386 i64 iEof; /* 1 byte past EOF for this iterator */
73387 int nAlloc; /* Bytes of space at aAlloc */
73388 int nKey; /* Number of bytes in key */
73389 sqlite3_file *pFile; /* File iterator is reading from */
73390 u8 *aAlloc; /* Allocated space */
73391 u8 *aKey; /* Pointer to current key */
73392 u8 *aBuffer; /* Current read buffer */
73393 int nBuffer; /* Size of read buffer in bytes */
73397 ** An instance of this structure is used to organize the stream of records
73398 ** being written to files by the merge-sort code into aligned, page-sized
73399 ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
73400 ** faster on many operating systems.
73402 struct FileWriter {
73403 int eFWErr; /* Non-zero if in an error state */
73404 u8 *aBuffer; /* Pointer to write buffer */
73405 int nBuffer; /* Size of write buffer in bytes */
73406 int iBufStart; /* First byte of buffer to write */
73407 int iBufEnd; /* Last byte of buffer to write */
73408 i64 iWriteOff; /* Offset of start of buffer in file */
73409 sqlite3_file *pFile; /* File to write to */
73413 ** A structure to store a single record. All in-memory records are connected
73414 ** together into a linked list headed at VdbeSorter.pRecord using the
73415 ** SorterRecord.pNext pointer.
73417 struct SorterRecord {
73418 void *pVal;
73419 int nVal;
73420 SorterRecord *pNext;
73423 /* Minimum allowable value for the VdbeSorter.nWorking variable */
73424 #define SORTER_MIN_WORKING 10
73426 /* Maximum number of segments to merge in a single pass. */
73427 #define SORTER_MAX_MERGE_COUNT 16
73430 ** Free all memory belonging to the VdbeSorterIter object passed as the second
73431 ** argument. All structure fields are set to zero before returning.
73433 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
73434 sqlite3DbFree(db, pIter->aAlloc);
73435 sqlite3DbFree(db, pIter->aBuffer);
73436 memset(pIter, 0, sizeof(VdbeSorterIter));
73440 ** Read nByte bytes of data from the stream of data iterated by object p.
73441 ** If successful, set *ppOut to point to a buffer containing the data
73442 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
73443 ** error code.
73445 ** The buffer indicated by *ppOut may only be considered valid until the
73446 ** next call to this function.
73448 static int vdbeSorterIterRead(
73449 sqlite3 *db, /* Database handle (for malloc) */
73450 VdbeSorterIter *p, /* Iterator */
73451 int nByte, /* Bytes of data to read */
73452 u8 **ppOut /* OUT: Pointer to buffer containing data */
73454 int iBuf; /* Offset within buffer to read from */
73455 int nAvail; /* Bytes of data available in buffer */
73456 assert( p->aBuffer );
73458 /* If there is no more data to be read from the buffer, read the next
73459 ** p->nBuffer bytes of data from the file into it. Or, if there are less
73460 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
73461 iBuf = p->iReadOff % p->nBuffer;
73462 if( iBuf==0 ){
73463 int nRead; /* Bytes to read from disk */
73464 int rc; /* sqlite3OsRead() return code */
73466 /* Determine how many bytes of data to read. */
73467 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
73468 nRead = p->nBuffer;
73469 }else{
73470 nRead = (int)(p->iEof - p->iReadOff);
73472 assert( nRead>0 );
73474 /* Read data from the file. Return early if an error occurs. */
73475 rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
73476 assert( rc!=SQLITE_IOERR_SHORT_READ );
73477 if( rc!=SQLITE_OK ) return rc;
73479 nAvail = p->nBuffer - iBuf;
73481 if( nByte<=nAvail ){
73482 /* The requested data is available in the in-memory buffer. In this
73483 ** case there is no need to make a copy of the data, just return a
73484 ** pointer into the buffer to the caller. */
73485 *ppOut = &p->aBuffer[iBuf];
73486 p->iReadOff += nByte;
73487 }else{
73488 /* The requested data is not all available in the in-memory buffer.
73489 ** In this case, allocate space at p->aAlloc[] to copy the requested
73490 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
73491 int nRem; /* Bytes remaining to copy */
73493 /* Extend the p->aAlloc[] allocation if required. */
73494 if( p->nAlloc<nByte ){
73495 int nNew = p->nAlloc*2;
73496 while( nByte>nNew ) nNew = nNew*2;
73497 p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
73498 if( !p->aAlloc ) return SQLITE_NOMEM;
73499 p->nAlloc = nNew;
73502 /* Copy as much data as is available in the buffer into the start of
73503 ** p->aAlloc[]. */
73504 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
73505 p->iReadOff += nAvail;
73506 nRem = nByte - nAvail;
73508 /* The following loop copies up to p->nBuffer bytes per iteration into
73509 ** the p->aAlloc[] buffer. */
73510 while( nRem>0 ){
73511 int rc; /* vdbeSorterIterRead() return code */
73512 int nCopy; /* Number of bytes to copy */
73513 u8 *aNext; /* Pointer to buffer to copy data from */
73515 nCopy = nRem;
73516 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
73517 rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
73518 if( rc!=SQLITE_OK ) return rc;
73519 assert( aNext!=p->aAlloc );
73520 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
73521 nRem -= nCopy;
73524 *ppOut = p->aAlloc;
73527 return SQLITE_OK;
73531 ** Read a varint from the stream of data accessed by p. Set *pnOut to
73532 ** the value read.
73534 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
73535 int iBuf;
73537 iBuf = p->iReadOff % p->nBuffer;
73538 if( iBuf && (p->nBuffer-iBuf)>=9 ){
73539 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
73540 }else{
73541 u8 aVarint[16], *a;
73542 int i = 0, rc;
73544 rc = vdbeSorterIterRead(db, p, 1, &a);
73545 if( rc ) return rc;
73546 aVarint[(i++)&0xf] = a[0];
73547 }while( (a[0]&0x80)!=0 );
73548 sqlite3GetVarint(aVarint, pnOut);
73551 return SQLITE_OK;
73556 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
73557 ** no error occurs, or an SQLite error code if one does.
73559 static int vdbeSorterIterNext(
73560 sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
73561 VdbeSorterIter *pIter /* Iterator to advance */
73563 int rc; /* Return Code */
73564 u64 nRec = 0; /* Size of record in bytes */
73566 if( pIter->iReadOff>=pIter->iEof ){
73567 /* This is an EOF condition */
73568 vdbeSorterIterZero(db, pIter);
73569 return SQLITE_OK;
73572 rc = vdbeSorterIterVarint(db, pIter, &nRec);
73573 if( rc==SQLITE_OK ){
73574 pIter->nKey = (int)nRec;
73575 rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
73578 return rc;
73582 ** Initialize iterator pIter to scan through the PMA stored in file pFile
73583 ** starting at offset iStart and ending at offset iEof-1. This function
73584 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
73585 ** PMA is empty).
73587 static int vdbeSorterIterInit(
73588 sqlite3 *db, /* Database handle */
73589 const VdbeSorter *pSorter, /* Sorter object */
73590 i64 iStart, /* Start offset in pFile */
73591 VdbeSorterIter *pIter, /* Iterator to populate */
73592 i64 *pnByte /* IN/OUT: Increment this value by PMA size */
73594 int rc = SQLITE_OK;
73595 int nBuf;
73597 nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
73599 assert( pSorter->iWriteOff>iStart );
73600 assert( pIter->aAlloc==0 );
73601 assert( pIter->aBuffer==0 );
73602 pIter->pFile = pSorter->pTemp1;
73603 pIter->iReadOff = iStart;
73604 pIter->nAlloc = 128;
73605 pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
73606 pIter->nBuffer = nBuf;
73607 pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
73609 if( !pIter->aBuffer ){
73610 rc = SQLITE_NOMEM;
73611 }else{
73612 int iBuf;
73614 iBuf = iStart % nBuf;
73615 if( iBuf ){
73616 int nRead = nBuf - iBuf;
73617 if( (iStart + nRead) > pSorter->iWriteOff ){
73618 nRead = (int)(pSorter->iWriteOff - iStart);
73620 rc = sqlite3OsRead(
73621 pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
73623 assert( rc!=SQLITE_IOERR_SHORT_READ );
73626 if( rc==SQLITE_OK ){
73627 u64 nByte; /* Size of PMA in bytes */
73628 pIter->iEof = pSorter->iWriteOff;
73629 rc = vdbeSorterIterVarint(db, pIter, &nByte);
73630 pIter->iEof = pIter->iReadOff + nByte;
73631 *pnByte += nByte;
73635 if( rc==SQLITE_OK ){
73636 rc = vdbeSorterIterNext(db, pIter);
73638 return rc;
73643 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
73644 ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
73645 ** used by the comparison. If an error occurs, return an SQLite error code.
73646 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
73647 ** value, depending on whether key1 is smaller, equal to or larger than key2.
73649 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
73650 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
73651 ** is true and key1 contains even a single NULL value, it is considered to
73652 ** be less than key2. Even if key2 also contains NULL values.
73654 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
73655 ** has been allocated and contains an unpacked record that is used as key2.
73657 static void vdbeSorterCompare(
73658 const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
73659 int nIgnore, /* Ignore the last nIgnore fields */
73660 const void *pKey1, int nKey1, /* Left side of comparison */
73661 const void *pKey2, int nKey2, /* Right side of comparison */
73662 int *pRes /* OUT: Result of comparison */
73664 KeyInfo *pKeyInfo = pCsr->pKeyInfo;
73665 VdbeSorter *pSorter = pCsr->pSorter;
73666 UnpackedRecord *r2 = pSorter->pUnpacked;
73667 int i;
73669 if( pKey2 ){
73670 sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
73673 if( nIgnore ){
73674 r2->nField = pKeyInfo->nField - nIgnore;
73675 assert( r2->nField>0 );
73676 for(i=0; i<r2->nField; i++){
73677 if( r2->aMem[i].flags & MEM_Null ){
73678 *pRes = -1;
73679 return;
73682 r2->flags |= UNPACKED_PREFIX_MATCH;
73685 *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
73689 ** This function is called to compare two iterator keys when merging
73690 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
73691 ** value to recalculate.
73693 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
73694 VdbeSorter *pSorter = pCsr->pSorter;
73695 int i1;
73696 int i2;
73697 int iRes;
73698 VdbeSorterIter *p1;
73699 VdbeSorterIter *p2;
73701 assert( iOut<pSorter->nTree && iOut>0 );
73703 if( iOut>=(pSorter->nTree/2) ){
73704 i1 = (iOut - pSorter->nTree/2) * 2;
73705 i2 = i1 + 1;
73706 }else{
73707 i1 = pSorter->aTree[iOut*2];
73708 i2 = pSorter->aTree[iOut*2+1];
73711 p1 = &pSorter->aIter[i1];
73712 p2 = &pSorter->aIter[i2];
73714 if( p1->pFile==0 ){
73715 iRes = i2;
73716 }else if( p2->pFile==0 ){
73717 iRes = i1;
73718 }else{
73719 int res;
73720 assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
73721 vdbeSorterCompare(
73722 pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
73724 if( res<=0 ){
73725 iRes = i1;
73726 }else{
73727 iRes = i2;
73731 pSorter->aTree[iOut] = iRes;
73732 return SQLITE_OK;
73736 ** Initialize the temporary index cursor just opened as a sorter cursor.
73738 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
73739 int pgsz; /* Page size of main database */
73740 int mxCache; /* Cache size */
73741 VdbeSorter *pSorter; /* The new sorter */
73742 char *d; /* Dummy */
73744 assert( pCsr->pKeyInfo && pCsr->pBt==0 );
73745 pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
73746 if( pSorter==0 ){
73747 return SQLITE_NOMEM;
73750 pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
73751 if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
73752 assert( pSorter->pUnpacked==(UnpackedRecord *)d );
73754 if( !sqlite3TempInMemory(db) ){
73755 pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
73756 pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
73757 mxCache = db->aDb[0].pSchema->cache_size;
73758 if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
73759 pSorter->mxPmaSize = mxCache * pgsz;
73762 return SQLITE_OK;
73766 ** Free the list of sorted records starting at pRecord.
73768 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
73769 SorterRecord *p;
73770 SorterRecord *pNext;
73771 for(p=pRecord; p; p=pNext){
73772 pNext = p->pNext;
73773 sqlite3DbFree(db, p);
73778 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
73780 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
73781 VdbeSorter *pSorter = pCsr->pSorter;
73782 if( pSorter ){
73783 if( pSorter->aIter ){
73784 int i;
73785 for(i=0; i<pSorter->nTree; i++){
73786 vdbeSorterIterZero(db, &pSorter->aIter[i]);
73788 sqlite3DbFree(db, pSorter->aIter);
73790 if( pSorter->pTemp1 ){
73791 sqlite3OsCloseFree(pSorter->pTemp1);
73793 vdbeSorterRecordFree(db, pSorter->pRecord);
73794 sqlite3DbFree(db, pSorter->pUnpacked);
73795 sqlite3DbFree(db, pSorter);
73796 pCsr->pSorter = 0;
73801 ** Allocate space for a file-handle and open a temporary file. If successful,
73802 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
73803 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
73805 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
73806 int dummy;
73807 return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
73808 SQLITE_OPEN_TEMP_JOURNAL |
73809 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
73810 SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
73815 ** Merge the two sorted lists p1 and p2 into a single list.
73816 ** Set *ppOut to the head of the new list.
73818 static void vdbeSorterMerge(
73819 const VdbeCursor *pCsr, /* For pKeyInfo */
73820 SorterRecord *p1, /* First list to merge */
73821 SorterRecord *p2, /* Second list to merge */
73822 SorterRecord **ppOut /* OUT: Head of merged list */
73824 SorterRecord *pFinal = 0;
73825 SorterRecord **pp = &pFinal;
73826 void *pVal2 = p2 ? p2->pVal : 0;
73828 while( p1 && p2 ){
73829 int res;
73830 vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
73831 if( res<=0 ){
73832 *pp = p1;
73833 pp = &p1->pNext;
73834 p1 = p1->pNext;
73835 pVal2 = 0;
73836 }else{
73837 *pp = p2;
73838 pp = &p2->pNext;
73839 p2 = p2->pNext;
73840 if( p2==0 ) break;
73841 pVal2 = p2->pVal;
73844 *pp = p1 ? p1 : p2;
73845 *ppOut = pFinal;
73849 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
73850 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
73851 ** occurs.
73853 static int vdbeSorterSort(const VdbeCursor *pCsr){
73854 int i;
73855 SorterRecord **aSlot;
73856 SorterRecord *p;
73857 VdbeSorter *pSorter = pCsr->pSorter;
73859 aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
73860 if( !aSlot ){
73861 return SQLITE_NOMEM;
73864 p = pSorter->pRecord;
73865 while( p ){
73866 SorterRecord *pNext = p->pNext;
73867 p->pNext = 0;
73868 for(i=0; aSlot[i]; i++){
73869 vdbeSorterMerge(pCsr, p, aSlot[i], &p);
73870 aSlot[i] = 0;
73872 aSlot[i] = p;
73873 p = pNext;
73876 p = 0;
73877 for(i=0; i<64; i++){
73878 vdbeSorterMerge(pCsr, p, aSlot[i], &p);
73880 pSorter->pRecord = p;
73882 sqlite3_free(aSlot);
73883 return SQLITE_OK;
73887 ** Initialize a file-writer object.
73889 static void fileWriterInit(
73890 sqlite3 *db, /* Database (for malloc) */
73891 sqlite3_file *pFile, /* File to write to */
73892 FileWriter *p, /* Object to populate */
73893 i64 iStart /* Offset of pFile to begin writing at */
73895 int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
73897 memset(p, 0, sizeof(FileWriter));
73898 p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
73899 if( !p->aBuffer ){
73900 p->eFWErr = SQLITE_NOMEM;
73901 }else{
73902 p->iBufEnd = p->iBufStart = (iStart % nBuf);
73903 p->iWriteOff = iStart - p->iBufStart;
73904 p->nBuffer = nBuf;
73905 p->pFile = pFile;
73910 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
73911 ** if successful, or an SQLite error code if an error occurs.
73913 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
73914 int nRem = nData;
73915 while( nRem>0 && p->eFWErr==0 ){
73916 int nCopy = nRem;
73917 if( nCopy>(p->nBuffer - p->iBufEnd) ){
73918 nCopy = p->nBuffer - p->iBufEnd;
73921 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
73922 p->iBufEnd += nCopy;
73923 if( p->iBufEnd==p->nBuffer ){
73924 p->eFWErr = sqlite3OsWrite(p->pFile,
73925 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
73926 p->iWriteOff + p->iBufStart
73928 p->iBufStart = p->iBufEnd = 0;
73929 p->iWriteOff += p->nBuffer;
73931 assert( p->iBufEnd<p->nBuffer );
73933 nRem -= nCopy;
73938 ** Flush any buffered data to disk and clean up the file-writer object.
73939 ** The results of using the file-writer after this call are undefined.
73940 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
73941 ** required. Otherwise, return an SQLite error code.
73943 ** Before returning, set *piEof to the offset immediately following the
73944 ** last byte written to the file.
73946 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
73947 int rc;
73948 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
73949 p->eFWErr = sqlite3OsWrite(p->pFile,
73950 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
73951 p->iWriteOff + p->iBufStart
73954 *piEof = (p->iWriteOff + p->iBufEnd);
73955 sqlite3DbFree(db, p->aBuffer);
73956 rc = p->eFWErr;
73957 memset(p, 0, sizeof(FileWriter));
73958 return rc;
73962 ** Write value iVal encoded as a varint to the file-write object. Return
73963 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
73965 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
73966 int nByte;
73967 u8 aByte[10];
73968 nByte = sqlite3PutVarint(aByte, iVal);
73969 fileWriterWrite(p, aByte, nByte);
73973 ** Write the current contents of the in-memory linked-list to a PMA. Return
73974 ** SQLITE_OK if successful, or an SQLite error code otherwise.
73976 ** The format of a PMA is:
73978 ** * A varint. This varint contains the total number of bytes of content
73979 ** in the PMA (not including the varint itself).
73981 ** * One or more records packed end-to-end in order of ascending keys.
73982 ** Each record consists of a varint followed by a blob of data (the
73983 ** key). The varint is the number of bytes in the blob of data.
73985 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
73986 int rc = SQLITE_OK; /* Return code */
73987 VdbeSorter *pSorter = pCsr->pSorter;
73988 FileWriter writer;
73990 memset(&writer, 0, sizeof(FileWriter));
73992 if( pSorter->nInMemory==0 ){
73993 assert( pSorter->pRecord==0 );
73994 return rc;
73997 rc = vdbeSorterSort(pCsr);
73999 /* If the first temporary PMA file has not been opened, open it now. */
74000 if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
74001 rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
74002 assert( rc!=SQLITE_OK || pSorter->pTemp1 );
74003 assert( pSorter->iWriteOff==0 );
74004 assert( pSorter->nPMA==0 );
74007 if( rc==SQLITE_OK ){
74008 SorterRecord *p;
74009 SorterRecord *pNext = 0;
74011 fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
74012 pSorter->nPMA++;
74013 fileWriterWriteVarint(&writer, pSorter->nInMemory);
74014 for(p=pSorter->pRecord; p; p=pNext){
74015 pNext = p->pNext;
74016 fileWriterWriteVarint(&writer, p->nVal);
74017 fileWriterWrite(&writer, p->pVal, p->nVal);
74018 sqlite3DbFree(db, p);
74020 pSorter->pRecord = p;
74021 rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
74024 return rc;
74028 ** Add a record to the sorter.
74030 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
74031 sqlite3 *db, /* Database handle */
74032 const VdbeCursor *pCsr, /* Sorter cursor */
74033 Mem *pVal /* Memory cell containing record */
74035 VdbeSorter *pSorter = pCsr->pSorter;
74036 int rc = SQLITE_OK; /* Return Code */
74037 SorterRecord *pNew; /* New list element */
74039 assert( pSorter );
74040 pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
74042 pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
74043 if( pNew==0 ){
74044 rc = SQLITE_NOMEM;
74045 }else{
74046 pNew->pVal = (void *)&pNew[1];
74047 memcpy(pNew->pVal, pVal->z, pVal->n);
74048 pNew->nVal = pVal->n;
74049 pNew->pNext = pSorter->pRecord;
74050 pSorter->pRecord = pNew;
74053 /* See if the contents of the sorter should now be written out. They
74054 ** are written out when either of the following are true:
74056 ** * The total memory allocated for the in-memory list is greater
74057 ** than (page-size * cache-size), or
74059 ** * The total memory allocated for the in-memory list is greater
74060 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
74062 if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
74063 (pSorter->nInMemory>pSorter->mxPmaSize)
74064 || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
74066 #ifdef SQLITE_DEBUG
74067 i64 nExpect = pSorter->iWriteOff
74068 + sqlite3VarintLen(pSorter->nInMemory)
74069 + pSorter->nInMemory;
74070 #endif
74071 rc = vdbeSorterListToPMA(db, pCsr);
74072 pSorter->nInMemory = 0;
74073 assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
74076 return rc;
74080 ** Helper function for sqlite3VdbeSorterRewind().
74082 static int vdbeSorterInitMerge(
74083 sqlite3 *db, /* Database handle */
74084 const VdbeCursor *pCsr, /* Cursor handle for this sorter */
74085 i64 *pnByte /* Sum of bytes in all opened PMAs */
74087 VdbeSorter *pSorter = pCsr->pSorter;
74088 int rc = SQLITE_OK; /* Return code */
74089 int i; /* Used to iterator through aIter[] */
74090 i64 nByte = 0; /* Total bytes in all opened PMAs */
74092 /* Initialize the iterators. */
74093 for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
74094 VdbeSorterIter *pIter = &pSorter->aIter[i];
74095 rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
74096 pSorter->iReadOff = pIter->iEof;
74097 assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
74098 if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
74101 /* Initialize the aTree[] array. */
74102 for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
74103 rc = vdbeSorterDoCompare(pCsr, i);
74106 *pnByte = nByte;
74107 return rc;
74111 ** Once the sorter has been populated, this function is called to prepare
74112 ** for iterating through its contents in sorted order.
74114 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
74115 VdbeSorter *pSorter = pCsr->pSorter;
74116 int rc; /* Return code */
74117 sqlite3_file *pTemp2 = 0; /* Second temp file to use */
74118 i64 iWrite2 = 0; /* Write offset for pTemp2 */
74119 int nIter; /* Number of iterators used */
74120 int nByte; /* Bytes of space required for aIter/aTree */
74121 int N = 2; /* Power of 2 >= nIter */
74123 assert( pSorter );
74125 /* If no data has been written to disk, then do not do so now. Instead,
74126 ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
74127 ** from the in-memory list. */
74128 if( pSorter->nPMA==0 ){
74129 *pbEof = !pSorter->pRecord;
74130 assert( pSorter->aTree==0 );
74131 return vdbeSorterSort(pCsr);
74134 /* Write the current in-memory list to a PMA. */
74135 rc = vdbeSorterListToPMA(db, pCsr);
74136 if( rc!=SQLITE_OK ) return rc;
74138 /* Allocate space for aIter[] and aTree[]. */
74139 nIter = pSorter->nPMA;
74140 if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
74141 assert( nIter>0 );
74142 while( N<nIter ) N += N;
74143 nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
74144 pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
74145 if( !pSorter->aIter ) return SQLITE_NOMEM;
74146 pSorter->aTree = (int *)&pSorter->aIter[N];
74147 pSorter->nTree = N;
74149 do {
74150 int iNew; /* Index of new, merged, PMA */
74152 for(iNew=0;
74153 rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
74154 iNew++
74156 int rc2; /* Return code from fileWriterFinish() */
74157 FileWriter writer; /* Object used to write to disk */
74158 i64 nWrite; /* Number of bytes in new PMA */
74160 memset(&writer, 0, sizeof(FileWriter));
74162 /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
74163 ** initialize an iterator for each of them and break out of the loop.
74164 ** These iterators will be incrementally merged as the VDBE layer calls
74165 ** sqlite3VdbeSorterNext().
74167 ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
74168 ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
74169 ** are merged into a single PMA that is written to file pTemp2.
74171 rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
74172 assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
74173 if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
74174 break;
74177 /* Open the second temp file, if it is not already open. */
74178 if( pTemp2==0 ){
74179 assert( iWrite2==0 );
74180 rc = vdbeSorterOpenTempFile(db, &pTemp2);
74183 if( rc==SQLITE_OK ){
74184 int bEof = 0;
74185 fileWriterInit(db, pTemp2, &writer, iWrite2);
74186 fileWriterWriteVarint(&writer, nWrite);
74187 while( rc==SQLITE_OK && bEof==0 ){
74188 VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
74189 assert( pIter->pFile );
74191 fileWriterWriteVarint(&writer, pIter->nKey);
74192 fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
74193 rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
74195 rc2 = fileWriterFinish(db, &writer, &iWrite2);
74196 if( rc==SQLITE_OK ) rc = rc2;
74200 if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
74201 break;
74202 }else{
74203 sqlite3_file *pTmp = pSorter->pTemp1;
74204 pSorter->nPMA = iNew;
74205 pSorter->pTemp1 = pTemp2;
74206 pTemp2 = pTmp;
74207 pSorter->iWriteOff = iWrite2;
74208 pSorter->iReadOff = 0;
74209 iWrite2 = 0;
74211 }while( rc==SQLITE_OK );
74213 if( pTemp2 ){
74214 sqlite3OsCloseFree(pTemp2);
74216 *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
74217 return rc;
74221 ** Advance to the next element in the sorter.
74223 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
74224 VdbeSorter *pSorter = pCsr->pSorter;
74225 int rc; /* Return code */
74227 if( pSorter->aTree ){
74228 int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
74229 int i; /* Index of aTree[] to recalculate */
74231 rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
74232 for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
74233 rc = vdbeSorterDoCompare(pCsr, i);
74236 *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
74237 }else{
74238 SorterRecord *pFree = pSorter->pRecord;
74239 pSorter->pRecord = pFree->pNext;
74240 pFree->pNext = 0;
74241 vdbeSorterRecordFree(db, pFree);
74242 *pbEof = !pSorter->pRecord;
74243 rc = SQLITE_OK;
74245 return rc;
74249 ** Return a pointer to a buffer owned by the sorter that contains the
74250 ** current key.
74252 static void *vdbeSorterRowkey(
74253 const VdbeSorter *pSorter, /* Sorter object */
74254 int *pnKey /* OUT: Size of current key in bytes */
74256 void *pKey;
74257 if( pSorter->aTree ){
74258 VdbeSorterIter *pIter;
74259 pIter = &pSorter->aIter[ pSorter->aTree[1] ];
74260 *pnKey = pIter->nKey;
74261 pKey = pIter->aKey;
74262 }else{
74263 *pnKey = pSorter->pRecord->nVal;
74264 pKey = pSorter->pRecord->pVal;
74266 return pKey;
74270 ** Copy the current sorter key into the memory cell pOut.
74272 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
74273 VdbeSorter *pSorter = pCsr->pSorter;
74274 void *pKey; int nKey; /* Sorter key to copy into pOut */
74276 pKey = vdbeSorterRowkey(pSorter, &nKey);
74277 if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
74278 return SQLITE_NOMEM;
74280 pOut->n = nKey;
74281 MemSetTypeFlag(pOut, MEM_Blob);
74282 memcpy(pOut->z, pKey, nKey);
74284 return SQLITE_OK;
74288 ** Compare the key in memory cell pVal with the key that the sorter cursor
74289 ** passed as the first argument currently points to. For the purposes of
74290 ** the comparison, ignore the rowid field at the end of each record.
74292 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
74293 ** Otherwise, set *pRes to a negative, zero or positive value if the
74294 ** key in pVal is smaller than, equal to or larger than the current sorter
74295 ** key.
74297 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
74298 const VdbeCursor *pCsr, /* Sorter cursor */
74299 Mem *pVal, /* Value to compare to current sorter key */
74300 int nIgnore, /* Ignore this many fields at the end */
74301 int *pRes /* OUT: Result of comparison */
74303 VdbeSorter *pSorter = pCsr->pSorter;
74304 void *pKey; int nKey; /* Sorter key to compare pVal with */
74306 pKey = vdbeSorterRowkey(pSorter, &nKey);
74307 vdbeSorterCompare(pCsr, nIgnore, pVal->z, pVal->n, pKey, nKey, pRes);
74308 return SQLITE_OK;
74311 /************** End of vdbesort.c ********************************************/
74312 /************** Begin file journal.c *****************************************/
74314 ** 2007 August 22
74316 ** The author disclaims copyright to this source code. In place of
74317 ** a legal notice, here is a blessing:
74319 ** May you do good and not evil.
74320 ** May you find forgiveness for yourself and forgive others.
74321 ** May you share freely, never taking more than you give.
74323 *************************************************************************
74325 ** This file implements a special kind of sqlite3_file object used
74326 ** by SQLite to create journal files if the atomic-write optimization
74327 ** is enabled.
74329 ** The distinctive characteristic of this sqlite3_file is that the
74330 ** actual on disk file is created lazily. When the file is created,
74331 ** the caller specifies a buffer size for an in-memory buffer to
74332 ** be used to service read() and write() requests. The actual file
74333 ** on disk is not created or populated until either:
74335 ** 1) The in-memory representation grows too large for the allocated
74336 ** buffer, or
74337 ** 2) The sqlite3JournalCreate() function is called.
74339 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
74343 ** A JournalFile object is a subclass of sqlite3_file used by
74344 ** as an open file handle for journal files.
74346 struct JournalFile {
74347 sqlite3_io_methods *pMethod; /* I/O methods on journal files */
74348 int nBuf; /* Size of zBuf[] in bytes */
74349 char *zBuf; /* Space to buffer journal writes */
74350 int iSize; /* Amount of zBuf[] currently used */
74351 int flags; /* xOpen flags */
74352 sqlite3_vfs *pVfs; /* The "real" underlying VFS */
74353 sqlite3_file *pReal; /* The "real" underlying file descriptor */
74354 const char *zJournal; /* Name of the journal file */
74356 typedef struct JournalFile JournalFile;
74359 ** If it does not already exists, create and populate the on-disk file
74360 ** for JournalFile p.
74362 static int createFile(JournalFile *p){
74363 int rc = SQLITE_OK;
74364 if( !p->pReal ){
74365 sqlite3_file *pReal = (sqlite3_file *)&p[1];
74366 rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
74367 if( rc==SQLITE_OK ){
74368 p->pReal = pReal;
74369 if( p->iSize>0 ){
74370 assert(p->iSize<=p->nBuf);
74371 rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
74373 if( rc!=SQLITE_OK ){
74374 /* If an error occurred while writing to the file, close it before
74375 ** returning. This way, SQLite uses the in-memory journal data to
74376 ** roll back changes made to the internal page-cache before this
74377 ** function was called. */
74378 sqlite3OsClose(pReal);
74379 p->pReal = 0;
74383 return rc;
74387 ** Close the file.
74389 static int jrnlClose(sqlite3_file *pJfd){
74390 JournalFile *p = (JournalFile *)pJfd;
74391 if( p->pReal ){
74392 sqlite3OsClose(p->pReal);
74394 sqlite3_free(p->zBuf);
74395 return SQLITE_OK;
74399 ** Read data from the file.
74401 static int jrnlRead(
74402 sqlite3_file *pJfd, /* The journal file from which to read */
74403 void *zBuf, /* Put the results here */
74404 int iAmt, /* Number of bytes to read */
74405 sqlite_int64 iOfst /* Begin reading at this offset */
74407 int rc = SQLITE_OK;
74408 JournalFile *p = (JournalFile *)pJfd;
74409 if( p->pReal ){
74410 rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
74411 }else if( (iAmt+iOfst)>p->iSize ){
74412 rc = SQLITE_IOERR_SHORT_READ;
74413 }else{
74414 memcpy(zBuf, &p->zBuf[iOfst], iAmt);
74416 return rc;
74420 ** Write data to the file.
74422 static int jrnlWrite(
74423 sqlite3_file *pJfd, /* The journal file into which to write */
74424 const void *zBuf, /* Take data to be written from here */
74425 int iAmt, /* Number of bytes to write */
74426 sqlite_int64 iOfst /* Begin writing at this offset into the file */
74428 int rc = SQLITE_OK;
74429 JournalFile *p = (JournalFile *)pJfd;
74430 if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
74431 rc = createFile(p);
74433 if( rc==SQLITE_OK ){
74434 if( p->pReal ){
74435 rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
74436 }else{
74437 memcpy(&p->zBuf[iOfst], zBuf, iAmt);
74438 if( p->iSize<(iOfst+iAmt) ){
74439 p->iSize = (iOfst+iAmt);
74443 return rc;
74447 ** Truncate the file.
74449 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
74450 int rc = SQLITE_OK;
74451 JournalFile *p = (JournalFile *)pJfd;
74452 if( p->pReal ){
74453 rc = sqlite3OsTruncate(p->pReal, size);
74454 }else if( size<p->iSize ){
74455 p->iSize = size;
74457 return rc;
74461 ** Sync the file.
74463 static int jrnlSync(sqlite3_file *pJfd, int flags){
74464 int rc;
74465 JournalFile *p = (JournalFile *)pJfd;
74466 if( p->pReal ){
74467 rc = sqlite3OsSync(p->pReal, flags);
74468 }else{
74469 rc = SQLITE_OK;
74471 return rc;
74475 ** Query the size of the file in bytes.
74477 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
74478 int rc = SQLITE_OK;
74479 JournalFile *p = (JournalFile *)pJfd;
74480 if( p->pReal ){
74481 rc = sqlite3OsFileSize(p->pReal, pSize);
74482 }else{
74483 *pSize = (sqlite_int64) p->iSize;
74485 return rc;
74489 ** Table of methods for JournalFile sqlite3_file object.
74491 static struct sqlite3_io_methods JournalFileMethods = {
74492 1, /* iVersion */
74493 jrnlClose, /* xClose */
74494 jrnlRead, /* xRead */
74495 jrnlWrite, /* xWrite */
74496 jrnlTruncate, /* xTruncate */
74497 jrnlSync, /* xSync */
74498 jrnlFileSize, /* xFileSize */
74499 0, /* xLock */
74500 0, /* xUnlock */
74501 0, /* xCheckReservedLock */
74502 0, /* xFileControl */
74503 0, /* xSectorSize */
74504 0, /* xDeviceCharacteristics */
74505 0, /* xShmMap */
74506 0, /* xShmLock */
74507 0, /* xShmBarrier */
74508 0 /* xShmUnmap */
74512 ** Open a journal file.
74514 SQLITE_PRIVATE int sqlite3JournalOpen(
74515 sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
74516 const char *zName, /* Name of the journal file */
74517 sqlite3_file *pJfd, /* Preallocated, blank file handle */
74518 int flags, /* Opening flags */
74519 int nBuf /* Bytes buffered before opening the file */
74521 JournalFile *p = (JournalFile *)pJfd;
74522 memset(p, 0, sqlite3JournalSize(pVfs));
74523 if( nBuf>0 ){
74524 p->zBuf = sqlite3MallocZero(nBuf);
74525 if( !p->zBuf ){
74526 return SQLITE_NOMEM;
74528 }else{
74529 return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
74531 p->pMethod = &JournalFileMethods;
74532 p->nBuf = nBuf;
74533 p->flags = flags;
74534 p->zJournal = zName;
74535 p->pVfs = pVfs;
74536 return SQLITE_OK;
74540 ** If the argument p points to a JournalFile structure, and the underlying
74541 ** file has not yet been created, create it now.
74543 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
74544 if( p->pMethods!=&JournalFileMethods ){
74545 return SQLITE_OK;
74547 return createFile((JournalFile *)p);
74551 ** The file-handle passed as the only argument is guaranteed to be an open
74552 ** file. It may or may not be of class JournalFile. If the file is a
74553 ** JournalFile, and the underlying file on disk has not yet been opened,
74554 ** return 0. Otherwise, return 1.
74556 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
74557 return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
74561 ** Return the number of bytes required to store a JournalFile that uses vfs
74562 ** pVfs to create the underlying on-disk files.
74564 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
74565 return (pVfs->szOsFile+sizeof(JournalFile));
74567 #endif
74569 /************** End of journal.c *********************************************/
74570 /************** Begin file memjournal.c **************************************/
74572 ** 2008 October 7
74574 ** The author disclaims copyright to this source code. In place of
74575 ** a legal notice, here is a blessing:
74577 ** May you do good and not evil.
74578 ** May you find forgiveness for yourself and forgive others.
74579 ** May you share freely, never taking more than you give.
74581 *************************************************************************
74583 ** This file contains code use to implement an in-memory rollback journal.
74584 ** The in-memory rollback journal is used to journal transactions for
74585 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
74588 /* Forward references to internal structures */
74589 typedef struct MemJournal MemJournal;
74590 typedef struct FilePoint FilePoint;
74591 typedef struct FileChunk FileChunk;
74593 /* Space to hold the rollback journal is allocated in increments of
74594 ** this many bytes.
74596 ** The size chosen is a little less than a power of two. That way,
74597 ** the FileChunk object will have a size that almost exactly fills
74598 ** a power-of-two allocation. This mimimizes wasted space in power-of-two
74599 ** memory allocators.
74601 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
74604 ** The rollback journal is composed of a linked list of these structures.
74606 struct FileChunk {
74607 FileChunk *pNext; /* Next chunk in the journal */
74608 u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
74612 ** An instance of this object serves as a cursor into the rollback journal.
74613 ** The cursor can be either for reading or writing.
74615 struct FilePoint {
74616 sqlite3_int64 iOffset; /* Offset from the beginning of the file */
74617 FileChunk *pChunk; /* Specific chunk into which cursor points */
74621 ** This subclass is a subclass of sqlite3_file. Each open memory-journal
74622 ** is an instance of this class.
74624 struct MemJournal {
74625 sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
74626 FileChunk *pFirst; /* Head of in-memory chunk-list */
74627 FilePoint endpoint; /* Pointer to the end of the file */
74628 FilePoint readpoint; /* Pointer to the end of the last xRead() */
74632 ** Read data from the in-memory journal file. This is the implementation
74633 ** of the sqlite3_vfs.xRead method.
74635 static int memjrnlRead(
74636 sqlite3_file *pJfd, /* The journal file from which to read */
74637 void *zBuf, /* Put the results here */
74638 int iAmt, /* Number of bytes to read */
74639 sqlite_int64 iOfst /* Begin reading at this offset */
74641 MemJournal *p = (MemJournal *)pJfd;
74642 u8 *zOut = zBuf;
74643 int nRead = iAmt;
74644 int iChunkOffset;
74645 FileChunk *pChunk;
74647 /* SQLite never tries to read past the end of a rollback journal file */
74648 assert( iOfst+iAmt<=p->endpoint.iOffset );
74650 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
74651 sqlite3_int64 iOff = 0;
74652 for(pChunk=p->pFirst;
74653 ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
74654 pChunk=pChunk->pNext
74656 iOff += JOURNAL_CHUNKSIZE;
74658 }else{
74659 pChunk = p->readpoint.pChunk;
74662 iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
74663 do {
74664 int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
74665 int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
74666 memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
74667 zOut += nCopy;
74668 nRead -= iSpace;
74669 iChunkOffset = 0;
74670 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
74671 p->readpoint.iOffset = iOfst+iAmt;
74672 p->readpoint.pChunk = pChunk;
74674 return SQLITE_OK;
74678 ** Write data to the file.
74680 static int memjrnlWrite(
74681 sqlite3_file *pJfd, /* The journal file into which to write */
74682 const void *zBuf, /* Take data to be written from here */
74683 int iAmt, /* Number of bytes to write */
74684 sqlite_int64 iOfst /* Begin writing at this offset into the file */
74686 MemJournal *p = (MemJournal *)pJfd;
74687 int nWrite = iAmt;
74688 u8 *zWrite = (u8 *)zBuf;
74690 /* An in-memory journal file should only ever be appended to. Random
74691 ** access writes are not required by sqlite.
74693 assert( iOfst==p->endpoint.iOffset );
74694 UNUSED_PARAMETER(iOfst);
74696 while( nWrite>0 ){
74697 FileChunk *pChunk = p->endpoint.pChunk;
74698 int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
74699 int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
74701 if( iChunkOffset==0 ){
74702 /* New chunk is required to extend the file. */
74703 FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
74704 if( !pNew ){
74705 return SQLITE_IOERR_NOMEM;
74707 pNew->pNext = 0;
74708 if( pChunk ){
74709 assert( p->pFirst );
74710 pChunk->pNext = pNew;
74711 }else{
74712 assert( !p->pFirst );
74713 p->pFirst = pNew;
74715 p->endpoint.pChunk = pNew;
74718 memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
74719 zWrite += iSpace;
74720 nWrite -= iSpace;
74721 p->endpoint.iOffset += iSpace;
74724 return SQLITE_OK;
74728 ** Truncate the file.
74730 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
74731 MemJournal *p = (MemJournal *)pJfd;
74732 FileChunk *pChunk;
74733 assert(size==0);
74734 UNUSED_PARAMETER(size);
74735 pChunk = p->pFirst;
74736 while( pChunk ){
74737 FileChunk *pTmp = pChunk;
74738 pChunk = pChunk->pNext;
74739 sqlite3_free(pTmp);
74741 sqlite3MemJournalOpen(pJfd);
74742 return SQLITE_OK;
74746 ** Close the file.
74748 static int memjrnlClose(sqlite3_file *pJfd){
74749 memjrnlTruncate(pJfd, 0);
74750 return SQLITE_OK;
74755 ** Sync the file.
74757 ** Syncing an in-memory journal is a no-op. And, in fact, this routine
74758 ** is never called in a working implementation. This implementation
74759 ** exists purely as a contingency, in case some malfunction in some other
74760 ** part of SQLite causes Sync to be called by mistake.
74762 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
74763 UNUSED_PARAMETER2(NotUsed, NotUsed2);
74764 return SQLITE_OK;
74768 ** Query the size of the file in bytes.
74770 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
74771 MemJournal *p = (MemJournal *)pJfd;
74772 *pSize = (sqlite_int64) p->endpoint.iOffset;
74773 return SQLITE_OK;
74777 ** Table of methods for MemJournal sqlite3_file object.
74779 static const struct sqlite3_io_methods MemJournalMethods = {
74780 1, /* iVersion */
74781 memjrnlClose, /* xClose */
74782 memjrnlRead, /* xRead */
74783 memjrnlWrite, /* xWrite */
74784 memjrnlTruncate, /* xTruncate */
74785 memjrnlSync, /* xSync */
74786 memjrnlFileSize, /* xFileSize */
74787 0, /* xLock */
74788 0, /* xUnlock */
74789 0, /* xCheckReservedLock */
74790 0, /* xFileControl */
74791 0, /* xSectorSize */
74792 0, /* xDeviceCharacteristics */
74793 0, /* xShmMap */
74794 0, /* xShmLock */
74795 0, /* xShmBarrier */
74796 0, /* xShmUnmap */
74797 0, /* xFetch */
74798 0 /* xUnfetch */
74802 ** Open a journal file.
74804 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
74805 MemJournal *p = (MemJournal *)pJfd;
74806 assert( EIGHT_BYTE_ALIGNMENT(p) );
74807 memset(p, 0, sqlite3MemJournalSize());
74808 p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
74812 ** Return true if the file-handle passed as an argument is
74813 ** an in-memory journal
74815 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
74816 return pJfd->pMethods==&MemJournalMethods;
74820 ** Return the number of bytes required to store a MemJournal file descriptor.
74822 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
74823 return sizeof(MemJournal);
74826 /************** End of memjournal.c ******************************************/
74827 /************** Begin file walker.c ******************************************/
74829 ** 2008 August 16
74831 ** The author disclaims copyright to this source code. In place of
74832 ** a legal notice, here is a blessing:
74834 ** May you do good and not evil.
74835 ** May you find forgiveness for yourself and forgive others.
74836 ** May you share freely, never taking more than you give.
74838 *************************************************************************
74839 ** This file contains routines used for walking the parser tree for
74840 ** an SQL statement.
74842 /* #include <stdlib.h> */
74843 /* #include <string.h> */
74847 ** Walk an expression tree. Invoke the callback once for each node
74848 ** of the expression, while decending. (In other words, the callback
74849 ** is invoked before visiting children.)
74851 ** The return value from the callback should be one of the WRC_*
74852 ** constants to specify how to proceed with the walk.
74854 ** WRC_Continue Continue descending down the tree.
74856 ** WRC_Prune Do not descend into child nodes. But allow
74857 ** the walk to continue with sibling nodes.
74859 ** WRC_Abort Do no more callbacks. Unwind the stack and
74860 ** return the top-level walk call.
74862 ** The return value from this routine is WRC_Abort to abandon the tree walk
74863 ** and WRC_Continue to continue.
74865 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
74866 int rc;
74867 if( pExpr==0 ) return WRC_Continue;
74868 testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
74869 testcase( ExprHasProperty(pExpr, EP_Reduced) );
74870 rc = pWalker->xExprCallback(pWalker, pExpr);
74871 if( rc==WRC_Continue
74872 && !ExprHasProperty(pExpr,EP_TokenOnly) ){
74873 if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
74874 if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
74875 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74876 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
74877 }else{
74878 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
74881 return rc & WRC_Abort;
74885 ** Call sqlite3WalkExpr() for every expression in list p or until
74886 ** an abort request is seen.
74888 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
74889 int i;
74890 struct ExprList_item *pItem;
74891 if( p ){
74892 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
74893 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
74896 return WRC_Continue;
74900 ** Walk all expressions associated with SELECT statement p. Do
74901 ** not invoke the SELECT callback on p, but do (of course) invoke
74902 ** any expr callbacks and SELECT callbacks that come from subqueries.
74903 ** Return WRC_Abort or WRC_Continue.
74905 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
74906 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
74907 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
74908 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
74909 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
74910 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
74911 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
74912 if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
74913 return WRC_Continue;
74917 ** Walk the parse trees associated with all subqueries in the
74918 ** FROM clause of SELECT statement p. Do not invoke the select
74919 ** callback on p, but do invoke it on each FROM clause subquery
74920 ** and on any subqueries further down in the tree. Return
74921 ** WRC_Abort or WRC_Continue;
74923 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
74924 SrcList *pSrc;
74925 int i;
74926 struct SrcList_item *pItem;
74928 pSrc = p->pSrc;
74929 if( ALWAYS(pSrc) ){
74930 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
74931 if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
74932 return WRC_Abort;
74936 return WRC_Continue;
74940 ** Call sqlite3WalkExpr() for every expression in Select statement p.
74941 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
74942 ** on the compound select chain, p->pPrior.
74944 ** If it is not NULL, the xSelectCallback() callback is invoked before
74945 ** the walk of the expressions and FROM clause. The xSelectCallback2()
74946 ** method, if it is not NULL, is invoked following the walk of the
74947 ** expressions and FROM clause.
74949 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
74950 ** there is an abort request.
74952 ** If the Walker does not have an xSelectCallback() then this routine
74953 ** is a no-op returning WRC_Continue.
74955 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
74956 int rc;
74957 if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
74958 return WRC_Continue;
74960 rc = WRC_Continue;
74961 pWalker->walkerDepth++;
74962 while( p ){
74963 if( pWalker->xSelectCallback ){
74964 rc = pWalker->xSelectCallback(pWalker, p);
74965 if( rc ) break;
74967 if( sqlite3WalkSelectExpr(pWalker, p)
74968 || sqlite3WalkSelectFrom(pWalker, p)
74970 pWalker->walkerDepth--;
74971 return WRC_Abort;
74973 if( pWalker->xSelectCallback2 ){
74974 pWalker->xSelectCallback2(pWalker, p);
74976 p = p->pPrior;
74978 pWalker->walkerDepth--;
74979 return rc & WRC_Abort;
74982 /************** End of walker.c **********************************************/
74983 /************** Begin file resolve.c *****************************************/
74985 ** 2008 August 18
74987 ** The author disclaims copyright to this source code. In place of
74988 ** a legal notice, here is a blessing:
74990 ** May you do good and not evil.
74991 ** May you find forgiveness for yourself and forgive others.
74992 ** May you share freely, never taking more than you give.
74994 *************************************************************************
74996 ** This file contains routines used for walking the parser tree and
74997 ** resolve all identifiers by associating them with a particular
74998 ** table and column.
75000 /* #include <stdlib.h> */
75001 /* #include <string.h> */
75004 ** Walk the expression tree pExpr and increase the aggregate function
75005 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
75006 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
75007 ** outer query into an inner subquery.
75009 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
75010 ** is a helper function - a callback for the tree walker.
75012 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
75013 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
75014 return WRC_Continue;
75016 static void incrAggFunctionDepth(Expr *pExpr, int N){
75017 if( N>0 ){
75018 Walker w;
75019 memset(&w, 0, sizeof(w));
75020 w.xExprCallback = incrAggDepth;
75021 w.u.i = N;
75022 sqlite3WalkExpr(&w, pExpr);
75027 ** Turn the pExpr expression into an alias for the iCol-th column of the
75028 ** result set in pEList.
75030 ** If the result set column is a simple column reference, then this routine
75031 ** makes an exact copy. But for any other kind of expression, this
75032 ** routine make a copy of the result set column as the argument to the
75033 ** TK_AS operator. The TK_AS operator causes the expression to be
75034 ** evaluated just once and then reused for each alias.
75036 ** The reason for suppressing the TK_AS term when the expression is a simple
75037 ** column reference is so that the column reference will be recognized as
75038 ** usable by indices within the WHERE clause processing logic.
75040 ** The TK_AS operator is inhibited if zType[0]=='G'. This means
75041 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
75043 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
75045 ** Is equivalent to:
75047 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
75049 ** The result of random()%5 in the GROUP BY clause is probably different
75050 ** from the result in the result-set. On the other hand Standard SQL does
75051 ** not allow the GROUP BY clause to contain references to result-set columns.
75052 ** So this should never come up in well-formed queries.
75054 ** If the reference is followed by a COLLATE operator, then make sure
75055 ** the COLLATE operator is preserved. For example:
75057 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
75059 ** Should be transformed into:
75061 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
75063 ** The nSubquery parameter specifies how many levels of subquery the
75064 ** alias is removed from the original expression. The usually value is
75065 ** zero but it might be more if the alias is contained within a subquery
75066 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
75067 ** structures must be increased by the nSubquery amount.
75069 static void resolveAlias(
75070 Parse *pParse, /* Parsing context */
75071 ExprList *pEList, /* A result set */
75072 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
75073 Expr *pExpr, /* Transform this into an alias to the result set */
75074 const char *zType, /* "GROUP" or "ORDER" or "" */
75075 int nSubquery /* Number of subqueries that the label is moving */
75077 Expr *pOrig; /* The iCol-th column of the result set */
75078 Expr *pDup; /* Copy of pOrig */
75079 sqlite3 *db; /* The database connection */
75081 assert( iCol>=0 && iCol<pEList->nExpr );
75082 pOrig = pEList->a[iCol].pExpr;
75083 assert( pOrig!=0 );
75084 assert( pOrig->flags & EP_Resolved );
75085 db = pParse->db;
75086 pDup = sqlite3ExprDup(db, pOrig, 0);
75087 if( pDup==0 ) return;
75088 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
75089 incrAggFunctionDepth(pDup, nSubquery);
75090 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
75091 if( pDup==0 ) return;
75092 ExprSetProperty(pDup, EP_Skip);
75093 if( pEList->a[iCol].u.x.iAlias==0 ){
75094 pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
75096 pDup->iTable = pEList->a[iCol].u.x.iAlias;
75098 if( pExpr->op==TK_COLLATE ){
75099 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
75102 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
75103 ** prevents ExprDelete() from deleting the Expr structure itself,
75104 ** allowing it to be repopulated by the memcpy() on the following line.
75105 ** The pExpr->u.zToken might point into memory that will be freed by the
75106 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
75107 ** make a copy of the token before doing the sqlite3DbFree().
75109 ExprSetProperty(pExpr, EP_Static);
75110 sqlite3ExprDelete(db, pExpr);
75111 memcpy(pExpr, pDup, sizeof(*pExpr));
75112 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
75113 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
75114 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
75115 pExpr->flags |= EP_MemToken;
75117 sqlite3DbFree(db, pDup);
75122 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
75124 ** Return FALSE if the USING clause is NULL or if it does not contain
75125 ** zCol.
75127 static int nameInUsingClause(IdList *pUsing, const char *zCol){
75128 if( pUsing ){
75129 int k;
75130 for(k=0; k<pUsing->nId; k++){
75131 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
75134 return 0;
75138 ** Subqueries stores the original database, table and column names for their
75139 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
75140 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
75141 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
75142 ** match anything.
75144 SQLITE_PRIVATE int sqlite3MatchSpanName(
75145 const char *zSpan,
75146 const char *zCol,
75147 const char *zTab,
75148 const char *zDb
75150 int n;
75151 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
75152 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
75153 return 0;
75155 zSpan += n+1;
75156 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
75157 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
75158 return 0;
75160 zSpan += n+1;
75161 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
75162 return 0;
75164 return 1;
75168 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
75169 ** that name in the set of source tables in pSrcList and make the pExpr
75170 ** expression node refer back to that source column. The following changes
75171 ** are made to pExpr:
75173 ** pExpr->iDb Set the index in db->aDb[] of the database X
75174 ** (even if X is implied).
75175 ** pExpr->iTable Set to the cursor number for the table obtained
75176 ** from pSrcList.
75177 ** pExpr->pTab Points to the Table structure of X.Y (even if
75178 ** X and/or Y are implied.)
75179 ** pExpr->iColumn Set to the column number within the table.
75180 ** pExpr->op Set to TK_COLUMN.
75181 ** pExpr->pLeft Any expression this points to is deleted
75182 ** pExpr->pRight Any expression this points to is deleted.
75184 ** The zDb variable is the name of the database (the "X"). This value may be
75185 ** NULL meaning that name is of the form Y.Z or Z. Any available database
75186 ** can be used. The zTable variable is the name of the table (the "Y"). This
75187 ** value can be NULL if zDb is also NULL. If zTable is NULL it
75188 ** means that the form of the name is Z and that columns from any table
75189 ** can be used.
75191 ** If the name cannot be resolved unambiguously, leave an error message
75192 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
75194 static int lookupName(
75195 Parse *pParse, /* The parsing context */
75196 const char *zDb, /* Name of the database containing table, or NULL */
75197 const char *zTab, /* Name of table containing column, or NULL */
75198 const char *zCol, /* Name of the column. */
75199 NameContext *pNC, /* The name context used to resolve the name */
75200 Expr *pExpr /* Make this EXPR node point to the selected column */
75202 int i, j; /* Loop counters */
75203 int cnt = 0; /* Number of matching column names */
75204 int cntTab = 0; /* Number of matching table names */
75205 int nSubquery = 0; /* How many levels of subquery */
75206 sqlite3 *db = pParse->db; /* The database connection */
75207 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
75208 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
75209 NameContext *pTopNC = pNC; /* First namecontext in the list */
75210 Schema *pSchema = 0; /* Schema of the expression */
75211 int isTrigger = 0; /* True if resolved to a trigger column */
75212 Table *pTab = 0; /* Table hold the row */
75213 Column *pCol; /* A column of pTab */
75215 assert( pNC ); /* the name context cannot be NULL. */
75216 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
75217 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
75219 /* Initialize the node to no-match */
75220 pExpr->iTable = -1;
75221 pExpr->pTab = 0;
75222 ExprSetVVAProperty(pExpr, EP_NoReduce);
75224 /* Translate the schema name in zDb into a pointer to the corresponding
75225 ** schema. If not found, pSchema will remain NULL and nothing will match
75226 ** resulting in an appropriate error message toward the end of this routine
75228 if( zDb ){
75229 testcase( pNC->ncFlags & NC_PartIdx );
75230 testcase( pNC->ncFlags & NC_IsCheck );
75231 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
75232 /* Silently ignore database qualifiers inside CHECK constraints and partial
75233 ** indices. Do not raise errors because that might break legacy and
75234 ** because it does not hurt anything to just ignore the database name. */
75235 zDb = 0;
75236 }else{
75237 for(i=0; i<db->nDb; i++){
75238 assert( db->aDb[i].zName );
75239 if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
75240 pSchema = db->aDb[i].pSchema;
75241 break;
75247 /* Start at the inner-most context and move outward until a match is found */
75248 while( pNC && cnt==0 ){
75249 ExprList *pEList;
75250 SrcList *pSrcList = pNC->pSrcList;
75252 if( pSrcList ){
75253 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
75254 pTab = pItem->pTab;
75255 assert( pTab!=0 && pTab->zName!=0 );
75256 assert( pTab->nCol>0 );
75257 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
75258 int hit = 0;
75259 pEList = pItem->pSelect->pEList;
75260 for(j=0; j<pEList->nExpr; j++){
75261 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
75262 cnt++;
75263 cntTab = 2;
75264 pMatch = pItem;
75265 pExpr->iColumn = j;
75266 hit = 1;
75269 if( hit || zTab==0 ) continue;
75271 if( zDb && pTab->pSchema!=pSchema ){
75272 continue;
75274 if( zTab ){
75275 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
75276 assert( zTabName!=0 );
75277 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
75278 continue;
75281 if( 0==(cntTab++) ){
75282 pMatch = pItem;
75284 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
75285 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
75286 /* If there has been exactly one prior match and this match
75287 ** is for the right-hand table of a NATURAL JOIN or is in a
75288 ** USING clause, then skip this match.
75290 if( cnt==1 ){
75291 if( pItem->jointype & JT_NATURAL ) continue;
75292 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
75294 cnt++;
75295 pMatch = pItem;
75296 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
75297 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
75298 break;
75302 if( pMatch ){
75303 pExpr->iTable = pMatch->iCursor;
75304 pExpr->pTab = pMatch->pTab;
75305 pSchema = pExpr->pTab->pSchema;
75307 } /* if( pSrcList ) */
75309 #ifndef SQLITE_OMIT_TRIGGER
75310 /* If we have not already resolved the name, then maybe
75311 ** it is a new.* or old.* trigger argument reference
75313 if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
75314 int op = pParse->eTriggerOp;
75315 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
75316 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
75317 pExpr->iTable = 1;
75318 pTab = pParse->pTriggerTab;
75319 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
75320 pExpr->iTable = 0;
75321 pTab = pParse->pTriggerTab;
75324 if( pTab ){
75325 int iCol;
75326 pSchema = pTab->pSchema;
75327 cntTab++;
75328 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
75329 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
75330 if( iCol==pTab->iPKey ){
75331 iCol = -1;
75333 break;
75336 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
75337 /* IMP: R-24309-18625 */
75338 /* IMP: R-44911-55124 */
75339 iCol = -1;
75341 if( iCol<pTab->nCol ){
75342 cnt++;
75343 if( iCol<0 ){
75344 pExpr->affinity = SQLITE_AFF_INTEGER;
75345 }else if( pExpr->iTable==0 ){
75346 testcase( iCol==31 );
75347 testcase( iCol==32 );
75348 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
75349 }else{
75350 testcase( iCol==31 );
75351 testcase( iCol==32 );
75352 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
75354 pExpr->iColumn = (i16)iCol;
75355 pExpr->pTab = pTab;
75356 isTrigger = 1;
75360 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
75363 ** Perhaps the name is a reference to the ROWID
75365 assert( pTab!=0 || cntTab==0 );
75366 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
75367 cnt = 1;
75368 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
75369 pExpr->affinity = SQLITE_AFF_INTEGER;
75373 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
75374 ** might refer to an result-set alias. This happens, for example, when
75375 ** we are resolving names in the WHERE clause of the following command:
75377 ** SELECT a+b AS x FROM table WHERE x<10;
75379 ** In cases like this, replace pExpr with a copy of the expression that
75380 ** forms the result set entry ("a+b" in the example) and return immediately.
75381 ** Note that the expression in the result set should have already been
75382 ** resolved by the time the WHERE clause is resolved.
75384 ** The ability to use an output result-set column in the WHERE, GROUP BY,
75385 ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
75386 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
75387 ** is supported for backwards compatibility only. TO DO: Issue a warning
75388 ** on sqlite3_log() whenever the capability is used.
75390 if( (pEList = pNC->pEList)!=0
75391 && zTab==0
75392 && cnt==0
75394 for(j=0; j<pEList->nExpr; j++){
75395 char *zAs = pEList->a[j].zName;
75396 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
75397 Expr *pOrig;
75398 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
75399 assert( pExpr->x.pList==0 );
75400 assert( pExpr->x.pSelect==0 );
75401 pOrig = pEList->a[j].pExpr;
75402 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
75403 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
75404 return WRC_Abort;
75406 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
75407 cnt = 1;
75408 pMatch = 0;
75409 assert( zTab==0 && zDb==0 );
75410 goto lookupname_end;
75415 /* Advance to the next name context. The loop will exit when either
75416 ** we have a match (cnt>0) or when we run out of name contexts.
75418 if( cnt==0 ){
75419 pNC = pNC->pNext;
75420 nSubquery++;
75425 ** If X and Y are NULL (in other words if only the column name Z is
75426 ** supplied) and the value of Z is enclosed in double-quotes, then
75427 ** Z is a string literal if it doesn't match any column names. In that
75428 ** case, we need to return right away and not make any changes to
75429 ** pExpr.
75431 ** Because no reference was made to outer contexts, the pNC->nRef
75432 ** fields are not changed in any context.
75434 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
75435 pExpr->op = TK_STRING;
75436 pExpr->pTab = 0;
75437 return WRC_Prune;
75441 ** cnt==0 means there was not match. cnt>1 means there were two or
75442 ** more matches. Either way, we have an error.
75444 if( cnt!=1 ){
75445 const char *zErr;
75446 zErr = cnt==0 ? "no such column" : "ambiguous column name";
75447 if( zDb ){
75448 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
75449 }else if( zTab ){
75450 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
75451 }else{
75452 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
75454 pParse->checkSchema = 1;
75455 pTopNC->nErr++;
75458 /* If a column from a table in pSrcList is referenced, then record
75459 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
75460 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
75461 ** column number is greater than the number of bits in the bitmask
75462 ** then set the high-order bit of the bitmask.
75464 if( pExpr->iColumn>=0 && pMatch!=0 ){
75465 int n = pExpr->iColumn;
75466 testcase( n==BMS-1 );
75467 if( n>=BMS ){
75468 n = BMS-1;
75470 assert( pMatch->iCursor==pExpr->iTable );
75471 pMatch->colUsed |= ((Bitmask)1)<<n;
75474 /* Clean up and return
75476 sqlite3ExprDelete(db, pExpr->pLeft);
75477 pExpr->pLeft = 0;
75478 sqlite3ExprDelete(db, pExpr->pRight);
75479 pExpr->pRight = 0;
75480 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
75481 lookupname_end:
75482 if( cnt==1 ){
75483 assert( pNC!=0 );
75484 if( pExpr->op!=TK_AS ){
75485 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
75487 /* Increment the nRef value on all name contexts from TopNC up to
75488 ** the point where the name matched. */
75489 for(;;){
75490 assert( pTopNC!=0 );
75491 pTopNC->nRef++;
75492 if( pTopNC==pNC ) break;
75493 pTopNC = pTopNC->pNext;
75495 return WRC_Prune;
75496 } else {
75497 return WRC_Abort;
75502 ** Allocate and return a pointer to an expression to load the column iCol
75503 ** from datasource iSrc in SrcList pSrc.
75505 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
75506 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
75507 if( p ){
75508 struct SrcList_item *pItem = &pSrc->a[iSrc];
75509 p->pTab = pItem->pTab;
75510 p->iTable = pItem->iCursor;
75511 if( p->pTab->iPKey==iCol ){
75512 p->iColumn = -1;
75513 }else{
75514 p->iColumn = (ynVar)iCol;
75515 testcase( iCol==BMS );
75516 testcase( iCol==BMS-1 );
75517 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
75519 ExprSetProperty(p, EP_Resolved);
75521 return p;
75525 ** Report an error that an expression is not valid for a partial index WHERE
75526 ** clause.
75528 static void notValidPartIdxWhere(
75529 Parse *pParse, /* Leave error message here */
75530 NameContext *pNC, /* The name context */
75531 const char *zMsg /* Type of error */
75533 if( (pNC->ncFlags & NC_PartIdx)!=0 ){
75534 sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
75535 zMsg);
75539 #ifndef SQLITE_OMIT_CHECK
75541 ** Report an error that an expression is not valid for a CHECK constraint.
75543 static void notValidCheckConstraint(
75544 Parse *pParse, /* Leave error message here */
75545 NameContext *pNC, /* The name context */
75546 const char *zMsg /* Type of error */
75548 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
75549 sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
75552 #else
75553 # define notValidCheckConstraint(P,N,M)
75554 #endif
75557 ** Expression p should encode a floating point value between 1.0 and 0.0.
75558 ** Return 1024 times this value. Or return -1 if p is not a floating point
75559 ** value between 1.0 and 0.0.
75561 static int exprProbability(Expr *p){
75562 double r = -1.0;
75563 if( p->op!=TK_FLOAT ) return -1;
75564 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
75565 assert( r>=0.0 );
75566 if( r>1.0 ) return -1;
75567 return (int)(r*1000.0);
75571 ** This routine is callback for sqlite3WalkExpr().
75573 ** Resolve symbolic names into TK_COLUMN operators for the current
75574 ** node in the expression tree. Return 0 to continue the search down
75575 ** the tree or 2 to abort the tree walk.
75577 ** This routine also does error checking and name resolution for
75578 ** function names. The operator for aggregate functions is changed
75579 ** to TK_AGG_FUNCTION.
75581 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
75582 NameContext *pNC;
75583 Parse *pParse;
75585 pNC = pWalker->u.pNC;
75586 assert( pNC!=0 );
75587 pParse = pNC->pParse;
75588 assert( pParse==pWalker->pParse );
75590 if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
75591 ExprSetProperty(pExpr, EP_Resolved);
75592 #ifndef NDEBUG
75593 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
75594 SrcList *pSrcList = pNC->pSrcList;
75595 int i;
75596 for(i=0; i<pNC->pSrcList->nSrc; i++){
75597 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
75600 #endif
75601 switch( pExpr->op ){
75603 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
75604 /* The special operator TK_ROW means use the rowid for the first
75605 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
75606 ** clause processing on UPDATE and DELETE statements.
75608 case TK_ROW: {
75609 SrcList *pSrcList = pNC->pSrcList;
75610 struct SrcList_item *pItem;
75611 assert( pSrcList && pSrcList->nSrc==1 );
75612 pItem = pSrcList->a;
75613 pExpr->op = TK_COLUMN;
75614 pExpr->pTab = pItem->pTab;
75615 pExpr->iTable = pItem->iCursor;
75616 pExpr->iColumn = -1;
75617 pExpr->affinity = SQLITE_AFF_INTEGER;
75618 break;
75620 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
75622 /* A lone identifier is the name of a column.
75624 case TK_ID: {
75625 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
75628 /* A table name and column name: ID.ID
75629 ** Or a database, table and column: ID.ID.ID
75631 case TK_DOT: {
75632 const char *zColumn;
75633 const char *zTable;
75634 const char *zDb;
75635 Expr *pRight;
75637 /* if( pSrcList==0 ) break; */
75638 pRight = pExpr->pRight;
75639 if( pRight->op==TK_ID ){
75640 zDb = 0;
75641 zTable = pExpr->pLeft->u.zToken;
75642 zColumn = pRight->u.zToken;
75643 }else{
75644 assert( pRight->op==TK_DOT );
75645 zDb = pExpr->pLeft->u.zToken;
75646 zTable = pRight->pLeft->u.zToken;
75647 zColumn = pRight->pRight->u.zToken;
75649 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
75652 /* Resolve function names
75654 case TK_FUNCTION: {
75655 ExprList *pList = pExpr->x.pList; /* The argument list */
75656 int n = pList ? pList->nExpr : 0; /* Number of arguments */
75657 int no_such_func = 0; /* True if no such function exists */
75658 int wrong_num_args = 0; /* True if wrong number of arguments */
75659 int is_agg = 0; /* True if is an aggregate function */
75660 int auth; /* Authorization to use the function */
75661 int nId; /* Number of characters in function name */
75662 const char *zId; /* The function name. */
75663 FuncDef *pDef; /* Information about the function */
75664 u8 enc = ENC(pParse->db); /* The database encoding */
75666 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
75667 notValidPartIdxWhere(pParse, pNC, "functions");
75668 zId = pExpr->u.zToken;
75669 nId = sqlite3Strlen30(zId);
75670 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
75671 if( pDef==0 ){
75672 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
75673 if( pDef==0 ){
75674 no_such_func = 1;
75675 }else{
75676 wrong_num_args = 1;
75678 }else{
75679 is_agg = pDef->xFunc==0;
75680 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
75681 ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
75682 if( n==2 ){
75683 pExpr->iTable = exprProbability(pList->a[1].pExpr);
75684 if( pExpr->iTable<0 ){
75685 sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
75686 "constant between 0.0 and 1.0");
75687 pNC->nErr++;
75689 }else{
75690 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
75691 ** likelihood(X, 0.0625).
75692 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
75693 ** likelihood(X,0.0625). */
75694 pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
75698 #ifndef SQLITE_OMIT_AUTHORIZATION
75699 if( pDef ){
75700 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
75701 if( auth!=SQLITE_OK ){
75702 if( auth==SQLITE_DENY ){
75703 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
75704 pDef->zName);
75705 pNC->nErr++;
75707 pExpr->op = TK_NULL;
75708 return WRC_Prune;
75710 if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
75712 #endif
75713 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
75714 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
75715 pNC->nErr++;
75716 is_agg = 0;
75717 }else if( no_such_func && pParse->db->init.busy==0 ){
75718 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
75719 pNC->nErr++;
75720 }else if( wrong_num_args ){
75721 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
75722 nId, zId);
75723 pNC->nErr++;
75725 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
75726 sqlite3WalkExprList(pWalker, pList);
75727 if( is_agg ){
75728 NameContext *pNC2 = pNC;
75729 pExpr->op = TK_AGG_FUNCTION;
75730 pExpr->op2 = 0;
75731 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
75732 pExpr->op2++;
75733 pNC2 = pNC2->pNext;
75735 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
75736 pNC->ncFlags |= NC_AllowAgg;
75738 /* FIX ME: Compute pExpr->affinity based on the expected return
75739 ** type of the function
75741 return WRC_Prune;
75743 #ifndef SQLITE_OMIT_SUBQUERY
75744 case TK_SELECT:
75745 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
75746 #endif
75747 case TK_IN: {
75748 testcase( pExpr->op==TK_IN );
75749 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75750 int nRef = pNC->nRef;
75751 notValidCheckConstraint(pParse, pNC, "subqueries");
75752 notValidPartIdxWhere(pParse, pNC, "subqueries");
75753 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
75754 assert( pNC->nRef>=nRef );
75755 if( nRef!=pNC->nRef ){
75756 ExprSetProperty(pExpr, EP_VarSelect);
75759 break;
75761 case TK_VARIABLE: {
75762 notValidCheckConstraint(pParse, pNC, "parameters");
75763 notValidPartIdxWhere(pParse, pNC, "parameters");
75764 break;
75767 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
75771 ** pEList is a list of expressions which are really the result set of the
75772 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
75773 ** This routine checks to see if pE is a simple identifier which corresponds
75774 ** to the AS-name of one of the terms of the expression list. If it is,
75775 ** this routine return an integer between 1 and N where N is the number of
75776 ** elements in pEList, corresponding to the matching entry. If there is
75777 ** no match, or if pE is not a simple identifier, then this routine
75778 ** return 0.
75780 ** pEList has been resolved. pE has not.
75782 static int resolveAsName(
75783 Parse *pParse, /* Parsing context for error messages */
75784 ExprList *pEList, /* List of expressions to scan */
75785 Expr *pE /* Expression we are trying to match */
75787 int i; /* Loop counter */
75789 UNUSED_PARAMETER(pParse);
75791 if( pE->op==TK_ID ){
75792 char *zCol = pE->u.zToken;
75793 for(i=0; i<pEList->nExpr; i++){
75794 char *zAs = pEList->a[i].zName;
75795 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
75796 return i+1;
75800 return 0;
75804 ** pE is a pointer to an expression which is a single term in the
75805 ** ORDER BY of a compound SELECT. The expression has not been
75806 ** name resolved.
75808 ** At the point this routine is called, we already know that the
75809 ** ORDER BY term is not an integer index into the result set. That
75810 ** case is handled by the calling routine.
75812 ** Attempt to match pE against result set columns in the left-most
75813 ** SELECT statement. Return the index i of the matching column,
75814 ** as an indication to the caller that it should sort by the i-th column.
75815 ** The left-most column is 1. In other words, the value returned is the
75816 ** same integer value that would be used in the SQL statement to indicate
75817 ** the column.
75819 ** If there is no match, return 0. Return -1 if an error occurs.
75821 static int resolveOrderByTermToExprList(
75822 Parse *pParse, /* Parsing context for error messages */
75823 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
75824 Expr *pE /* The specific ORDER BY term */
75826 int i; /* Loop counter */
75827 ExprList *pEList; /* The columns of the result set */
75828 NameContext nc; /* Name context for resolving pE */
75829 sqlite3 *db; /* Database connection */
75830 int rc; /* Return code from subprocedures */
75831 u8 savedSuppErr; /* Saved value of db->suppressErr */
75833 assert( sqlite3ExprIsInteger(pE, &i)==0 );
75834 pEList = pSelect->pEList;
75836 /* Resolve all names in the ORDER BY term expression
75838 memset(&nc, 0, sizeof(nc));
75839 nc.pParse = pParse;
75840 nc.pSrcList = pSelect->pSrc;
75841 nc.pEList = pEList;
75842 nc.ncFlags = NC_AllowAgg;
75843 nc.nErr = 0;
75844 db = pParse->db;
75845 savedSuppErr = db->suppressErr;
75846 db->suppressErr = 1;
75847 rc = sqlite3ResolveExprNames(&nc, pE);
75848 db->suppressErr = savedSuppErr;
75849 if( rc ) return 0;
75851 /* Try to match the ORDER BY expression against an expression
75852 ** in the result set. Return an 1-based index of the matching
75853 ** result-set entry.
75855 for(i=0; i<pEList->nExpr; i++){
75856 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
75857 return i+1;
75861 /* If no match, return 0. */
75862 return 0;
75866 ** Generate an ORDER BY or GROUP BY term out-of-range error.
75868 static void resolveOutOfRangeError(
75869 Parse *pParse, /* The error context into which to write the error */
75870 const char *zType, /* "ORDER" or "GROUP" */
75871 int i, /* The index (1-based) of the term out of range */
75872 int mx /* Largest permissible value of i */
75874 sqlite3ErrorMsg(pParse,
75875 "%r %s BY term out of range - should be "
75876 "between 1 and %d", i, zType, mx);
75880 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
75881 ** each term of the ORDER BY clause is a constant integer between 1
75882 ** and N where N is the number of columns in the compound SELECT.
75884 ** ORDER BY terms that are already an integer between 1 and N are
75885 ** unmodified. ORDER BY terms that are integers outside the range of
75886 ** 1 through N generate an error. ORDER BY terms that are expressions
75887 ** are matched against result set expressions of compound SELECT
75888 ** beginning with the left-most SELECT and working toward the right.
75889 ** At the first match, the ORDER BY expression is transformed into
75890 ** the integer column number.
75892 ** Return the number of errors seen.
75894 static int resolveCompoundOrderBy(
75895 Parse *pParse, /* Parsing context. Leave error messages here */
75896 Select *pSelect /* The SELECT statement containing the ORDER BY */
75898 int i;
75899 ExprList *pOrderBy;
75900 ExprList *pEList;
75901 sqlite3 *db;
75902 int moreToDo = 1;
75904 pOrderBy = pSelect->pOrderBy;
75905 if( pOrderBy==0 ) return 0;
75906 db = pParse->db;
75907 #if SQLITE_MAX_COLUMN
75908 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
75909 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
75910 return 1;
75912 #endif
75913 for(i=0; i<pOrderBy->nExpr; i++){
75914 pOrderBy->a[i].done = 0;
75916 pSelect->pNext = 0;
75917 while( pSelect->pPrior ){
75918 pSelect->pPrior->pNext = pSelect;
75919 pSelect = pSelect->pPrior;
75921 while( pSelect && moreToDo ){
75922 struct ExprList_item *pItem;
75923 moreToDo = 0;
75924 pEList = pSelect->pEList;
75925 assert( pEList!=0 );
75926 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
75927 int iCol = -1;
75928 Expr *pE, *pDup;
75929 if( pItem->done ) continue;
75930 pE = sqlite3ExprSkipCollate(pItem->pExpr);
75931 if( sqlite3ExprIsInteger(pE, &iCol) ){
75932 if( iCol<=0 || iCol>pEList->nExpr ){
75933 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
75934 return 1;
75936 }else{
75937 iCol = resolveAsName(pParse, pEList, pE);
75938 if( iCol==0 ){
75939 pDup = sqlite3ExprDup(db, pE, 0);
75940 if( !db->mallocFailed ){
75941 assert(pDup);
75942 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
75944 sqlite3ExprDelete(db, pDup);
75947 if( iCol>0 ){
75948 /* Convert the ORDER BY term into an integer column number iCol,
75949 ** taking care to preserve the COLLATE clause if it exists */
75950 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
75951 if( pNew==0 ) return 1;
75952 pNew->flags |= EP_IntValue;
75953 pNew->u.iValue = iCol;
75954 if( pItem->pExpr==pE ){
75955 pItem->pExpr = pNew;
75956 }else{
75957 assert( pItem->pExpr->op==TK_COLLATE );
75958 assert( pItem->pExpr->pLeft==pE );
75959 pItem->pExpr->pLeft = pNew;
75961 sqlite3ExprDelete(db, pE);
75962 pItem->u.x.iOrderByCol = (u16)iCol;
75963 pItem->done = 1;
75964 }else{
75965 moreToDo = 1;
75968 pSelect = pSelect->pNext;
75970 for(i=0; i<pOrderBy->nExpr; i++){
75971 if( pOrderBy->a[i].done==0 ){
75972 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
75973 "column in the result set", i+1);
75974 return 1;
75977 return 0;
75981 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
75982 ** the SELECT statement pSelect. If any term is reference to a
75983 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
75984 ** field) then convert that term into a copy of the corresponding result set
75985 ** column.
75987 ** If any errors are detected, add an error message to pParse and
75988 ** return non-zero. Return zero if no errors are seen.
75990 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
75991 Parse *pParse, /* Parsing context. Leave error messages here */
75992 Select *pSelect, /* The SELECT statement containing the clause */
75993 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
75994 const char *zType /* "ORDER" or "GROUP" */
75996 int i;
75997 sqlite3 *db = pParse->db;
75998 ExprList *pEList;
75999 struct ExprList_item *pItem;
76001 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
76002 #if SQLITE_MAX_COLUMN
76003 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
76004 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
76005 return 1;
76007 #endif
76008 pEList = pSelect->pEList;
76009 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
76010 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
76011 if( pItem->u.x.iOrderByCol ){
76012 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
76013 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
76014 return 1;
76016 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
76019 return 0;
76023 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
76024 ** The Name context of the SELECT statement is pNC. zType is either
76025 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
76027 ** This routine resolves each term of the clause into an expression.
76028 ** If the order-by term is an integer I between 1 and N (where N is the
76029 ** number of columns in the result set of the SELECT) then the expression
76030 ** in the resolution is a copy of the I-th result-set expression. If
76031 ** the order-by term is an identifier that corresponds to the AS-name of
76032 ** a result-set expression, then the term resolves to a copy of the
76033 ** result-set expression. Otherwise, the expression is resolved in
76034 ** the usual way - using sqlite3ResolveExprNames().
76036 ** This routine returns the number of errors. If errors occur, then
76037 ** an appropriate error message might be left in pParse. (OOM errors
76038 ** excepted.)
76040 static int resolveOrderGroupBy(
76041 NameContext *pNC, /* The name context of the SELECT statement */
76042 Select *pSelect, /* The SELECT statement holding pOrderBy */
76043 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
76044 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
76046 int i, j; /* Loop counters */
76047 int iCol; /* Column number */
76048 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
76049 Parse *pParse; /* Parsing context */
76050 int nResult; /* Number of terms in the result set */
76052 if( pOrderBy==0 ) return 0;
76053 nResult = pSelect->pEList->nExpr;
76054 pParse = pNC->pParse;
76055 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
76056 Expr *pE = pItem->pExpr;
76057 Expr *pE2 = sqlite3ExprSkipCollate(pE);
76058 if( zType[0]!='G' ){
76059 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
76060 if( iCol>0 ){
76061 /* If an AS-name match is found, mark this ORDER BY column as being
76062 ** a copy of the iCol-th result-set column. The subsequent call to
76063 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
76064 ** copy of the iCol-th result-set expression. */
76065 pItem->u.x.iOrderByCol = (u16)iCol;
76066 continue;
76069 if( sqlite3ExprIsInteger(pE2, &iCol) ){
76070 /* The ORDER BY term is an integer constant. Again, set the column
76071 ** number so that sqlite3ResolveOrderGroupBy() will convert the
76072 ** order-by term to a copy of the result-set expression */
76073 if( iCol<1 || iCol>0xffff ){
76074 resolveOutOfRangeError(pParse, zType, i+1, nResult);
76075 return 1;
76077 pItem->u.x.iOrderByCol = (u16)iCol;
76078 continue;
76081 /* Otherwise, treat the ORDER BY term as an ordinary expression */
76082 pItem->u.x.iOrderByCol = 0;
76083 if( sqlite3ResolveExprNames(pNC, pE) ){
76084 return 1;
76086 for(j=0; j<pSelect->pEList->nExpr; j++){
76087 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
76088 pItem->u.x.iOrderByCol = j+1;
76092 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
76096 ** Resolve names in the SELECT statement p and all of its descendents.
76098 static int resolveSelectStep(Walker *pWalker, Select *p){
76099 NameContext *pOuterNC; /* Context that contains this SELECT */
76100 NameContext sNC; /* Name context of this SELECT */
76101 int isCompound; /* True if p is a compound select */
76102 int nCompound; /* Number of compound terms processed so far */
76103 Parse *pParse; /* Parsing context */
76104 ExprList *pEList; /* Result set expression list */
76105 int i; /* Loop counter */
76106 ExprList *pGroupBy; /* The GROUP BY clause */
76107 Select *pLeftmost; /* Left-most of SELECT of a compound */
76108 sqlite3 *db; /* Database connection */
76111 assert( p!=0 );
76112 if( p->selFlags & SF_Resolved ){
76113 return WRC_Prune;
76115 pOuterNC = pWalker->u.pNC;
76116 pParse = pWalker->pParse;
76117 db = pParse->db;
76119 /* Normally sqlite3SelectExpand() will be called first and will have
76120 ** already expanded this SELECT. However, if this is a subquery within
76121 ** an expression, sqlite3ResolveExprNames() will be called without a
76122 ** prior call to sqlite3SelectExpand(). When that happens, let
76123 ** sqlite3SelectPrep() do all of the processing for this SELECT.
76124 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
76125 ** this routine in the correct order.
76127 if( (p->selFlags & SF_Expanded)==0 ){
76128 sqlite3SelectPrep(pParse, p, pOuterNC);
76129 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
76132 isCompound = p->pPrior!=0;
76133 nCompound = 0;
76134 pLeftmost = p;
76135 while( p ){
76136 assert( (p->selFlags & SF_Expanded)!=0 );
76137 assert( (p->selFlags & SF_Resolved)==0 );
76138 p->selFlags |= SF_Resolved;
76140 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
76141 ** are not allowed to refer to any names, so pass an empty NameContext.
76143 memset(&sNC, 0, sizeof(sNC));
76144 sNC.pParse = pParse;
76145 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
76146 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
76147 return WRC_Abort;
76150 /* Recursively resolve names in all subqueries
76152 for(i=0; i<p->pSrc->nSrc; i++){
76153 struct SrcList_item *pItem = &p->pSrc->a[i];
76154 if( pItem->pSelect ){
76155 NameContext *pNC; /* Used to iterate name contexts */
76156 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
76157 const char *zSavedContext = pParse->zAuthContext;
76159 /* Count the total number of references to pOuterNC and all of its
76160 ** parent contexts. After resolving references to expressions in
76161 ** pItem->pSelect, check if this value has changed. If so, then
76162 ** SELECT statement pItem->pSelect must be correlated. Set the
76163 ** pItem->isCorrelated flag if this is the case. */
76164 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
76166 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
76167 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
76168 pParse->zAuthContext = zSavedContext;
76169 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
76171 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
76172 assert( pItem->isCorrelated==0 && nRef<=0 );
76173 pItem->isCorrelated = (nRef!=0);
76177 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
76178 ** resolve the result-set expression list.
76180 sNC.ncFlags = NC_AllowAgg;
76181 sNC.pSrcList = p->pSrc;
76182 sNC.pNext = pOuterNC;
76184 /* Resolve names in the result set. */
76185 pEList = p->pEList;
76186 assert( pEList!=0 );
76187 for(i=0; i<pEList->nExpr; i++){
76188 Expr *pX = pEList->a[i].pExpr;
76189 if( sqlite3ResolveExprNames(&sNC, pX) ){
76190 return WRC_Abort;
76194 /* If there are no aggregate functions in the result-set, and no GROUP BY
76195 ** expression, do not allow aggregates in any of the other expressions.
76197 assert( (p->selFlags & SF_Aggregate)==0 );
76198 pGroupBy = p->pGroupBy;
76199 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
76200 p->selFlags |= SF_Aggregate;
76201 }else{
76202 sNC.ncFlags &= ~NC_AllowAgg;
76205 /* If a HAVING clause is present, then there must be a GROUP BY clause.
76207 if( p->pHaving && !pGroupBy ){
76208 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
76209 return WRC_Abort;
76212 /* Add the output column list to the name-context before parsing the
76213 ** other expressions in the SELECT statement. This is so that
76214 ** expressions in the WHERE clause (etc.) can refer to expressions by
76215 ** aliases in the result set.
76217 ** Minor point: If this is the case, then the expression will be
76218 ** re-evaluated for each reference to it.
76220 sNC.pEList = p->pEList;
76221 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
76222 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
76224 /* The ORDER BY and GROUP BY clauses may not refer to terms in
76225 ** outer queries
76227 sNC.pNext = 0;
76228 sNC.ncFlags |= NC_AllowAgg;
76230 /* Process the ORDER BY clause for singleton SELECT statements.
76231 ** The ORDER BY clause for compounds SELECT statements is handled
76232 ** below, after all of the result-sets for all of the elements of
76233 ** the compound have been resolved.
76235 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
76236 return WRC_Abort;
76238 if( db->mallocFailed ){
76239 return WRC_Abort;
76242 /* Resolve the GROUP BY clause. At the same time, make sure
76243 ** the GROUP BY clause does not contain aggregate functions.
76245 if( pGroupBy ){
76246 struct ExprList_item *pItem;
76248 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
76249 return WRC_Abort;
76251 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
76252 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
76253 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
76254 "the GROUP BY clause");
76255 return WRC_Abort;
76260 /* Advance to the next term of the compound
76262 p = p->pPrior;
76263 nCompound++;
76266 /* Resolve the ORDER BY on a compound SELECT after all terms of
76267 ** the compound have been resolved.
76269 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
76270 return WRC_Abort;
76273 return WRC_Prune;
76277 ** This routine walks an expression tree and resolves references to
76278 ** table columns and result-set columns. At the same time, do error
76279 ** checking on function usage and set a flag if any aggregate functions
76280 ** are seen.
76282 ** To resolve table columns references we look for nodes (or subtrees) of the
76283 ** form X.Y.Z or Y.Z or just Z where
76285 ** X: The name of a database. Ex: "main" or "temp" or
76286 ** the symbolic name assigned to an ATTACH-ed database.
76288 ** Y: The name of a table in a FROM clause. Or in a trigger
76289 ** one of the special names "old" or "new".
76291 ** Z: The name of a column in table Y.
76293 ** The node at the root of the subtree is modified as follows:
76295 ** Expr.op Changed to TK_COLUMN
76296 ** Expr.pTab Points to the Table object for X.Y
76297 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
76298 ** Expr.iTable The VDBE cursor number for X.Y
76301 ** To resolve result-set references, look for expression nodes of the
76302 ** form Z (with no X and Y prefix) where the Z matches the right-hand
76303 ** size of an AS clause in the result-set of a SELECT. The Z expression
76304 ** is replaced by a copy of the left-hand side of the result-set expression.
76305 ** Table-name and function resolution occurs on the substituted expression
76306 ** tree. For example, in:
76308 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
76310 ** The "x" term of the order by is replaced by "a+b" to render:
76312 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
76314 ** Function calls are checked to make sure that the function is
76315 ** defined and that the correct number of arguments are specified.
76316 ** If the function is an aggregate function, then the NC_HasAgg flag is
76317 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
76318 ** If an expression contains aggregate functions then the EP_Agg
76319 ** property on the expression is set.
76321 ** An error message is left in pParse if anything is amiss. The number
76322 ** if errors is returned.
76324 SQLITE_PRIVATE int sqlite3ResolveExprNames(
76325 NameContext *pNC, /* Namespace to resolve expressions in. */
76326 Expr *pExpr /* The expression to be analyzed. */
76328 u8 savedHasAgg;
76329 Walker w;
76331 if( pExpr==0 ) return 0;
76332 #if SQLITE_MAX_EXPR_DEPTH>0
76334 Parse *pParse = pNC->pParse;
76335 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
76336 return 1;
76338 pParse->nHeight += pExpr->nHeight;
76340 #endif
76341 savedHasAgg = pNC->ncFlags & NC_HasAgg;
76342 pNC->ncFlags &= ~NC_HasAgg;
76343 memset(&w, 0, sizeof(w));
76344 w.xExprCallback = resolveExprStep;
76345 w.xSelectCallback = resolveSelectStep;
76346 w.pParse = pNC->pParse;
76347 w.u.pNC = pNC;
76348 sqlite3WalkExpr(&w, pExpr);
76349 #if SQLITE_MAX_EXPR_DEPTH>0
76350 pNC->pParse->nHeight -= pExpr->nHeight;
76351 #endif
76352 if( pNC->nErr>0 || w.pParse->nErr>0 ){
76353 ExprSetProperty(pExpr, EP_Error);
76355 if( pNC->ncFlags & NC_HasAgg ){
76356 ExprSetProperty(pExpr, EP_Agg);
76357 }else if( savedHasAgg ){
76358 pNC->ncFlags |= NC_HasAgg;
76360 return ExprHasProperty(pExpr, EP_Error);
76365 ** Resolve all names in all expressions of a SELECT and in all
76366 ** decendents of the SELECT, including compounds off of p->pPrior,
76367 ** subqueries in expressions, and subqueries used as FROM clause
76368 ** terms.
76370 ** See sqlite3ResolveExprNames() for a description of the kinds of
76371 ** transformations that occur.
76373 ** All SELECT statements should have been expanded using
76374 ** sqlite3SelectExpand() prior to invoking this routine.
76376 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
76377 Parse *pParse, /* The parser context */
76378 Select *p, /* The SELECT statement being coded. */
76379 NameContext *pOuterNC /* Name context for parent SELECT statement */
76381 Walker w;
76383 assert( p!=0 );
76384 memset(&w, 0, sizeof(w));
76385 w.xExprCallback = resolveExprStep;
76386 w.xSelectCallback = resolveSelectStep;
76387 w.pParse = pParse;
76388 w.u.pNC = pOuterNC;
76389 sqlite3WalkSelect(&w, p);
76393 ** Resolve names in expressions that can only reference a single table:
76395 ** * CHECK constraints
76396 ** * WHERE clauses on partial indices
76398 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
76399 ** is set to -1 and the Expr.iColumn value is set to the column number.
76401 ** Any errors cause an error message to be set in pParse.
76403 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
76404 Parse *pParse, /* Parsing context */
76405 Table *pTab, /* The table being referenced */
76406 int type, /* NC_IsCheck or NC_PartIdx */
76407 Expr *pExpr, /* Expression to resolve. May be NULL. */
76408 ExprList *pList /* Expression list to resolve. May be NUL. */
76410 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
76411 NameContext sNC; /* Name context for pParse->pNewTable */
76412 int i; /* Loop counter */
76414 assert( type==NC_IsCheck || type==NC_PartIdx );
76415 memset(&sNC, 0, sizeof(sNC));
76416 memset(&sSrc, 0, sizeof(sSrc));
76417 sSrc.nSrc = 1;
76418 sSrc.a[0].zName = pTab->zName;
76419 sSrc.a[0].pTab = pTab;
76420 sSrc.a[0].iCursor = -1;
76421 sNC.pParse = pParse;
76422 sNC.pSrcList = &sSrc;
76423 sNC.ncFlags = type;
76424 if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
76425 if( pList ){
76426 for(i=0; i<pList->nExpr; i++){
76427 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
76428 return;
76434 /************** End of resolve.c *********************************************/
76435 /************** Begin file expr.c ********************************************/
76437 ** 2001 September 15
76439 ** The author disclaims copyright to this source code. In place of
76440 ** a legal notice, here is a blessing:
76442 ** May you do good and not evil.
76443 ** May you find forgiveness for yourself and forgive others.
76444 ** May you share freely, never taking more than you give.
76446 *************************************************************************
76447 ** This file contains routines used for analyzing expressions and
76448 ** for generating VDBE code that evaluates expressions in SQLite.
76452 ** Return the 'affinity' of the expression pExpr if any.
76454 ** If pExpr is a column, a reference to a column via an 'AS' alias,
76455 ** or a sub-select with a column as the return value, then the
76456 ** affinity of that column is returned. Otherwise, 0x00 is returned,
76457 ** indicating no affinity for the expression.
76459 ** i.e. the WHERE clause expresssions in the following statements all
76460 ** have an affinity:
76462 ** CREATE TABLE t1(a);
76463 ** SELECT * FROM t1 WHERE a;
76464 ** SELECT a AS b FROM t1 WHERE b;
76465 ** SELECT * FROM t1 WHERE (select a from t1);
76467 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
76468 int op;
76469 pExpr = sqlite3ExprSkipCollate(pExpr);
76470 op = pExpr->op;
76471 if( op==TK_SELECT ){
76472 assert( pExpr->flags&EP_xIsSelect );
76473 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
76475 #ifndef SQLITE_OMIT_CAST
76476 if( op==TK_CAST ){
76477 assert( !ExprHasProperty(pExpr, EP_IntValue) );
76478 return sqlite3AffinityType(pExpr->u.zToken, 0);
76480 #endif
76481 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
76482 && pExpr->pTab!=0
76484 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
76485 ** a TK_COLUMN but was previously evaluated and cached in a register */
76486 int j = pExpr->iColumn;
76487 if( j<0 ) return SQLITE_AFF_INTEGER;
76488 assert( pExpr->pTab && j<pExpr->pTab->nCol );
76489 return pExpr->pTab->aCol[j].affinity;
76491 return pExpr->affinity;
76495 ** Set the collating sequence for expression pExpr to be the collating
76496 ** sequence named by pToken. Return a pointer to a new Expr node that
76497 ** implements the COLLATE operator.
76499 ** If a memory allocation error occurs, that fact is recorded in pParse->db
76500 ** and the pExpr parameter is returned unchanged.
76502 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
76503 if( pCollName->n>0 ){
76504 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
76505 if( pNew ){
76506 pNew->pLeft = pExpr;
76507 pNew->flags |= EP_Collate|EP_Skip;
76508 pExpr = pNew;
76511 return pExpr;
76513 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
76514 Token s;
76515 assert( zC!=0 );
76516 s.z = zC;
76517 s.n = sqlite3Strlen30(s.z);
76518 return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
76522 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
76523 ** or likelihood() function at the root of an expression.
76525 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
76526 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
76527 if( ExprHasProperty(pExpr, EP_Unlikely) ){
76528 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76529 assert( pExpr->x.pList->nExpr>0 );
76530 assert( pExpr->op==TK_FUNCTION );
76531 pExpr = pExpr->x.pList->a[0].pExpr;
76532 }else{
76533 assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
76534 pExpr = pExpr->pLeft;
76537 return pExpr;
76541 ** Return the collation sequence for the expression pExpr. If
76542 ** there is no defined collating sequence, return NULL.
76544 ** The collating sequence might be determined by a COLLATE operator
76545 ** or by the presence of a column with a defined collating sequence.
76546 ** COLLATE operators take first precedence. Left operands take
76547 ** precedence over right operands.
76549 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
76550 sqlite3 *db = pParse->db;
76551 CollSeq *pColl = 0;
76552 Expr *p = pExpr;
76553 while( p ){
76554 int op = p->op;
76555 if( op==TK_CAST || op==TK_UPLUS ){
76556 p = p->pLeft;
76557 continue;
76559 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
76560 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
76561 break;
76563 if( p->pTab!=0
76564 && (op==TK_AGG_COLUMN || op==TK_COLUMN
76565 || op==TK_REGISTER || op==TK_TRIGGER)
76567 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
76568 ** a TK_COLUMN but was previously evaluated and cached in a register */
76569 int j = p->iColumn;
76570 if( j>=0 ){
76571 const char *zColl = p->pTab->aCol[j].zColl;
76572 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
76574 break;
76576 if( p->flags & EP_Collate ){
76577 if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
76578 p = p->pLeft;
76579 }else{
76580 p = p->pRight;
76582 }else{
76583 break;
76586 if( sqlite3CheckCollSeq(pParse, pColl) ){
76587 pColl = 0;
76589 return pColl;
76593 ** pExpr is an operand of a comparison operator. aff2 is the
76594 ** type affinity of the other operand. This routine returns the
76595 ** type affinity that should be used for the comparison operator.
76597 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
76598 char aff1 = sqlite3ExprAffinity(pExpr);
76599 if( aff1 && aff2 ){
76600 /* Both sides of the comparison are columns. If one has numeric
76601 ** affinity, use that. Otherwise use no affinity.
76603 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
76604 return SQLITE_AFF_NUMERIC;
76605 }else{
76606 return SQLITE_AFF_NONE;
76608 }else if( !aff1 && !aff2 ){
76609 /* Neither side of the comparison is a column. Compare the
76610 ** results directly.
76612 return SQLITE_AFF_NONE;
76613 }else{
76614 /* One side is a column, the other is not. Use the columns affinity. */
76615 assert( aff1==0 || aff2==0 );
76616 return (aff1 + aff2);
76621 ** pExpr is a comparison operator. Return the type affinity that should
76622 ** be applied to both operands prior to doing the comparison.
76624 static char comparisonAffinity(Expr *pExpr){
76625 char aff;
76626 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
76627 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
76628 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
76629 assert( pExpr->pLeft );
76630 aff = sqlite3ExprAffinity(pExpr->pLeft);
76631 if( pExpr->pRight ){
76632 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
76633 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76634 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
76635 }else if( !aff ){
76636 aff = SQLITE_AFF_NONE;
76638 return aff;
76642 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
76643 ** idx_affinity is the affinity of an indexed column. Return true
76644 ** if the index with affinity idx_affinity may be used to implement
76645 ** the comparison in pExpr.
76647 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
76648 char aff = comparisonAffinity(pExpr);
76649 switch( aff ){
76650 case SQLITE_AFF_NONE:
76651 return 1;
76652 case SQLITE_AFF_TEXT:
76653 return idx_affinity==SQLITE_AFF_TEXT;
76654 default:
76655 return sqlite3IsNumericAffinity(idx_affinity);
76660 ** Return the P5 value that should be used for a binary comparison
76661 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
76663 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
76664 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
76665 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
76666 return aff;
76670 ** Return a pointer to the collation sequence that should be used by
76671 ** a binary comparison operator comparing pLeft and pRight.
76673 ** If the left hand expression has a collating sequence type, then it is
76674 ** used. Otherwise the collation sequence for the right hand expression
76675 ** is used, or the default (BINARY) if neither expression has a collating
76676 ** type.
76678 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
76679 ** it is not considered.
76681 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
76682 Parse *pParse,
76683 Expr *pLeft,
76684 Expr *pRight
76686 CollSeq *pColl;
76687 assert( pLeft );
76688 if( pLeft->flags & EP_Collate ){
76689 pColl = sqlite3ExprCollSeq(pParse, pLeft);
76690 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
76691 pColl = sqlite3ExprCollSeq(pParse, pRight);
76692 }else{
76693 pColl = sqlite3ExprCollSeq(pParse, pLeft);
76694 if( !pColl ){
76695 pColl = sqlite3ExprCollSeq(pParse, pRight);
76698 return pColl;
76702 ** Generate code for a comparison operator.
76704 static int codeCompare(
76705 Parse *pParse, /* The parsing (and code generating) context */
76706 Expr *pLeft, /* The left operand */
76707 Expr *pRight, /* The right operand */
76708 int opcode, /* The comparison opcode */
76709 int in1, int in2, /* Register holding operands */
76710 int dest, /* Jump here if true. */
76711 int jumpIfNull /* If true, jump if either operand is NULL */
76713 int p5;
76714 int addr;
76715 CollSeq *p4;
76717 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
76718 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
76719 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
76720 (void*)p4, P4_COLLSEQ);
76721 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
76722 return addr;
76725 #if SQLITE_MAX_EXPR_DEPTH>0
76727 ** Check that argument nHeight is less than or equal to the maximum
76728 ** expression depth allowed. If it is not, leave an error message in
76729 ** pParse.
76731 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
76732 int rc = SQLITE_OK;
76733 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
76734 if( nHeight>mxHeight ){
76735 sqlite3ErrorMsg(pParse,
76736 "Expression tree is too large (maximum depth %d)", mxHeight
76738 rc = SQLITE_ERROR;
76740 return rc;
76743 /* The following three functions, heightOfExpr(), heightOfExprList()
76744 ** and heightOfSelect(), are used to determine the maximum height
76745 ** of any expression tree referenced by the structure passed as the
76746 ** first argument.
76748 ** If this maximum height is greater than the current value pointed
76749 ** to by pnHeight, the second parameter, then set *pnHeight to that
76750 ** value.
76752 static void heightOfExpr(Expr *p, int *pnHeight){
76753 if( p ){
76754 if( p->nHeight>*pnHeight ){
76755 *pnHeight = p->nHeight;
76759 static void heightOfExprList(ExprList *p, int *pnHeight){
76760 if( p ){
76761 int i;
76762 for(i=0; i<p->nExpr; i++){
76763 heightOfExpr(p->a[i].pExpr, pnHeight);
76767 static void heightOfSelect(Select *p, int *pnHeight){
76768 if( p ){
76769 heightOfExpr(p->pWhere, pnHeight);
76770 heightOfExpr(p->pHaving, pnHeight);
76771 heightOfExpr(p->pLimit, pnHeight);
76772 heightOfExpr(p->pOffset, pnHeight);
76773 heightOfExprList(p->pEList, pnHeight);
76774 heightOfExprList(p->pGroupBy, pnHeight);
76775 heightOfExprList(p->pOrderBy, pnHeight);
76776 heightOfSelect(p->pPrior, pnHeight);
76781 ** Set the Expr.nHeight variable in the structure passed as an
76782 ** argument. An expression with no children, Expr.pList or
76783 ** Expr.pSelect member has a height of 1. Any other expression
76784 ** has a height equal to the maximum height of any other
76785 ** referenced Expr plus one.
76787 static void exprSetHeight(Expr *p){
76788 int nHeight = 0;
76789 heightOfExpr(p->pLeft, &nHeight);
76790 heightOfExpr(p->pRight, &nHeight);
76791 if( ExprHasProperty(p, EP_xIsSelect) ){
76792 heightOfSelect(p->x.pSelect, &nHeight);
76793 }else{
76794 heightOfExprList(p->x.pList, &nHeight);
76796 p->nHeight = nHeight + 1;
76800 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
76801 ** the height is greater than the maximum allowed expression depth,
76802 ** leave an error in pParse.
76804 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
76805 exprSetHeight(p);
76806 sqlite3ExprCheckHeight(pParse, p->nHeight);
76810 ** Return the maximum height of any expression tree referenced
76811 ** by the select statement passed as an argument.
76813 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
76814 int nHeight = 0;
76815 heightOfSelect(p, &nHeight);
76816 return nHeight;
76818 #else
76819 #define exprSetHeight(y)
76820 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
76823 ** This routine is the core allocator for Expr nodes.
76825 ** Construct a new expression node and return a pointer to it. Memory
76826 ** for this node and for the pToken argument is a single allocation
76827 ** obtained from sqlite3DbMalloc(). The calling function
76828 ** is responsible for making sure the node eventually gets freed.
76830 ** If dequote is true, then the token (if it exists) is dequoted.
76831 ** If dequote is false, no dequoting is performance. The deQuote
76832 ** parameter is ignored if pToken is NULL or if the token does not
76833 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
76834 ** then the EP_DblQuoted flag is set on the expression node.
76836 ** Special case: If op==TK_INTEGER and pToken points to a string that
76837 ** can be translated into a 32-bit integer, then the token is not
76838 ** stored in u.zToken. Instead, the integer values is written
76839 ** into u.iValue and the EP_IntValue flag is set. No extra storage
76840 ** is allocated to hold the integer text and the dequote flag is ignored.
76842 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
76843 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
76844 int op, /* Expression opcode */
76845 const Token *pToken, /* Token argument. Might be NULL */
76846 int dequote /* True to dequote */
76848 Expr *pNew;
76849 int nExtra = 0;
76850 int iValue = 0;
76852 if( pToken ){
76853 if( op!=TK_INTEGER || pToken->z==0
76854 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
76855 nExtra = pToken->n+1;
76856 assert( iValue>=0 );
76859 pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
76860 if( pNew ){
76861 pNew->op = (u8)op;
76862 pNew->iAgg = -1;
76863 if( pToken ){
76864 if( nExtra==0 ){
76865 pNew->flags |= EP_IntValue;
76866 pNew->u.iValue = iValue;
76867 }else{
76868 int c;
76869 pNew->u.zToken = (char*)&pNew[1];
76870 assert( pToken->z!=0 || pToken->n==0 );
76871 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
76872 pNew->u.zToken[pToken->n] = 0;
76873 if( dequote && nExtra>=3
76874 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
76875 sqlite3Dequote(pNew->u.zToken);
76876 if( c=='"' ) pNew->flags |= EP_DblQuoted;
76880 #if SQLITE_MAX_EXPR_DEPTH>0
76881 pNew->nHeight = 1;
76882 #endif
76884 return pNew;
76888 ** Allocate a new expression node from a zero-terminated token that has
76889 ** already been dequoted.
76891 SQLITE_PRIVATE Expr *sqlite3Expr(
76892 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
76893 int op, /* Expression opcode */
76894 const char *zToken /* Token argument. Might be NULL */
76896 Token x;
76897 x.z = zToken;
76898 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
76899 return sqlite3ExprAlloc(db, op, &x, 0);
76903 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
76905 ** If pRoot==NULL that means that a memory allocation error has occurred.
76906 ** In that case, delete the subtrees pLeft and pRight.
76908 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
76909 sqlite3 *db,
76910 Expr *pRoot,
76911 Expr *pLeft,
76912 Expr *pRight
76914 if( pRoot==0 ){
76915 assert( db->mallocFailed );
76916 sqlite3ExprDelete(db, pLeft);
76917 sqlite3ExprDelete(db, pRight);
76918 }else{
76919 if( pRight ){
76920 pRoot->pRight = pRight;
76921 pRoot->flags |= EP_Collate & pRight->flags;
76923 if( pLeft ){
76924 pRoot->pLeft = pLeft;
76925 pRoot->flags |= EP_Collate & pLeft->flags;
76927 exprSetHeight(pRoot);
76932 ** Allocate a Expr node which joins as many as two subtrees.
76934 ** One or both of the subtrees can be NULL. Return a pointer to the new
76935 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
76936 ** free the subtrees and return NULL.
76938 SQLITE_PRIVATE Expr *sqlite3PExpr(
76939 Parse *pParse, /* Parsing context */
76940 int op, /* Expression opcode */
76941 Expr *pLeft, /* Left operand */
76942 Expr *pRight, /* Right operand */
76943 const Token *pToken /* Argument token */
76945 Expr *p;
76946 if( op==TK_AND && pLeft && pRight ){
76947 /* Take advantage of short-circuit false optimization for AND */
76948 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
76949 }else{
76950 p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
76951 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
76953 if( p ) {
76954 sqlite3ExprCheckHeight(pParse, p->nHeight);
76956 return p;
76960 ** If the expression is always either TRUE or FALSE (respectively),
76961 ** then return 1. If one cannot determine the truth value of the
76962 ** expression at compile-time return 0.
76964 ** This is an optimization. If is OK to return 0 here even if
76965 ** the expression really is always false or false (a false negative).
76966 ** But it is a bug to return 1 if the expression might have different
76967 ** boolean values in different circumstances (a false positive.)
76969 ** Note that if the expression is part of conditional for a
76970 ** LEFT JOIN, then we cannot determine at compile-time whether or not
76971 ** is it true or false, so always return 0.
76973 static int exprAlwaysTrue(Expr *p){
76974 int v = 0;
76975 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
76976 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
76977 return v!=0;
76979 static int exprAlwaysFalse(Expr *p){
76980 int v = 0;
76981 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
76982 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
76983 return v==0;
76987 ** Join two expressions using an AND operator. If either expression is
76988 ** NULL, then just return the other expression.
76990 ** If one side or the other of the AND is known to be false, then instead
76991 ** of returning an AND expression, just return a constant expression with
76992 ** a value of false.
76994 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
76995 if( pLeft==0 ){
76996 return pRight;
76997 }else if( pRight==0 ){
76998 return pLeft;
76999 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
77000 sqlite3ExprDelete(db, pLeft);
77001 sqlite3ExprDelete(db, pRight);
77002 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
77003 }else{
77004 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
77005 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
77006 return pNew;
77011 ** Construct a new expression node for a function with multiple
77012 ** arguments.
77014 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
77015 Expr *pNew;
77016 sqlite3 *db = pParse->db;
77017 assert( pToken );
77018 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
77019 if( pNew==0 ){
77020 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
77021 return 0;
77023 pNew->x.pList = pList;
77024 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
77025 sqlite3ExprSetHeight(pParse, pNew);
77026 return pNew;
77030 ** Assign a variable number to an expression that encodes a wildcard
77031 ** in the original SQL statement.
77033 ** Wildcards consisting of a single "?" are assigned the next sequential
77034 ** variable number.
77036 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
77037 ** sure "nnn" is not too be to avoid a denial of service attack when
77038 ** the SQL statement comes from an external source.
77040 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
77041 ** as the previous instance of the same wildcard. Or if this is the first
77042 ** instance of the wildcard, the next sequenial variable number is
77043 ** assigned.
77045 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
77046 sqlite3 *db = pParse->db;
77047 const char *z;
77049 if( pExpr==0 ) return;
77050 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
77051 z = pExpr->u.zToken;
77052 assert( z!=0 );
77053 assert( z[0]!=0 );
77054 if( z[1]==0 ){
77055 /* Wildcard of the form "?". Assign the next variable number */
77056 assert( z[0]=='?' );
77057 pExpr->iColumn = (ynVar)(++pParse->nVar);
77058 }else{
77059 ynVar x = 0;
77060 u32 n = sqlite3Strlen30(z);
77061 if( z[0]=='?' ){
77062 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
77063 ** use it as the variable number */
77064 i64 i;
77065 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
77066 pExpr->iColumn = x = (ynVar)i;
77067 testcase( i==0 );
77068 testcase( i==1 );
77069 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
77070 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
77071 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
77072 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
77073 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
77074 x = 0;
77076 if( i>pParse->nVar ){
77077 pParse->nVar = (int)i;
77079 }else{
77080 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
77081 ** number as the prior appearance of the same name, or if the name
77082 ** has never appeared before, reuse the same variable number
77084 ynVar i;
77085 for(i=0; i<pParse->nzVar; i++){
77086 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
77087 pExpr->iColumn = x = (ynVar)i+1;
77088 break;
77091 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
77093 if( x>0 ){
77094 if( x>pParse->nzVar ){
77095 char **a;
77096 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
77097 if( a==0 ) return; /* Error reported through db->mallocFailed */
77098 pParse->azVar = a;
77099 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
77100 pParse->nzVar = x;
77102 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
77103 sqlite3DbFree(db, pParse->azVar[x-1]);
77104 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
77108 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
77109 sqlite3ErrorMsg(pParse, "too many SQL variables");
77114 ** Recursively delete an expression tree.
77116 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
77117 if( p==0 ) return;
77118 /* Sanity check: Assert that the IntValue is non-negative if it exists */
77119 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
77120 if( !ExprHasProperty(p, EP_TokenOnly) ){
77121 /* The Expr.x union is never used at the same time as Expr.pRight */
77122 assert( p->x.pList==0 || p->pRight==0 );
77123 sqlite3ExprDelete(db, p->pLeft);
77124 sqlite3ExprDelete(db, p->pRight);
77125 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
77126 if( ExprHasProperty(p, EP_xIsSelect) ){
77127 sqlite3SelectDelete(db, p->x.pSelect);
77128 }else{
77129 sqlite3ExprListDelete(db, p->x.pList);
77132 if( !ExprHasProperty(p, EP_Static) ){
77133 sqlite3DbFree(db, p);
77138 ** Return the number of bytes allocated for the expression structure
77139 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
77140 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
77142 static int exprStructSize(Expr *p){
77143 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
77144 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
77145 return EXPR_FULLSIZE;
77149 ** The dupedExpr*Size() routines each return the number of bytes required
77150 ** to store a copy of an expression or expression tree. They differ in
77151 ** how much of the tree is measured.
77153 ** dupedExprStructSize() Size of only the Expr structure
77154 ** dupedExprNodeSize() Size of Expr + space for token
77155 ** dupedExprSize() Expr + token + subtree components
77157 ***************************************************************************
77159 ** The dupedExprStructSize() function returns two values OR-ed together:
77160 ** (1) the space required for a copy of the Expr structure only and
77161 ** (2) the EP_xxx flags that indicate what the structure size should be.
77162 ** The return values is always one of:
77164 ** EXPR_FULLSIZE
77165 ** EXPR_REDUCEDSIZE | EP_Reduced
77166 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
77168 ** The size of the structure can be found by masking the return value
77169 ** of this routine with 0xfff. The flags can be found by masking the
77170 ** return value with EP_Reduced|EP_TokenOnly.
77172 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
77173 ** (unreduced) Expr objects as they or originally constructed by the parser.
77174 ** During expression analysis, extra information is computed and moved into
77175 ** later parts of teh Expr object and that extra information might get chopped
77176 ** off if the expression is reduced. Note also that it does not work to
77177 ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
77178 ** to reduce a pristine expression tree from the parser. The implementation
77179 ** of dupedExprStructSize() contain multiple assert() statements that attempt
77180 ** to enforce this constraint.
77182 static int dupedExprStructSize(Expr *p, int flags){
77183 int nSize;
77184 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
77185 assert( EXPR_FULLSIZE<=0xfff );
77186 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
77187 if( 0==(flags&EXPRDUP_REDUCE) ){
77188 nSize = EXPR_FULLSIZE;
77189 }else{
77190 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
77191 assert( !ExprHasProperty(p, EP_FromJoin) );
77192 assert( !ExprHasProperty(p, EP_MemToken) );
77193 assert( !ExprHasProperty(p, EP_NoReduce) );
77194 if( p->pLeft || p->x.pList ){
77195 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
77196 }else{
77197 assert( p->pRight==0 );
77198 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
77201 return nSize;
77205 ** This function returns the space in bytes required to store the copy
77206 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
77207 ** string is defined.)
77209 static int dupedExprNodeSize(Expr *p, int flags){
77210 int nByte = dupedExprStructSize(p, flags) & 0xfff;
77211 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
77212 nByte += sqlite3Strlen30(p->u.zToken)+1;
77214 return ROUND8(nByte);
77218 ** Return the number of bytes required to create a duplicate of the
77219 ** expression passed as the first argument. The second argument is a
77220 ** mask containing EXPRDUP_XXX flags.
77222 ** The value returned includes space to create a copy of the Expr struct
77223 ** itself and the buffer referred to by Expr.u.zToken, if any.
77225 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
77226 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
77227 ** and Expr.pRight variables (but not for any structures pointed to or
77228 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
77230 static int dupedExprSize(Expr *p, int flags){
77231 int nByte = 0;
77232 if( p ){
77233 nByte = dupedExprNodeSize(p, flags);
77234 if( flags&EXPRDUP_REDUCE ){
77235 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
77238 return nByte;
77242 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
77243 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
77244 ** to store the copy of expression p, the copies of p->u.zToken
77245 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
77246 ** if any. Before returning, *pzBuffer is set to the first byte passed the
77247 ** portion of the buffer copied into by this function.
77249 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
77250 Expr *pNew = 0; /* Value to return */
77251 if( p ){
77252 const int isReduced = (flags&EXPRDUP_REDUCE);
77253 u8 *zAlloc;
77254 u32 staticFlag = 0;
77256 assert( pzBuffer==0 || isReduced );
77258 /* Figure out where to write the new Expr structure. */
77259 if( pzBuffer ){
77260 zAlloc = *pzBuffer;
77261 staticFlag = EP_Static;
77262 }else{
77263 zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
77265 pNew = (Expr *)zAlloc;
77267 if( pNew ){
77268 /* Set nNewSize to the size allocated for the structure pointed to
77269 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
77270 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
77271 ** by the copy of the p->u.zToken string (if any).
77273 const unsigned nStructSize = dupedExprStructSize(p, flags);
77274 const int nNewSize = nStructSize & 0xfff;
77275 int nToken;
77276 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
77277 nToken = sqlite3Strlen30(p->u.zToken) + 1;
77278 }else{
77279 nToken = 0;
77281 if( isReduced ){
77282 assert( ExprHasProperty(p, EP_Reduced)==0 );
77283 memcpy(zAlloc, p, nNewSize);
77284 }else{
77285 int nSize = exprStructSize(p);
77286 memcpy(zAlloc, p, nSize);
77287 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
77290 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
77291 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
77292 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
77293 pNew->flags |= staticFlag;
77295 /* Copy the p->u.zToken string, if any. */
77296 if( nToken ){
77297 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
77298 memcpy(zToken, p->u.zToken, nToken);
77301 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
77302 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
77303 if( ExprHasProperty(p, EP_xIsSelect) ){
77304 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
77305 }else{
77306 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
77310 /* Fill in pNew->pLeft and pNew->pRight. */
77311 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
77312 zAlloc += dupedExprNodeSize(p, flags);
77313 if( ExprHasProperty(pNew, EP_Reduced) ){
77314 pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
77315 pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
77317 if( pzBuffer ){
77318 *pzBuffer = zAlloc;
77320 }else{
77321 if( !ExprHasProperty(p, EP_TokenOnly) ){
77322 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
77323 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
77329 return pNew;
77333 ** Create and return a deep copy of the object passed as the second
77334 ** argument. If an OOM condition is encountered, NULL is returned
77335 ** and the db->mallocFailed flag set.
77337 #ifndef SQLITE_OMIT_CTE
77338 static With *withDup(sqlite3 *db, With *p){
77339 With *pRet = 0;
77340 if( p ){
77341 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
77342 pRet = sqlite3DbMallocZero(db, nByte);
77343 if( pRet ){
77344 int i;
77345 pRet->nCte = p->nCte;
77346 for(i=0; i<p->nCte; i++){
77347 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
77348 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
77349 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
77353 return pRet;
77355 #else
77356 # define withDup(x,y) 0
77357 #endif
77360 ** The following group of routines make deep copies of expressions,
77361 ** expression lists, ID lists, and select statements. The copies can
77362 ** be deleted (by being passed to their respective ...Delete() routines)
77363 ** without effecting the originals.
77365 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
77366 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
77367 ** by subsequent calls to sqlite*ListAppend() routines.
77369 ** Any tables that the SrcList might point to are not duplicated.
77371 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
77372 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
77373 ** truncated version of the usual Expr structure that will be stored as
77374 ** part of the in-memory representation of the database schema.
77376 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
77377 return exprDup(db, p, flags, 0);
77379 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
77380 ExprList *pNew;
77381 struct ExprList_item *pItem, *pOldItem;
77382 int i;
77383 if( p==0 ) return 0;
77384 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
77385 if( pNew==0 ) return 0;
77386 pNew->iECursor = 0;
77387 pNew->nExpr = i = p->nExpr;
77388 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
77389 pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
77390 if( pItem==0 ){
77391 sqlite3DbFree(db, pNew);
77392 return 0;
77394 pOldItem = p->a;
77395 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
77396 Expr *pOldExpr = pOldItem->pExpr;
77397 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
77398 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
77399 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
77400 pItem->sortOrder = pOldItem->sortOrder;
77401 pItem->done = 0;
77402 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
77403 pItem->u = pOldItem->u;
77405 return pNew;
77409 ** If cursors, triggers, views and subqueries are all omitted from
77410 ** the build, then none of the following routines, except for
77411 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
77412 ** called with a NULL argument.
77414 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
77415 || !defined(SQLITE_OMIT_SUBQUERY)
77416 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
77417 SrcList *pNew;
77418 int i;
77419 int nByte;
77420 if( p==0 ) return 0;
77421 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
77422 pNew = sqlite3DbMallocRaw(db, nByte );
77423 if( pNew==0 ) return 0;
77424 pNew->nSrc = pNew->nAlloc = p->nSrc;
77425 for(i=0; i<p->nSrc; i++){
77426 struct SrcList_item *pNewItem = &pNew->a[i];
77427 struct SrcList_item *pOldItem = &p->a[i];
77428 Table *pTab;
77429 pNewItem->pSchema = pOldItem->pSchema;
77430 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
77431 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
77432 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
77433 pNewItem->jointype = pOldItem->jointype;
77434 pNewItem->iCursor = pOldItem->iCursor;
77435 pNewItem->addrFillSub = pOldItem->addrFillSub;
77436 pNewItem->regReturn = pOldItem->regReturn;
77437 pNewItem->isCorrelated = pOldItem->isCorrelated;
77438 pNewItem->viaCoroutine = pOldItem->viaCoroutine;
77439 pNewItem->isRecursive = pOldItem->isRecursive;
77440 pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
77441 pNewItem->notIndexed = pOldItem->notIndexed;
77442 pNewItem->pIndex = pOldItem->pIndex;
77443 pTab = pNewItem->pTab = pOldItem->pTab;
77444 if( pTab ){
77445 pTab->nRef++;
77447 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
77448 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
77449 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
77450 pNewItem->colUsed = pOldItem->colUsed;
77452 return pNew;
77454 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
77455 IdList *pNew;
77456 int i;
77457 if( p==0 ) return 0;
77458 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
77459 if( pNew==0 ) return 0;
77460 pNew->nId = p->nId;
77461 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
77462 if( pNew->a==0 ){
77463 sqlite3DbFree(db, pNew);
77464 return 0;
77466 /* Note that because the size of the allocation for p->a[] is not
77467 ** necessarily a power of two, sqlite3IdListAppend() may not be called
77468 ** on the duplicate created by this function. */
77469 for(i=0; i<p->nId; i++){
77470 struct IdList_item *pNewItem = &pNew->a[i];
77471 struct IdList_item *pOldItem = &p->a[i];
77472 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
77473 pNewItem->idx = pOldItem->idx;
77475 return pNew;
77477 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
77478 Select *pNew, *pPrior;
77479 if( p==0 ) return 0;
77480 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
77481 if( pNew==0 ) return 0;
77482 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
77483 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
77484 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
77485 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
77486 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
77487 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
77488 pNew->op = p->op;
77489 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
77490 if( pPrior ) pPrior->pNext = pNew;
77491 pNew->pNext = 0;
77492 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
77493 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
77494 pNew->iLimit = 0;
77495 pNew->iOffset = 0;
77496 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
77497 pNew->pRightmost = 0;
77498 pNew->addrOpenEphm[0] = -1;
77499 pNew->addrOpenEphm[1] = -1;
77500 pNew->addrOpenEphm[2] = -1;
77501 pNew->nSelectRow = p->nSelectRow;
77502 pNew->pWith = withDup(db, p->pWith);
77503 return pNew;
77505 #else
77506 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
77507 assert( p==0 );
77508 return 0;
77510 #endif
77514 ** Add a new element to the end of an expression list. If pList is
77515 ** initially NULL, then create a new expression list.
77517 ** If a memory allocation error occurs, the entire list is freed and
77518 ** NULL is returned. If non-NULL is returned, then it is guaranteed
77519 ** that the new entry was successfully appended.
77521 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
77522 Parse *pParse, /* Parsing context */
77523 ExprList *pList, /* List to which to append. Might be NULL */
77524 Expr *pExpr /* Expression to be appended. Might be NULL */
77526 sqlite3 *db = pParse->db;
77527 if( pList==0 ){
77528 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
77529 if( pList==0 ){
77530 goto no_mem;
77532 pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
77533 if( pList->a==0 ) goto no_mem;
77534 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
77535 struct ExprList_item *a;
77536 assert( pList->nExpr>0 );
77537 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
77538 if( a==0 ){
77539 goto no_mem;
77541 pList->a = a;
77543 assert( pList->a!=0 );
77544 if( 1 ){
77545 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
77546 memset(pItem, 0, sizeof(*pItem));
77547 pItem->pExpr = pExpr;
77549 return pList;
77551 no_mem:
77552 /* Avoid leaking memory if malloc has failed. */
77553 sqlite3ExprDelete(db, pExpr);
77554 sqlite3ExprListDelete(db, pList);
77555 return 0;
77559 ** Set the ExprList.a[].zName element of the most recently added item
77560 ** on the expression list.
77562 ** pList might be NULL following an OOM error. But pName should never be
77563 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
77564 ** is set.
77566 SQLITE_PRIVATE void sqlite3ExprListSetName(
77567 Parse *pParse, /* Parsing context */
77568 ExprList *pList, /* List to which to add the span. */
77569 Token *pName, /* Name to be added */
77570 int dequote /* True to cause the name to be dequoted */
77572 assert( pList!=0 || pParse->db->mallocFailed!=0 );
77573 if( pList ){
77574 struct ExprList_item *pItem;
77575 assert( pList->nExpr>0 );
77576 pItem = &pList->a[pList->nExpr-1];
77577 assert( pItem->zName==0 );
77578 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
77579 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
77584 ** Set the ExprList.a[].zSpan element of the most recently added item
77585 ** on the expression list.
77587 ** pList might be NULL following an OOM error. But pSpan should never be
77588 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
77589 ** is set.
77591 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
77592 Parse *pParse, /* Parsing context */
77593 ExprList *pList, /* List to which to add the span. */
77594 ExprSpan *pSpan /* The span to be added */
77596 sqlite3 *db = pParse->db;
77597 assert( pList!=0 || db->mallocFailed!=0 );
77598 if( pList ){
77599 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
77600 assert( pList->nExpr>0 );
77601 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
77602 sqlite3DbFree(db, pItem->zSpan);
77603 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
77604 (int)(pSpan->zEnd - pSpan->zStart));
77609 ** If the expression list pEList contains more than iLimit elements,
77610 ** leave an error message in pParse.
77612 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
77613 Parse *pParse,
77614 ExprList *pEList,
77615 const char *zObject
77617 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
77618 testcase( pEList && pEList->nExpr==mx );
77619 testcase( pEList && pEList->nExpr==mx+1 );
77620 if( pEList && pEList->nExpr>mx ){
77621 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
77626 ** Delete an entire expression list.
77628 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
77629 int i;
77630 struct ExprList_item *pItem;
77631 if( pList==0 ) return;
77632 assert( pList->a!=0 || pList->nExpr==0 );
77633 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
77634 sqlite3ExprDelete(db, pItem->pExpr);
77635 sqlite3DbFree(db, pItem->zName);
77636 sqlite3DbFree(db, pItem->zSpan);
77638 sqlite3DbFree(db, pList->a);
77639 sqlite3DbFree(db, pList);
77643 ** These routines are Walker callbacks. Walker.u.pi is a pointer
77644 ** to an integer. These routines are checking an expression to see
77645 ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
77646 ** not constant.
77648 ** These callback routines are used to implement the following:
77650 ** sqlite3ExprIsConstant()
77651 ** sqlite3ExprIsConstantNotJoin()
77652 ** sqlite3ExprIsConstantOrFunction()
77655 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
77657 /* If pWalker->u.i is 3 then any term of the expression that comes from
77658 ** the ON or USING clauses of a join disqualifies the expression
77659 ** from being considered constant. */
77660 if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
77661 pWalker->u.i = 0;
77662 return WRC_Abort;
77665 switch( pExpr->op ){
77666 /* Consider functions to be constant if all their arguments are constant
77667 ** and either pWalker->u.i==2 or the function as the SQLITE_FUNC_CONST
77668 ** flag. */
77669 case TK_FUNCTION:
77670 if( pWalker->u.i==2 || ExprHasProperty(pExpr,EP_Constant) ){
77671 return WRC_Continue;
77673 /* Fall through */
77674 case TK_ID:
77675 case TK_COLUMN:
77676 case TK_AGG_FUNCTION:
77677 case TK_AGG_COLUMN:
77678 testcase( pExpr->op==TK_ID );
77679 testcase( pExpr->op==TK_COLUMN );
77680 testcase( pExpr->op==TK_AGG_FUNCTION );
77681 testcase( pExpr->op==TK_AGG_COLUMN );
77682 pWalker->u.i = 0;
77683 return WRC_Abort;
77684 default:
77685 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
77686 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
77687 return WRC_Continue;
77690 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
77691 UNUSED_PARAMETER(NotUsed);
77692 pWalker->u.i = 0;
77693 return WRC_Abort;
77695 static int exprIsConst(Expr *p, int initFlag){
77696 Walker w;
77697 memset(&w, 0, sizeof(w));
77698 w.u.i = initFlag;
77699 w.xExprCallback = exprNodeIsConstant;
77700 w.xSelectCallback = selectNodeIsConstant;
77701 sqlite3WalkExpr(&w, p);
77702 return w.u.i;
77706 ** Walk an expression tree. Return 1 if the expression is constant
77707 ** and 0 if it involves variables or function calls.
77709 ** For the purposes of this function, a double-quoted string (ex: "abc")
77710 ** is considered a variable but a single-quoted string (ex: 'abc') is
77711 ** a constant.
77713 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
77714 return exprIsConst(p, 1);
77718 ** Walk an expression tree. Return 1 if the expression is constant
77719 ** that does no originate from the ON or USING clauses of a join.
77720 ** Return 0 if it involves variables or function calls or terms from
77721 ** an ON or USING clause.
77723 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
77724 return exprIsConst(p, 3);
77728 ** Walk an expression tree. Return 1 if the expression is constant
77729 ** or a function call with constant arguments. Return and 0 if there
77730 ** are any variables.
77732 ** For the purposes of this function, a double-quoted string (ex: "abc")
77733 ** is considered a variable but a single-quoted string (ex: 'abc') is
77734 ** a constant.
77736 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
77737 return exprIsConst(p, 2);
77741 ** If the expression p codes a constant integer that is small enough
77742 ** to fit in a 32-bit integer, return 1 and put the value of the integer
77743 ** in *pValue. If the expression is not an integer or if it is too big
77744 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
77746 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
77747 int rc = 0;
77749 /* If an expression is an integer literal that fits in a signed 32-bit
77750 ** integer, then the EP_IntValue flag will have already been set */
77751 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
77752 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
77754 if( p->flags & EP_IntValue ){
77755 *pValue = p->u.iValue;
77756 return 1;
77758 switch( p->op ){
77759 case TK_UPLUS: {
77760 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
77761 break;
77763 case TK_UMINUS: {
77764 int v;
77765 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
77766 assert( v!=(-2147483647-1) );
77767 *pValue = -v;
77768 rc = 1;
77770 break;
77772 default: break;
77774 return rc;
77778 ** Return FALSE if there is no chance that the expression can be NULL.
77780 ** If the expression might be NULL or if the expression is too complex
77781 ** to tell return TRUE.
77783 ** This routine is used as an optimization, to skip OP_IsNull opcodes
77784 ** when we know that a value cannot be NULL. Hence, a false positive
77785 ** (returning TRUE when in fact the expression can never be NULL) might
77786 ** be a small performance hit but is otherwise harmless. On the other
77787 ** hand, a false negative (returning FALSE when the result could be NULL)
77788 ** will likely result in an incorrect answer. So when in doubt, return
77789 ** TRUE.
77791 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
77792 u8 op;
77793 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
77794 op = p->op;
77795 if( op==TK_REGISTER ) op = p->op2;
77796 switch( op ){
77797 case TK_INTEGER:
77798 case TK_STRING:
77799 case TK_FLOAT:
77800 case TK_BLOB:
77801 return 0;
77802 default:
77803 return 1;
77808 ** Generate an OP_IsNull instruction that tests register iReg and jumps
77809 ** to location iDest if the value in iReg is NULL. The value in iReg
77810 ** was computed by pExpr. If we can look at pExpr at compile-time and
77811 ** determine that it can never generate a NULL, then the OP_IsNull operation
77812 ** can be omitted.
77814 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
77815 Vdbe *v, /* The VDBE under construction */
77816 const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
77817 int iReg, /* Test the value in this register for NULL */
77818 int iDest /* Jump here if the value is null */
77820 if( sqlite3ExprCanBeNull(pExpr) ){
77821 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
77826 ** Return TRUE if the given expression is a constant which would be
77827 ** unchanged by OP_Affinity with the affinity given in the second
77828 ** argument.
77830 ** This routine is used to determine if the OP_Affinity operation
77831 ** can be omitted. When in doubt return FALSE. A false negative
77832 ** is harmless. A false positive, however, can result in the wrong
77833 ** answer.
77835 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
77836 u8 op;
77837 if( aff==SQLITE_AFF_NONE ) return 1;
77838 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
77839 op = p->op;
77840 if( op==TK_REGISTER ) op = p->op2;
77841 switch( op ){
77842 case TK_INTEGER: {
77843 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
77845 case TK_FLOAT: {
77846 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
77848 case TK_STRING: {
77849 return aff==SQLITE_AFF_TEXT;
77851 case TK_BLOB: {
77852 return 1;
77854 case TK_COLUMN: {
77855 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
77856 return p->iColumn<0
77857 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
77859 default: {
77860 return 0;
77866 ** Return TRUE if the given string is a row-id column name.
77868 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
77869 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
77870 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
77871 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
77872 return 0;
77876 ** Return true if we are able to the IN operator optimization on a
77877 ** query of the form
77879 ** x IN (SELECT ...)
77881 ** Where the SELECT... clause is as specified by the parameter to this
77882 ** routine.
77884 ** The Select object passed in has already been preprocessed and no
77885 ** errors have been found.
77887 #ifndef SQLITE_OMIT_SUBQUERY
77888 static int isCandidateForInOpt(Select *p){
77889 SrcList *pSrc;
77890 ExprList *pEList;
77891 Table *pTab;
77892 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
77893 if( p->pPrior ) return 0; /* Not a compound SELECT */
77894 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
77895 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
77896 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
77897 return 0; /* No DISTINCT keyword and no aggregate functions */
77899 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
77900 if( p->pLimit ) return 0; /* Has no LIMIT clause */
77901 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
77902 if( p->pWhere ) return 0; /* Has no WHERE clause */
77903 pSrc = p->pSrc;
77904 assert( pSrc!=0 );
77905 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
77906 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
77907 pTab = pSrc->a[0].pTab;
77908 if( NEVER(pTab==0) ) return 0;
77909 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
77910 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
77911 pEList = p->pEList;
77912 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
77913 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
77914 return 1;
77916 #endif /* SQLITE_OMIT_SUBQUERY */
77919 ** Code an OP_Once instruction and allocate space for its flag. Return the
77920 ** address of the new instruction.
77922 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
77923 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
77924 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
77928 ** This function is used by the implementation of the IN (...) operator.
77929 ** The pX parameter is the expression on the RHS of the IN operator, which
77930 ** might be either a list of expressions or a subquery.
77932 ** The job of this routine is to find or create a b-tree object that can
77933 ** be used either to test for membership in the RHS set or to iterate through
77934 ** all members of the RHS set, skipping duplicates.
77936 ** A cursor is opened on the b-tree object that the RHS of the IN operator
77937 ** and pX->iTable is set to the index of that cursor.
77939 ** The returned value of this function indicates the b-tree type, as follows:
77941 ** IN_INDEX_ROWID - The cursor was opened on a database table.
77942 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
77943 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
77944 ** IN_INDEX_EPH - The cursor was opened on a specially created and
77945 ** populated epheremal table.
77947 ** An existing b-tree might be used if the RHS expression pX is a simple
77948 ** subquery such as:
77950 ** SELECT <column> FROM <table>
77952 ** If the RHS of the IN operator is a list or a more complex subquery, then
77953 ** an ephemeral table might need to be generated from the RHS and then
77954 ** pX->iTable made to point to the ephermeral table instead of an
77955 ** existing table.
77957 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
77958 ** through the set members, skipping any duplicates. In this case an
77959 ** epheremal table must be used unless the selected <column> is guaranteed
77960 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
77961 ** has a UNIQUE constraint or UNIQUE index.
77963 ** If the prNotFound parameter is not 0, then the b-tree will be used
77964 ** for fast set membership tests. In this case an epheremal table must
77965 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
77966 ** be found with <column> as its left-most column.
77968 ** When the b-tree is being used for membership tests, the calling function
77969 ** needs to know whether or not the structure contains an SQL NULL
77970 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
77971 ** If there is any chance that the (...) might contain a NULL value at
77972 ** runtime, then a register is allocated and the register number written
77973 ** to *prNotFound. If there is no chance that the (...) contains a
77974 ** NULL value, then *prNotFound is left unchanged.
77976 ** If a register is allocated and its location stored in *prNotFound, then
77977 ** its initial value is NULL. If the (...) does not remain constant
77978 ** for the duration of the query (i.e. the SELECT within the (...)
77979 ** is a correlated subquery) then the value of the allocated register is
77980 ** reset to NULL each time the subquery is rerun. This allows the
77981 ** caller to use vdbe code equivalent to the following:
77983 ** if( register==NULL ){
77984 ** has_null = <test if data structure contains null>
77985 ** register = 1
77986 ** }
77988 ** in order to avoid running the <test if data structure contains null>
77989 ** test more often than is necessary.
77991 #ifndef SQLITE_OMIT_SUBQUERY
77992 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
77993 Select *p; /* SELECT to the right of IN operator */
77994 int eType = 0; /* Type of RHS table. IN_INDEX_* */
77995 int iTab = pParse->nTab++; /* Cursor of the RHS table */
77996 int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
77997 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
77999 assert( pX->op==TK_IN );
78001 /* Check to see if an existing table or index can be used to
78002 ** satisfy the query. This is preferable to generating a new
78003 ** ephemeral table.
78005 p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
78006 if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
78007 sqlite3 *db = pParse->db; /* Database connection */
78008 Table *pTab; /* Table <table>. */
78009 Expr *pExpr; /* Expression <column> */
78010 i16 iCol; /* Index of column <column> */
78011 i16 iDb; /* Database idx for pTab */
78013 assert( p ); /* Because of isCandidateForInOpt(p) */
78014 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
78015 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
78016 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
78017 pTab = p->pSrc->a[0].pTab;
78018 pExpr = p->pEList->a[0].pExpr;
78019 iCol = (i16)pExpr->iColumn;
78021 /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
78022 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
78023 sqlite3CodeVerifySchema(pParse, iDb);
78024 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
78026 /* This function is only called from two places. In both cases the vdbe
78027 ** has already been allocated. So assume sqlite3GetVdbe() is always
78028 ** successful here.
78030 assert(v);
78031 if( iCol<0 ){
78032 int iAddr;
78034 iAddr = sqlite3CodeOnce(pParse);
78036 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
78037 eType = IN_INDEX_ROWID;
78039 sqlite3VdbeJumpHere(v, iAddr);
78040 }else{
78041 Index *pIdx; /* Iterator variable */
78043 /* The collation sequence used by the comparison. If an index is to
78044 ** be used in place of a temp-table, it must be ordered according
78045 ** to this collation sequence. */
78046 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
78048 /* Check that the affinity that will be used to perform the
78049 ** comparison is the same as the affinity of the column. If
78050 ** it is not, it is not possible to use any index.
78052 int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
78054 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
78055 if( (pIdx->aiColumn[0]==iCol)
78056 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
78057 && (!mustBeUnique || (pIdx->nKeyCol==1 && pIdx->onError!=OE_None))
78059 int iAddr = sqlite3CodeOnce(pParse);
78060 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
78061 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
78062 VdbeComment((v, "%s", pIdx->zName));
78063 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
78064 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
78066 sqlite3VdbeJumpHere(v, iAddr);
78067 if( prNotFound && !pTab->aCol[iCol].notNull ){
78068 *prNotFound = ++pParse->nMem;
78069 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
78076 if( eType==0 ){
78077 /* Could not found an existing table or index to use as the RHS b-tree.
78078 ** We will have to generate an ephemeral table to do the job.
78080 u32 savedNQueryLoop = pParse->nQueryLoop;
78081 int rMayHaveNull = 0;
78082 eType = IN_INDEX_EPH;
78083 if( prNotFound ){
78084 *prNotFound = rMayHaveNull = ++pParse->nMem;
78085 sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
78086 }else{
78087 testcase( pParse->nQueryLoop>0 );
78088 pParse->nQueryLoop = 0;
78089 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
78090 eType = IN_INDEX_ROWID;
78093 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
78094 pParse->nQueryLoop = savedNQueryLoop;
78095 }else{
78096 pX->iTable = iTab;
78098 return eType;
78100 #endif
78103 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
78104 ** or IN operators. Examples:
78106 ** (SELECT a FROM b) -- subquery
78107 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
78108 ** x IN (4,5,11) -- IN operator with list on right-hand side
78109 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
78111 ** The pExpr parameter describes the expression that contains the IN
78112 ** operator or subquery.
78114 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
78115 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
78116 ** to some integer key column of a table B-Tree. In this case, use an
78117 ** intkey B-Tree to store the set of IN(...) values instead of the usual
78118 ** (slower) variable length keys B-Tree.
78120 ** If rMayHaveNull is non-zero, that means that the operation is an IN
78121 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
78122 ** Furthermore, the IN is in a WHERE clause and that we really want
78123 ** to iterate over the RHS of the IN operator in order to quickly locate
78124 ** all corresponding LHS elements. All this routine does is initialize
78125 ** the register given by rMayHaveNull to NULL. Calling routines will take
78126 ** care of changing this register value to non-NULL if the RHS is NULL-free.
78128 ** If rMayHaveNull is zero, that means that the subquery is being used
78129 ** for membership testing only. There is no need to initialize any
78130 ** registers to indicate the presence or absence of NULLs on the RHS.
78132 ** For a SELECT or EXISTS operator, return the register that holds the
78133 ** result. For IN operators or if an error occurs, the return value is 0.
78135 #ifndef SQLITE_OMIT_SUBQUERY
78136 SQLITE_PRIVATE int sqlite3CodeSubselect(
78137 Parse *pParse, /* Parsing context */
78138 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
78139 int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
78140 int isRowid /* If true, LHS of IN operator is a rowid */
78142 int testAddr = -1; /* One-time test address */
78143 int rReg = 0; /* Register storing resulting */
78144 Vdbe *v = sqlite3GetVdbe(pParse);
78145 if( NEVER(v==0) ) return 0;
78146 sqlite3ExprCachePush(pParse);
78148 /* This code must be run in its entirety every time it is encountered
78149 ** if any of the following is true:
78151 ** * The right-hand side is a correlated subquery
78152 ** * The right-hand side is an expression list containing variables
78153 ** * We are inside a trigger
78155 ** If all of the above are false, then we can run this code just once
78156 ** save the results, and reuse the same result on subsequent invocations.
78158 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
78159 testAddr = sqlite3CodeOnce(pParse);
78162 #ifndef SQLITE_OMIT_EXPLAIN
78163 if( pParse->explain==2 ){
78164 char *zMsg = sqlite3MPrintf(
78165 pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
78166 pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
78168 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
78170 #endif
78172 switch( pExpr->op ){
78173 case TK_IN: {
78174 char affinity; /* Affinity of the LHS of the IN */
78175 int addr; /* Address of OP_OpenEphemeral instruction */
78176 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
78177 KeyInfo *pKeyInfo = 0; /* Key information */
78179 if( rMayHaveNull ){
78180 sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
78183 affinity = sqlite3ExprAffinity(pLeft);
78185 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
78186 ** expression it is handled the same way. An ephemeral table is
78187 ** filled with single-field index keys representing the results
78188 ** from the SELECT or the <exprlist>.
78190 ** If the 'x' expression is a column value, or the SELECT...
78191 ** statement returns a column value, then the affinity of that
78192 ** column is used to build the index keys. If both 'x' and the
78193 ** SELECT... statement are columns, then numeric affinity is used
78194 ** if either column has NUMERIC or INTEGER affinity. If neither
78195 ** 'x' nor the SELECT... statement are columns, then numeric affinity
78196 ** is used.
78198 pExpr->iTable = pParse->nTab++;
78199 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
78200 if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
78201 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
78203 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78204 /* Case 1: expr IN (SELECT ...)
78206 ** Generate code to write the results of the select into the temporary
78207 ** table allocated and opened above.
78209 SelectDest dest;
78210 ExprList *pEList;
78212 assert( !isRowid );
78213 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
78214 dest.affSdst = (u8)affinity;
78215 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
78216 pExpr->x.pSelect->iLimit = 0;
78217 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
78218 if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
78219 sqlite3KeyInfoUnref(pKeyInfo);
78220 return 0;
78222 pEList = pExpr->x.pSelect->pEList;
78223 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
78224 assert( pEList!=0 );
78225 assert( pEList->nExpr>0 );
78226 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
78227 pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
78228 pEList->a[0].pExpr);
78229 }else if( ALWAYS(pExpr->x.pList!=0) ){
78230 /* Case 2: expr IN (exprlist)
78232 ** For each expression, build an index key from the evaluation and
78233 ** store it in the temporary table. If <expr> is a column, then use
78234 ** that columns affinity when building index keys. If <expr> is not
78235 ** a column, use numeric affinity.
78237 int i;
78238 ExprList *pList = pExpr->x.pList;
78239 struct ExprList_item *pItem;
78240 int r1, r2, r3;
78242 if( !affinity ){
78243 affinity = SQLITE_AFF_NONE;
78245 if( pKeyInfo ){
78246 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
78247 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
78250 /* Loop through each expression in <exprlist>. */
78251 r1 = sqlite3GetTempReg(pParse);
78252 r2 = sqlite3GetTempReg(pParse);
78253 sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
78254 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
78255 Expr *pE2 = pItem->pExpr;
78256 int iValToIns;
78258 /* If the expression is not constant then we will need to
78259 ** disable the test that was generated above that makes sure
78260 ** this code only executes once. Because for a non-constant
78261 ** expression we need to rerun this code each time.
78263 if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
78264 sqlite3VdbeChangeToNoop(v, testAddr);
78265 testAddr = -1;
78268 /* Evaluate the expression and insert it into the temp table */
78269 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
78270 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
78271 }else{
78272 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
78273 if( isRowid ){
78274 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
78275 sqlite3VdbeCurrentAddr(v)+2);
78276 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
78277 }else{
78278 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
78279 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
78280 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
78284 sqlite3ReleaseTempReg(pParse, r1);
78285 sqlite3ReleaseTempReg(pParse, r2);
78287 if( pKeyInfo ){
78288 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
78290 break;
78293 case TK_EXISTS:
78294 case TK_SELECT:
78295 default: {
78296 /* If this has to be a scalar SELECT. Generate code to put the
78297 ** value of this select in a memory cell and record the number
78298 ** of the memory cell in iColumn. If this is an EXISTS, write
78299 ** an integer 0 (not exists) or 1 (exists) into a memory cell
78300 ** and record that memory cell in iColumn.
78302 Select *pSel; /* SELECT statement to encode */
78303 SelectDest dest; /* How to deal with SELECt result */
78305 testcase( pExpr->op==TK_EXISTS );
78306 testcase( pExpr->op==TK_SELECT );
78307 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
78309 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
78310 pSel = pExpr->x.pSelect;
78311 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
78312 if( pExpr->op==TK_SELECT ){
78313 dest.eDest = SRT_Mem;
78314 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
78315 VdbeComment((v, "Init subquery result"));
78316 }else{
78317 dest.eDest = SRT_Exists;
78318 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
78319 VdbeComment((v, "Init EXISTS result"));
78321 sqlite3ExprDelete(pParse->db, pSel->pLimit);
78322 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
78323 &sqlite3IntTokens[1]);
78324 pSel->iLimit = 0;
78325 if( sqlite3Select(pParse, pSel, &dest) ){
78326 return 0;
78328 rReg = dest.iSDParm;
78329 ExprSetVVAProperty(pExpr, EP_NoReduce);
78330 break;
78334 if( testAddr>=0 ){
78335 sqlite3VdbeJumpHere(v, testAddr);
78337 sqlite3ExprCachePop(pParse, 1);
78339 return rReg;
78341 #endif /* SQLITE_OMIT_SUBQUERY */
78343 #ifndef SQLITE_OMIT_SUBQUERY
78345 ** Generate code for an IN expression.
78347 ** x IN (SELECT ...)
78348 ** x IN (value, value, ...)
78350 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
78351 ** is an array of zero or more values. The expression is true if the LHS is
78352 ** contained within the RHS. The value of the expression is unknown (NULL)
78353 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
78354 ** RHS contains one or more NULL values.
78356 ** This routine generates code will jump to destIfFalse if the LHS is not
78357 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
78358 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
78359 ** within the RHS then fall through.
78361 static void sqlite3ExprCodeIN(
78362 Parse *pParse, /* Parsing and code generating context */
78363 Expr *pExpr, /* The IN expression */
78364 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
78365 int destIfNull /* Jump here if the results are unknown due to NULLs */
78367 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
78368 char affinity; /* Comparison affinity to use */
78369 int eType; /* Type of the RHS */
78370 int r1; /* Temporary use register */
78371 Vdbe *v; /* Statement under construction */
78373 /* Compute the RHS. After this step, the table with cursor
78374 ** pExpr->iTable will contains the values that make up the RHS.
78376 v = pParse->pVdbe;
78377 assert( v!=0 ); /* OOM detected prior to this routine */
78378 VdbeNoopComment((v, "begin IN expr"));
78379 eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
78381 /* Figure out the affinity to use to create a key from the results
78382 ** of the expression. affinityStr stores a static string suitable for
78383 ** P4 of OP_MakeRecord.
78385 affinity = comparisonAffinity(pExpr);
78387 /* Code the LHS, the <expr> from "<expr> IN (...)".
78389 sqlite3ExprCachePush(pParse);
78390 r1 = sqlite3GetTempReg(pParse);
78391 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
78393 /* If the LHS is NULL, then the result is either false or NULL depending
78394 ** on whether the RHS is empty or not, respectively.
78396 if( destIfNull==destIfFalse ){
78397 /* Shortcut for the common case where the false and NULL outcomes are
78398 ** the same. */
78399 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
78400 }else{
78401 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
78402 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
78403 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
78404 sqlite3VdbeJumpHere(v, addr1);
78407 if( eType==IN_INDEX_ROWID ){
78408 /* In this case, the RHS is the ROWID of table b-tree
78410 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
78411 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
78412 }else{
78413 /* In this case, the RHS is an index b-tree.
78415 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
78417 /* If the set membership test fails, then the result of the
78418 ** "x IN (...)" expression must be either 0 or NULL. If the set
78419 ** contains no NULL values, then the result is 0. If the set
78420 ** contains one or more NULL values, then the result of the
78421 ** expression is also NULL.
78423 if( rRhsHasNull==0 || destIfFalse==destIfNull ){
78424 /* This branch runs if it is known at compile time that the RHS
78425 ** cannot contain NULL values. This happens as the result
78426 ** of a "NOT NULL" constraint in the database schema.
78428 ** Also run this branch if NULL is equivalent to FALSE
78429 ** for this particular IN operator.
78431 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
78433 }else{
78434 /* In this branch, the RHS of the IN might contain a NULL and
78435 ** the presence of a NULL on the RHS makes a difference in the
78436 ** outcome.
78438 int j1, j2, j3;
78440 /* First check to see if the LHS is contained in the RHS. If so,
78441 ** then the presence of NULLs in the RHS does not matter, so jump
78442 ** over all of the code that follows.
78444 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
78446 /* Here we begin generating code that runs if the LHS is not
78447 ** contained within the RHS. Generate additional code that
78448 ** tests the RHS for NULLs. If the RHS contains a NULL then
78449 ** jump to destIfNull. If there are no NULLs in the RHS then
78450 ** jump to destIfFalse.
78452 j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
78453 j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
78454 sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
78455 sqlite3VdbeJumpHere(v, j3);
78456 sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
78457 sqlite3VdbeJumpHere(v, j2);
78459 /* Jump to the appropriate target depending on whether or not
78460 ** the RHS contains a NULL
78462 sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
78463 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
78465 /* The OP_Found at the top of this branch jumps here when true,
78466 ** causing the overall IN expression evaluation to fall through.
78468 sqlite3VdbeJumpHere(v, j1);
78471 sqlite3ReleaseTempReg(pParse, r1);
78472 sqlite3ExprCachePop(pParse, 1);
78473 VdbeComment((v, "end IN expr"));
78475 #endif /* SQLITE_OMIT_SUBQUERY */
78478 ** Duplicate an 8-byte value
78480 static char *dup8bytes(Vdbe *v, const char *in){
78481 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
78482 if( out ){
78483 memcpy(out, in, 8);
78485 return out;
78488 #ifndef SQLITE_OMIT_FLOATING_POINT
78490 ** Generate an instruction that will put the floating point
78491 ** value described by z[0..n-1] into register iMem.
78493 ** The z[] string will probably not be zero-terminated. But the
78494 ** z[n] character is guaranteed to be something that does not look
78495 ** like the continuation of the number.
78497 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
78498 if( ALWAYS(z!=0) ){
78499 double value;
78500 char *zV;
78501 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
78502 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
78503 if( negateFlag ) value = -value;
78504 zV = dup8bytes(v, (char*)&value);
78505 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
78508 #endif
78512 ** Generate an instruction that will put the integer describe by
78513 ** text z[0..n-1] into register iMem.
78515 ** Expr.u.zToken is always UTF8 and zero-terminated.
78517 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
78518 Vdbe *v = pParse->pVdbe;
78519 if( pExpr->flags & EP_IntValue ){
78520 int i = pExpr->u.iValue;
78521 assert( i>=0 );
78522 if( negFlag ) i = -i;
78523 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
78524 }else{
78525 int c;
78526 i64 value;
78527 const char *z = pExpr->u.zToken;
78528 assert( z!=0 );
78529 c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
78530 if( c==0 || (c==2 && negFlag) ){
78531 char *zV;
78532 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
78533 zV = dup8bytes(v, (char*)&value);
78534 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
78535 }else{
78536 #ifdef SQLITE_OMIT_FLOATING_POINT
78537 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
78538 #else
78539 codeReal(v, z, negFlag, iMem);
78540 #endif
78546 ** Clear a cache entry.
78548 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
78549 if( p->tempReg ){
78550 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78551 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
78553 p->tempReg = 0;
78559 ** Record in the column cache that a particular column from a
78560 ** particular table is stored in a particular register.
78562 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
78563 int i;
78564 int minLru;
78565 int idxLru;
78566 struct yColCache *p;
78568 assert( iReg>0 ); /* Register numbers are always positive */
78569 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
78571 /* The SQLITE_ColumnCache flag disables the column cache. This is used
78572 ** for testing only - to verify that SQLite always gets the same answer
78573 ** with and without the column cache.
78575 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
78577 /* First replace any existing entry.
78579 ** Actually, the way the column cache is currently used, we are guaranteed
78580 ** that the object will never already be in cache. Verify this guarantee.
78582 #ifndef NDEBUG
78583 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78584 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
78586 #endif
78588 /* Find an empty slot and replace it */
78589 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78590 if( p->iReg==0 ){
78591 p->iLevel = pParse->iCacheLevel;
78592 p->iTable = iTab;
78593 p->iColumn = iCol;
78594 p->iReg = iReg;
78595 p->tempReg = 0;
78596 p->lru = pParse->iCacheCnt++;
78597 return;
78601 /* Replace the last recently used */
78602 minLru = 0x7fffffff;
78603 idxLru = -1;
78604 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78605 if( p->lru<minLru ){
78606 idxLru = i;
78607 minLru = p->lru;
78610 if( ALWAYS(idxLru>=0) ){
78611 p = &pParse->aColCache[idxLru];
78612 p->iLevel = pParse->iCacheLevel;
78613 p->iTable = iTab;
78614 p->iColumn = iCol;
78615 p->iReg = iReg;
78616 p->tempReg = 0;
78617 p->lru = pParse->iCacheCnt++;
78618 return;
78623 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
78624 ** Purge the range of registers from the column cache.
78626 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
78627 int i;
78628 int iLast = iReg + nReg - 1;
78629 struct yColCache *p;
78630 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78631 int r = p->iReg;
78632 if( r>=iReg && r<=iLast ){
78633 cacheEntryClear(pParse, p);
78634 p->iReg = 0;
78640 ** Remember the current column cache context. Any new entries added
78641 ** added to the column cache after this call are removed when the
78642 ** corresponding pop occurs.
78644 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
78645 pParse->iCacheLevel++;
78646 #ifdef SQLITE_DEBUG
78647 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
78648 printf("PUSH to %d\n", pParse->iCacheLevel);
78650 #endif
78654 ** Remove from the column cache any entries that were added since the
78655 ** the previous N Push operations. In other words, restore the cache
78656 ** to the state it was in N Pushes ago.
78658 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
78659 int i;
78660 struct yColCache *p;
78661 assert( N>0 );
78662 assert( pParse->iCacheLevel>=N );
78663 pParse->iCacheLevel -= N;
78664 #ifdef SQLITE_DEBUG
78665 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
78666 printf("POP to %d\n", pParse->iCacheLevel);
78668 #endif
78669 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78670 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
78671 cacheEntryClear(pParse, p);
78672 p->iReg = 0;
78678 ** When a cached column is reused, make sure that its register is
78679 ** no longer available as a temp register. ticket #3879: that same
78680 ** register might be in the cache in multiple places, so be sure to
78681 ** get them all.
78683 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
78684 int i;
78685 struct yColCache *p;
78686 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78687 if( p->iReg==iReg ){
78688 p->tempReg = 0;
78694 ** Generate code to extract the value of the iCol-th column of a table.
78696 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
78697 Vdbe *v, /* The VDBE under construction */
78698 Table *pTab, /* The table containing the value */
78699 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
78700 int iCol, /* Index of the column to extract */
78701 int regOut /* Extract the value into this register */
78703 if( iCol<0 || iCol==pTab->iPKey ){
78704 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
78705 }else{
78706 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
78707 int x = iCol;
78708 if( !HasRowid(pTab) ){
78709 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
78711 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
78713 if( iCol>=0 ){
78714 sqlite3ColumnDefault(v, pTab, iCol, regOut);
78719 ** Generate code that will extract the iColumn-th column from
78720 ** table pTab and store the column value in a register. An effort
78721 ** is made to store the column value in register iReg, but this is
78722 ** not guaranteed. The location of the column value is returned.
78724 ** There must be an open cursor to pTab in iTable when this routine
78725 ** is called. If iColumn<0 then code is generated that extracts the rowid.
78727 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
78728 Parse *pParse, /* Parsing and code generating context */
78729 Table *pTab, /* Description of the table we are reading from */
78730 int iColumn, /* Index of the table column */
78731 int iTable, /* The cursor pointing to the table */
78732 int iReg, /* Store results here */
78733 u8 p5 /* P5 value for OP_Column */
78735 Vdbe *v = pParse->pVdbe;
78736 int i;
78737 struct yColCache *p;
78739 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78740 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
78741 p->lru = pParse->iCacheCnt++;
78742 sqlite3ExprCachePinRegister(pParse, p->iReg);
78743 return p->iReg;
78746 assert( v!=0 );
78747 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
78748 if( p5 ){
78749 sqlite3VdbeChangeP5(v, p5);
78750 }else{
78751 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
78753 return iReg;
78757 ** Clear all column cache entries.
78759 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
78760 int i;
78761 struct yColCache *p;
78763 #if SQLITE_DEBUG
78764 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
78765 printf("CLEAR\n");
78767 #endif
78768 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78769 if( p->iReg ){
78770 cacheEntryClear(pParse, p);
78771 p->iReg = 0;
78777 ** Record the fact that an affinity change has occurred on iCount
78778 ** registers starting with iStart.
78780 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
78781 sqlite3ExprCacheRemove(pParse, iStart, iCount);
78785 ** Generate code to move content from registers iFrom...iFrom+nReg-1
78786 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
78788 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
78789 int i;
78790 struct yColCache *p;
78791 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
78792 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
78793 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78794 int x = p->iReg;
78795 if( x>=iFrom && x<iFrom+nReg ){
78796 p->iReg += iTo-iFrom;
78801 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
78803 ** Return true if any register in the range iFrom..iTo (inclusive)
78804 ** is used as part of the column cache.
78806 ** This routine is used within assert() and testcase() macros only
78807 ** and does not appear in a normal build.
78809 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
78810 int i;
78811 struct yColCache *p;
78812 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78813 int r = p->iReg;
78814 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
78816 return 0;
78818 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
78821 ** Convert an expression node to a TK_REGISTER
78823 static void exprToRegister(Expr *p, int iReg){
78824 p->op2 = p->op;
78825 p->op = TK_REGISTER;
78826 p->iTable = iReg;
78827 ExprClearProperty(p, EP_Skip);
78831 ** Generate code into the current Vdbe to evaluate the given
78832 ** expression. Attempt to store the results in register "target".
78833 ** Return the register where results are stored.
78835 ** With this routine, there is no guarantee that results will
78836 ** be stored in target. The result might be stored in some other
78837 ** register if it is convenient to do so. The calling function
78838 ** must check the return code and move the results to the desired
78839 ** register.
78841 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
78842 Vdbe *v = pParse->pVdbe; /* The VM under construction */
78843 int op; /* The opcode being coded */
78844 int inReg = target; /* Results stored in register inReg */
78845 int regFree1 = 0; /* If non-zero free this temporary register */
78846 int regFree2 = 0; /* If non-zero free this temporary register */
78847 int r1, r2, r3, r4; /* Various register numbers */
78848 sqlite3 *db = pParse->db; /* The database connection */
78849 Expr tempX; /* Temporary expression node */
78851 assert( target>0 && target<=pParse->nMem );
78852 if( v==0 ){
78853 assert( pParse->db->mallocFailed );
78854 return 0;
78857 if( pExpr==0 ){
78858 op = TK_NULL;
78859 }else{
78860 op = pExpr->op;
78862 switch( op ){
78863 case TK_AGG_COLUMN: {
78864 AggInfo *pAggInfo = pExpr->pAggInfo;
78865 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
78866 if( !pAggInfo->directMode ){
78867 assert( pCol->iMem>0 );
78868 inReg = pCol->iMem;
78869 break;
78870 }else if( pAggInfo->useSortingIdx ){
78871 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
78872 pCol->iSorterColumn, target);
78873 break;
78875 /* Otherwise, fall thru into the TK_COLUMN case */
78877 case TK_COLUMN: {
78878 int iTab = pExpr->iTable;
78879 if( iTab<0 ){
78880 if( pParse->ckBase>0 ){
78881 /* Generating CHECK constraints or inserting into partial index */
78882 inReg = pExpr->iColumn + pParse->ckBase;
78883 break;
78884 }else{
78885 /* Deleting from a partial index */
78886 iTab = pParse->iPartIdxTab;
78889 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
78890 pExpr->iColumn, iTab, target,
78891 pExpr->op2);
78892 break;
78894 case TK_INTEGER: {
78895 codeInteger(pParse, pExpr, 0, target);
78896 break;
78898 #ifndef SQLITE_OMIT_FLOATING_POINT
78899 case TK_FLOAT: {
78900 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78901 codeReal(v, pExpr->u.zToken, 0, target);
78902 break;
78904 #endif
78905 case TK_STRING: {
78906 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78907 sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
78908 break;
78910 case TK_NULL: {
78911 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78912 break;
78914 #ifndef SQLITE_OMIT_BLOB_LITERAL
78915 case TK_BLOB: {
78916 int n;
78917 const char *z;
78918 char *zBlob;
78919 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78920 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
78921 assert( pExpr->u.zToken[1]=='\'' );
78922 z = &pExpr->u.zToken[2];
78923 n = sqlite3Strlen30(z) - 1;
78924 assert( z[n]=='\'' );
78925 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
78926 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
78927 break;
78929 #endif
78930 case TK_VARIABLE: {
78931 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78932 assert( pExpr->u.zToken!=0 );
78933 assert( pExpr->u.zToken[0]!=0 );
78934 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
78935 if( pExpr->u.zToken[1]!=0 ){
78936 assert( pExpr->u.zToken[0]=='?'
78937 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
78938 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
78940 break;
78942 case TK_REGISTER: {
78943 inReg = pExpr->iTable;
78944 break;
78946 case TK_AS: {
78947 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
78948 break;
78950 #ifndef SQLITE_OMIT_CAST
78951 case TK_CAST: {
78952 /* Expressions of the form: CAST(pLeft AS token) */
78953 int aff, to_op;
78954 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
78955 assert( !ExprHasProperty(pExpr, EP_IntValue) );
78956 aff = sqlite3AffinityType(pExpr->u.zToken, 0);
78957 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
78958 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
78959 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
78960 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
78961 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
78962 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
78963 testcase( to_op==OP_ToText );
78964 testcase( to_op==OP_ToBlob );
78965 testcase( to_op==OP_ToNumeric );
78966 testcase( to_op==OP_ToInt );
78967 testcase( to_op==OP_ToReal );
78968 if( inReg!=target ){
78969 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
78970 inReg = target;
78972 sqlite3VdbeAddOp1(v, to_op, inReg);
78973 testcase( usedAsColumnCache(pParse, inReg, inReg) );
78974 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
78975 break;
78977 #endif /* SQLITE_OMIT_CAST */
78978 case TK_LT:
78979 case TK_LE:
78980 case TK_GT:
78981 case TK_GE:
78982 case TK_NE:
78983 case TK_EQ: {
78984 assert( TK_LT==OP_Lt );
78985 assert( TK_LE==OP_Le );
78986 assert( TK_GT==OP_Gt );
78987 assert( TK_GE==OP_Ge );
78988 assert( TK_EQ==OP_Eq );
78989 assert( TK_NE==OP_Ne );
78990 testcase( op==TK_LT );
78991 testcase( op==TK_LE );
78992 testcase( op==TK_GT );
78993 testcase( op==TK_GE );
78994 testcase( op==TK_EQ );
78995 testcase( op==TK_NE );
78996 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78997 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78998 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78999 r1, r2, inReg, SQLITE_STOREP2);
79000 testcase( regFree1==0 );
79001 testcase( regFree2==0 );
79002 break;
79004 case TK_IS:
79005 case TK_ISNOT: {
79006 testcase( op==TK_IS );
79007 testcase( op==TK_ISNOT );
79008 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79009 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79010 op = (op==TK_IS) ? TK_EQ : TK_NE;
79011 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
79012 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
79013 testcase( regFree1==0 );
79014 testcase( regFree2==0 );
79015 break;
79017 case TK_AND:
79018 case TK_OR:
79019 case TK_PLUS:
79020 case TK_STAR:
79021 case TK_MINUS:
79022 case TK_REM:
79023 case TK_BITAND:
79024 case TK_BITOR:
79025 case TK_SLASH:
79026 case TK_LSHIFT:
79027 case TK_RSHIFT:
79028 case TK_CONCAT: {
79029 assert( TK_AND==OP_And );
79030 assert( TK_OR==OP_Or );
79031 assert( TK_PLUS==OP_Add );
79032 assert( TK_MINUS==OP_Subtract );
79033 assert( TK_REM==OP_Remainder );
79034 assert( TK_BITAND==OP_BitAnd );
79035 assert( TK_BITOR==OP_BitOr );
79036 assert( TK_SLASH==OP_Divide );
79037 assert( TK_LSHIFT==OP_ShiftLeft );
79038 assert( TK_RSHIFT==OP_ShiftRight );
79039 assert( TK_CONCAT==OP_Concat );
79040 testcase( op==TK_AND );
79041 testcase( op==TK_OR );
79042 testcase( op==TK_PLUS );
79043 testcase( op==TK_MINUS );
79044 testcase( op==TK_REM );
79045 testcase( op==TK_BITAND );
79046 testcase( op==TK_BITOR );
79047 testcase( op==TK_SLASH );
79048 testcase( op==TK_LSHIFT );
79049 testcase( op==TK_RSHIFT );
79050 testcase( op==TK_CONCAT );
79051 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79052 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
79053 sqlite3VdbeAddOp3(v, op, r2, r1, target);
79054 testcase( regFree1==0 );
79055 testcase( regFree2==0 );
79056 break;
79058 case TK_UMINUS: {
79059 Expr *pLeft = pExpr->pLeft;
79060 assert( pLeft );
79061 if( pLeft->op==TK_INTEGER ){
79062 codeInteger(pParse, pLeft, 1, target);
79063 #ifndef SQLITE_OMIT_FLOATING_POINT
79064 }else if( pLeft->op==TK_FLOAT ){
79065 assert( !ExprHasProperty(pExpr, EP_IntValue) );
79066 codeReal(v, pLeft->u.zToken, 1, target);
79067 #endif
79068 }else{
79069 tempX.op = TK_INTEGER;
79070 tempX.flags = EP_IntValue|EP_TokenOnly;
79071 tempX.u.iValue = 0;
79072 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
79073 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
79074 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
79075 testcase( regFree2==0 );
79077 inReg = target;
79078 break;
79080 case TK_BITNOT:
79081 case TK_NOT: {
79082 assert( TK_BITNOT==OP_BitNot );
79083 assert( TK_NOT==OP_Not );
79084 testcase( op==TK_BITNOT );
79085 testcase( op==TK_NOT );
79086 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79087 testcase( regFree1==0 );
79088 inReg = target;
79089 sqlite3VdbeAddOp2(v, op, r1, inReg);
79090 break;
79092 case TK_ISNULL:
79093 case TK_NOTNULL: {
79094 int addr;
79095 assert( TK_ISNULL==OP_IsNull );
79096 assert( TK_NOTNULL==OP_NotNull );
79097 testcase( op==TK_ISNULL );
79098 testcase( op==TK_NOTNULL );
79099 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
79100 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
79101 testcase( regFree1==0 );
79102 addr = sqlite3VdbeAddOp1(v, op, r1);
79103 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
79104 sqlite3VdbeJumpHere(v, addr);
79105 break;
79107 case TK_AGG_FUNCTION: {
79108 AggInfo *pInfo = pExpr->pAggInfo;
79109 if( pInfo==0 ){
79110 assert( !ExprHasProperty(pExpr, EP_IntValue) );
79111 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
79112 }else{
79113 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
79115 break;
79117 case TK_FUNCTION: {
79118 ExprList *pFarg; /* List of function arguments */
79119 int nFarg; /* Number of function arguments */
79120 FuncDef *pDef; /* The function definition object */
79121 int nId; /* Length of the function name in bytes */
79122 const char *zId; /* The function name */
79123 u32 constMask = 0; /* Mask of function arguments that are constant */
79124 int i; /* Loop counter */
79125 u8 enc = ENC(db); /* The text encoding used by this database */
79126 CollSeq *pColl = 0; /* A collating sequence */
79128 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79129 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
79130 pFarg = 0;
79131 }else{
79132 pFarg = pExpr->x.pList;
79134 nFarg = pFarg ? pFarg->nExpr : 0;
79135 assert( !ExprHasProperty(pExpr, EP_IntValue) );
79136 zId = pExpr->u.zToken;
79137 nId = sqlite3Strlen30(zId);
79138 pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
79139 if( pDef==0 ){
79140 sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
79141 break;
79144 /* Attempt a direct implementation of the built-in COALESCE() and
79145 ** IFNULL() functions. This avoids unnecessary evalation of
79146 ** arguments past the first non-NULL argument.
79148 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
79149 int endCoalesce = sqlite3VdbeMakeLabel(v);
79150 assert( nFarg>=2 );
79151 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
79152 for(i=1; i<nFarg; i++){
79153 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
79154 sqlite3ExprCacheRemove(pParse, target, 1);
79155 sqlite3ExprCachePush(pParse);
79156 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
79157 sqlite3ExprCachePop(pParse, 1);
79159 sqlite3VdbeResolveLabel(v, endCoalesce);
79160 break;
79163 /* The UNLIKELY() function is a no-op. The result is the value
79164 ** of the first argument.
79166 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
79167 assert( nFarg>=1 );
79168 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
79169 break;
79172 for(i=0; i<nFarg; i++){
79173 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
79174 testcase( i==31 );
79175 constMask |= MASKBIT32(i);
79177 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
79178 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
79181 if( pFarg ){
79182 if( constMask ){
79183 r1 = pParse->nMem+1;
79184 pParse->nMem += nFarg;
79185 }else{
79186 r1 = sqlite3GetTempRange(pParse, nFarg);
79189 /* For length() and typeof() functions with a column argument,
79190 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
79191 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
79192 ** loading.
79194 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
79195 u8 exprOp;
79196 assert( nFarg==1 );
79197 assert( pFarg->a[0].pExpr!=0 );
79198 exprOp = pFarg->a[0].pExpr->op;
79199 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
79200 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
79201 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
79202 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
79203 pFarg->a[0].pExpr->op2 =
79204 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
79208 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
79209 sqlite3ExprCodeExprList(pParse, pFarg, r1,
79210 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
79211 sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
79212 }else{
79213 r1 = 0;
79215 #ifndef SQLITE_OMIT_VIRTUALTABLE
79216 /* Possibly overload the function if the first argument is
79217 ** a virtual table column.
79219 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
79220 ** second argument, not the first, as the argument to test to
79221 ** see if it is a column in a virtual table. This is done because
79222 ** the left operand of infix functions (the operand we want to
79223 ** control overloading) ends up as the second argument to the
79224 ** function. The expression "A glob B" is equivalent to
79225 ** "glob(B,A). We want to use the A in "A glob B" to test
79226 ** for function overloading. But we use the B term in "glob(B,A)".
79228 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
79229 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
79230 }else if( nFarg>0 ){
79231 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
79233 #endif
79234 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
79235 if( !pColl ) pColl = db->pDfltColl;
79236 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
79238 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
79239 (char*)pDef, P4_FUNCDEF);
79240 sqlite3VdbeChangeP5(v, (u8)nFarg);
79241 if( nFarg && constMask==0 ){
79242 sqlite3ReleaseTempRange(pParse, r1, nFarg);
79244 break;
79246 #ifndef SQLITE_OMIT_SUBQUERY
79247 case TK_EXISTS:
79248 case TK_SELECT: {
79249 testcase( op==TK_EXISTS );
79250 testcase( op==TK_SELECT );
79251 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
79252 break;
79254 case TK_IN: {
79255 int destIfFalse = sqlite3VdbeMakeLabel(v);
79256 int destIfNull = sqlite3VdbeMakeLabel(v);
79257 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
79258 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
79259 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
79260 sqlite3VdbeResolveLabel(v, destIfFalse);
79261 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
79262 sqlite3VdbeResolveLabel(v, destIfNull);
79263 break;
79265 #endif /* SQLITE_OMIT_SUBQUERY */
79269 ** x BETWEEN y AND z
79271 ** This is equivalent to
79273 ** x>=y AND x<=z
79275 ** X is stored in pExpr->pLeft.
79276 ** Y is stored in pExpr->pList->a[0].pExpr.
79277 ** Z is stored in pExpr->pList->a[1].pExpr.
79279 case TK_BETWEEN: {
79280 Expr *pLeft = pExpr->pLeft;
79281 struct ExprList_item *pLItem = pExpr->x.pList->a;
79282 Expr *pRight = pLItem->pExpr;
79284 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
79285 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
79286 testcase( regFree1==0 );
79287 testcase( regFree2==0 );
79288 r3 = sqlite3GetTempReg(pParse);
79289 r4 = sqlite3GetTempReg(pParse);
79290 codeCompare(pParse, pLeft, pRight, OP_Ge,
79291 r1, r2, r3, SQLITE_STOREP2);
79292 pLItem++;
79293 pRight = pLItem->pExpr;
79294 sqlite3ReleaseTempReg(pParse, regFree2);
79295 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
79296 testcase( regFree2==0 );
79297 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
79298 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
79299 sqlite3ReleaseTempReg(pParse, r3);
79300 sqlite3ReleaseTempReg(pParse, r4);
79301 break;
79303 case TK_COLLATE:
79304 case TK_UPLUS: {
79305 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
79306 break;
79309 case TK_TRIGGER: {
79310 /* If the opcode is TK_TRIGGER, then the expression is a reference
79311 ** to a column in the new.* or old.* pseudo-tables available to
79312 ** trigger programs. In this case Expr.iTable is set to 1 for the
79313 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
79314 ** is set to the column of the pseudo-table to read, or to -1 to
79315 ** read the rowid field.
79317 ** The expression is implemented using an OP_Param opcode. The p1
79318 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
79319 ** to reference another column of the old.* pseudo-table, where
79320 ** i is the index of the column. For a new.rowid reference, p1 is
79321 ** set to (n+1), where n is the number of columns in each pseudo-table.
79322 ** For a reference to any other column in the new.* pseudo-table, p1
79323 ** is set to (n+2+i), where n and i are as defined previously. For
79324 ** example, if the table on which triggers are being fired is
79325 ** declared as:
79327 ** CREATE TABLE t1(a, b);
79329 ** Then p1 is interpreted as follows:
79331 ** p1==0 -> old.rowid p1==3 -> new.rowid
79332 ** p1==1 -> old.a p1==4 -> new.a
79333 ** p1==2 -> old.b p1==5 -> new.b
79335 Table *pTab = pExpr->pTab;
79336 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
79338 assert( pExpr->iTable==0 || pExpr->iTable==1 );
79339 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
79340 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
79341 assert( p1>=0 && p1<(pTab->nCol*2+2) );
79343 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
79344 VdbeComment((v, "%s.%s -> $%d",
79345 (pExpr->iTable ? "new" : "old"),
79346 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
79347 target
79350 #ifndef SQLITE_OMIT_FLOATING_POINT
79351 /* If the column has REAL affinity, it may currently be stored as an
79352 ** integer. Use OP_RealAffinity to make sure it is really real. */
79353 if( pExpr->iColumn>=0
79354 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
79356 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
79358 #endif
79359 break;
79364 ** Form A:
79365 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
79367 ** Form B:
79368 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
79370 ** Form A is can be transformed into the equivalent form B as follows:
79371 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
79372 ** WHEN x=eN THEN rN ELSE y END
79374 ** X (if it exists) is in pExpr->pLeft.
79375 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
79376 ** odd. The Y is also optional. If the number of elements in x.pList
79377 ** is even, then Y is omitted and the "otherwise" result is NULL.
79378 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
79380 ** The result of the expression is the Ri for the first matching Ei,
79381 ** or if there is no matching Ei, the ELSE term Y, or if there is
79382 ** no ELSE term, NULL.
79384 default: assert( op==TK_CASE ); {
79385 int endLabel; /* GOTO label for end of CASE stmt */
79386 int nextCase; /* GOTO label for next WHEN clause */
79387 int nExpr; /* 2x number of WHEN terms */
79388 int i; /* Loop counter */
79389 ExprList *pEList; /* List of WHEN terms */
79390 struct ExprList_item *aListelem; /* Array of WHEN terms */
79391 Expr opCompare; /* The X==Ei expression */
79392 Expr *pX; /* The X expression */
79393 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
79394 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
79396 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
79397 assert(pExpr->x.pList->nExpr > 0);
79398 pEList = pExpr->x.pList;
79399 aListelem = pEList->a;
79400 nExpr = pEList->nExpr;
79401 endLabel = sqlite3VdbeMakeLabel(v);
79402 if( (pX = pExpr->pLeft)!=0 ){
79403 tempX = *pX;
79404 testcase( pX->op==TK_COLUMN );
79405 exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
79406 testcase( regFree1==0 );
79407 opCompare.op = TK_EQ;
79408 opCompare.pLeft = &tempX;
79409 pTest = &opCompare;
79410 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
79411 ** The value in regFree1 might get SCopy-ed into the file result.
79412 ** So make sure that the regFree1 register is not reused for other
79413 ** purposes and possibly overwritten. */
79414 regFree1 = 0;
79416 for(i=0; i<nExpr-1; i=i+2){
79417 sqlite3ExprCachePush(pParse);
79418 if( pX ){
79419 assert( pTest!=0 );
79420 opCompare.pRight = aListelem[i].pExpr;
79421 }else{
79422 pTest = aListelem[i].pExpr;
79424 nextCase = sqlite3VdbeMakeLabel(v);
79425 testcase( pTest->op==TK_COLUMN );
79426 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
79427 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
79428 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
79429 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
79430 sqlite3ExprCachePop(pParse, 1);
79431 sqlite3VdbeResolveLabel(v, nextCase);
79433 if( (nExpr&1)!=0 ){
79434 sqlite3ExprCachePush(pParse);
79435 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
79436 sqlite3ExprCachePop(pParse, 1);
79437 }else{
79438 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
79440 assert( db->mallocFailed || pParse->nErr>0
79441 || pParse->iCacheLevel==iCacheLevel );
79442 sqlite3VdbeResolveLabel(v, endLabel);
79443 break;
79445 #ifndef SQLITE_OMIT_TRIGGER
79446 case TK_RAISE: {
79447 assert( pExpr->affinity==OE_Rollback
79448 || pExpr->affinity==OE_Abort
79449 || pExpr->affinity==OE_Fail
79450 || pExpr->affinity==OE_Ignore
79452 if( !pParse->pTriggerTab ){
79453 sqlite3ErrorMsg(pParse,
79454 "RAISE() may only be used within a trigger-program");
79455 return 0;
79457 if( pExpr->affinity==OE_Abort ){
79458 sqlite3MayAbort(pParse);
79460 assert( !ExprHasProperty(pExpr, EP_IntValue) );
79461 if( pExpr->affinity==OE_Ignore ){
79462 sqlite3VdbeAddOp4(
79463 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
79464 }else{
79465 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
79466 pExpr->affinity, pExpr->u.zToken, 0, 0);
79469 break;
79471 #endif
79473 sqlite3ReleaseTempReg(pParse, regFree1);
79474 sqlite3ReleaseTempReg(pParse, regFree2);
79475 return inReg;
79479 ** Factor out the code of the given expression to initialization time.
79481 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
79482 Parse *pParse, /* Parsing context */
79483 Expr *pExpr, /* The expression to code when the VDBE initializes */
79484 int regDest, /* Store the value in this register */
79485 u8 reusable /* True if this expression is reusable */
79487 ExprList *p;
79488 assert( ConstFactorOk(pParse) );
79489 p = pParse->pConstExpr;
79490 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
79491 p = sqlite3ExprListAppend(pParse, p, pExpr);
79492 if( p ){
79493 struct ExprList_item *pItem = &p->a[p->nExpr-1];
79494 pItem->u.iConstExprReg = regDest;
79495 pItem->reusable = reusable;
79497 pParse->pConstExpr = p;
79501 ** Generate code to evaluate an expression and store the results
79502 ** into a register. Return the register number where the results
79503 ** are stored.
79505 ** If the register is a temporary register that can be deallocated,
79506 ** then write its number into *pReg. If the result register is not
79507 ** a temporary, then set *pReg to zero.
79509 ** If pExpr is a constant, then this routine might generate this
79510 ** code to fill the register in the initialization section of the
79511 ** VDBE program, in order to factor it out of the evaluation loop.
79513 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
79514 int r2;
79515 pExpr = sqlite3ExprSkipCollate(pExpr);
79516 if( ConstFactorOk(pParse)
79517 && pExpr->op!=TK_REGISTER
79518 && sqlite3ExprIsConstantNotJoin(pExpr)
79520 ExprList *p = pParse->pConstExpr;
79521 int i;
79522 *pReg = 0;
79523 if( p ){
79524 struct ExprList_item *pItem;
79525 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
79526 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
79527 return pItem->u.iConstExprReg;
79531 r2 = ++pParse->nMem;
79532 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
79533 }else{
79534 int r1 = sqlite3GetTempReg(pParse);
79535 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
79536 if( r2==r1 ){
79537 *pReg = r1;
79538 }else{
79539 sqlite3ReleaseTempReg(pParse, r1);
79540 *pReg = 0;
79543 return r2;
79547 ** Generate code that will evaluate expression pExpr and store the
79548 ** results in register target. The results are guaranteed to appear
79549 ** in register target.
79551 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
79552 int inReg;
79554 assert( target>0 && target<=pParse->nMem );
79555 if( pExpr && pExpr->op==TK_REGISTER ){
79556 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
79557 }else{
79558 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
79559 assert( pParse->pVdbe || pParse->db->mallocFailed );
79560 if( inReg!=target && pParse->pVdbe ){
79561 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
79564 return target;
79568 ** Generate code that evalutes the given expression and puts the result
79569 ** in register target.
79571 ** Also make a copy of the expression results into another "cache" register
79572 ** and modify the expression so that the next time it is evaluated,
79573 ** the result is a copy of the cache register.
79575 ** This routine is used for expressions that are used multiple
79576 ** times. They are evaluated once and the results of the expression
79577 ** are reused.
79579 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
79580 Vdbe *v = pParse->pVdbe;
79581 int inReg;
79582 inReg = sqlite3ExprCode(pParse, pExpr, target);
79583 assert( target>0 );
79584 /* The only place, other than this routine, where expressions can be
79585 ** converted to TK_REGISTER is internal subexpressions in BETWEEN and
79586 ** CASE operators. Neither ever calls this routine. And this routine
79587 ** is never called twice on the same expression. Hence it is impossible
79588 ** for the input to this routine to already be a register. Nevertheless,
79589 ** it seems prudent to keep the ALWAYS() in case the conditions above
79590 ** change with future modifications or enhancements. */
79591 if( ALWAYS(pExpr->op!=TK_REGISTER) ){
79592 int iMem;
79593 iMem = ++pParse->nMem;
79594 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
79595 exprToRegister(pExpr, iMem);
79597 return inReg;
79600 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
79602 ** Generate a human-readable explanation of an expression tree.
79604 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
79605 int op; /* The opcode being coded */
79606 const char *zBinOp = 0; /* Binary operator */
79607 const char *zUniOp = 0; /* Unary operator */
79608 if( pExpr==0 ){
79609 op = TK_NULL;
79610 }else{
79611 op = pExpr->op;
79613 switch( op ){
79614 case TK_AGG_COLUMN: {
79615 sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
79616 pExpr->iTable, pExpr->iColumn);
79617 break;
79619 case TK_COLUMN: {
79620 if( pExpr->iTable<0 ){
79621 /* This only happens when coding check constraints */
79622 sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
79623 }else{
79624 sqlite3ExplainPrintf(pOut, "{%d:%d}",
79625 pExpr->iTable, pExpr->iColumn);
79627 break;
79629 case TK_INTEGER: {
79630 if( pExpr->flags & EP_IntValue ){
79631 sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
79632 }else{
79633 sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
79635 break;
79637 #ifndef SQLITE_OMIT_FLOATING_POINT
79638 case TK_FLOAT: {
79639 sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
79640 break;
79642 #endif
79643 case TK_STRING: {
79644 sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
79645 break;
79647 case TK_NULL: {
79648 sqlite3ExplainPrintf(pOut,"NULL");
79649 break;
79651 #ifndef SQLITE_OMIT_BLOB_LITERAL
79652 case TK_BLOB: {
79653 sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
79654 break;
79656 #endif
79657 case TK_VARIABLE: {
79658 sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
79659 pExpr->u.zToken, pExpr->iColumn);
79660 break;
79662 case TK_REGISTER: {
79663 sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
79664 break;
79666 case TK_AS: {
79667 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79668 break;
79670 #ifndef SQLITE_OMIT_CAST
79671 case TK_CAST: {
79672 /* Expressions of the form: CAST(pLeft AS token) */
79673 const char *zAff = "unk";
79674 switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
79675 case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
79676 case SQLITE_AFF_NONE: zAff = "NONE"; break;
79677 case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
79678 case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
79679 case SQLITE_AFF_REAL: zAff = "REAL"; break;
79681 sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
79682 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79683 sqlite3ExplainPrintf(pOut, ")");
79684 break;
79686 #endif /* SQLITE_OMIT_CAST */
79687 case TK_LT: zBinOp = "LT"; break;
79688 case TK_LE: zBinOp = "LE"; break;
79689 case TK_GT: zBinOp = "GT"; break;
79690 case TK_GE: zBinOp = "GE"; break;
79691 case TK_NE: zBinOp = "NE"; break;
79692 case TK_EQ: zBinOp = "EQ"; break;
79693 case TK_IS: zBinOp = "IS"; break;
79694 case TK_ISNOT: zBinOp = "ISNOT"; break;
79695 case TK_AND: zBinOp = "AND"; break;
79696 case TK_OR: zBinOp = "OR"; break;
79697 case TK_PLUS: zBinOp = "ADD"; break;
79698 case TK_STAR: zBinOp = "MUL"; break;
79699 case TK_MINUS: zBinOp = "SUB"; break;
79700 case TK_REM: zBinOp = "REM"; break;
79701 case TK_BITAND: zBinOp = "BITAND"; break;
79702 case TK_BITOR: zBinOp = "BITOR"; break;
79703 case TK_SLASH: zBinOp = "DIV"; break;
79704 case TK_LSHIFT: zBinOp = "LSHIFT"; break;
79705 case TK_RSHIFT: zBinOp = "RSHIFT"; break;
79706 case TK_CONCAT: zBinOp = "CONCAT"; break;
79708 case TK_UMINUS: zUniOp = "UMINUS"; break;
79709 case TK_UPLUS: zUniOp = "UPLUS"; break;
79710 case TK_BITNOT: zUniOp = "BITNOT"; break;
79711 case TK_NOT: zUniOp = "NOT"; break;
79712 case TK_ISNULL: zUniOp = "ISNULL"; break;
79713 case TK_NOTNULL: zUniOp = "NOTNULL"; break;
79715 case TK_COLLATE: {
79716 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79717 sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
79718 break;
79721 case TK_AGG_FUNCTION:
79722 case TK_FUNCTION: {
79723 ExprList *pFarg; /* List of function arguments */
79724 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
79725 pFarg = 0;
79726 }else{
79727 pFarg = pExpr->x.pList;
79729 if( op==TK_AGG_FUNCTION ){
79730 sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
79731 pExpr->op2, pExpr->u.zToken);
79732 }else{
79733 sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
79735 if( pFarg ){
79736 sqlite3ExplainExprList(pOut, pFarg);
79738 sqlite3ExplainPrintf(pOut, ")");
79739 break;
79741 #ifndef SQLITE_OMIT_SUBQUERY
79742 case TK_EXISTS: {
79743 sqlite3ExplainPrintf(pOut, "EXISTS(");
79744 sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
79745 sqlite3ExplainPrintf(pOut,")");
79746 break;
79748 case TK_SELECT: {
79749 sqlite3ExplainPrintf(pOut, "(");
79750 sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
79751 sqlite3ExplainPrintf(pOut, ")");
79752 break;
79754 case TK_IN: {
79755 sqlite3ExplainPrintf(pOut, "IN(");
79756 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79757 sqlite3ExplainPrintf(pOut, ",");
79758 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
79759 sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
79760 }else{
79761 sqlite3ExplainExprList(pOut, pExpr->x.pList);
79763 sqlite3ExplainPrintf(pOut, ")");
79764 break;
79766 #endif /* SQLITE_OMIT_SUBQUERY */
79769 ** x BETWEEN y AND z
79771 ** This is equivalent to
79773 ** x>=y AND x<=z
79775 ** X is stored in pExpr->pLeft.
79776 ** Y is stored in pExpr->pList->a[0].pExpr.
79777 ** Z is stored in pExpr->pList->a[1].pExpr.
79779 case TK_BETWEEN: {
79780 Expr *pX = pExpr->pLeft;
79781 Expr *pY = pExpr->x.pList->a[0].pExpr;
79782 Expr *pZ = pExpr->x.pList->a[1].pExpr;
79783 sqlite3ExplainPrintf(pOut, "BETWEEN(");
79784 sqlite3ExplainExpr(pOut, pX);
79785 sqlite3ExplainPrintf(pOut, ",");
79786 sqlite3ExplainExpr(pOut, pY);
79787 sqlite3ExplainPrintf(pOut, ",");
79788 sqlite3ExplainExpr(pOut, pZ);
79789 sqlite3ExplainPrintf(pOut, ")");
79790 break;
79792 case TK_TRIGGER: {
79793 /* If the opcode is TK_TRIGGER, then the expression is a reference
79794 ** to a column in the new.* or old.* pseudo-tables available to
79795 ** trigger programs. In this case Expr.iTable is set to 1 for the
79796 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
79797 ** is set to the column of the pseudo-table to read, or to -1 to
79798 ** read the rowid field.
79800 sqlite3ExplainPrintf(pOut, "%s(%d)",
79801 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
79802 break;
79804 case TK_CASE: {
79805 sqlite3ExplainPrintf(pOut, "CASE(");
79806 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79807 sqlite3ExplainPrintf(pOut, ",");
79808 sqlite3ExplainExprList(pOut, pExpr->x.pList);
79809 break;
79811 #ifndef SQLITE_OMIT_TRIGGER
79812 case TK_RAISE: {
79813 const char *zType = "unk";
79814 switch( pExpr->affinity ){
79815 case OE_Rollback: zType = "rollback"; break;
79816 case OE_Abort: zType = "abort"; break;
79817 case OE_Fail: zType = "fail"; break;
79818 case OE_Ignore: zType = "ignore"; break;
79820 sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
79821 break;
79823 #endif
79825 if( zBinOp ){
79826 sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
79827 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79828 sqlite3ExplainPrintf(pOut,",");
79829 sqlite3ExplainExpr(pOut, pExpr->pRight);
79830 sqlite3ExplainPrintf(pOut,")");
79831 }else if( zUniOp ){
79832 sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
79833 sqlite3ExplainExpr(pOut, pExpr->pLeft);
79834 sqlite3ExplainPrintf(pOut,")");
79837 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
79839 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
79841 ** Generate a human-readable explanation of an expression list.
79843 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
79844 int i;
79845 if( pList==0 || pList->nExpr==0 ){
79846 sqlite3ExplainPrintf(pOut, "(empty-list)");
79847 return;
79848 }else if( pList->nExpr==1 ){
79849 sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
79850 }else{
79851 sqlite3ExplainPush(pOut);
79852 for(i=0; i<pList->nExpr; i++){
79853 sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
79854 sqlite3ExplainPush(pOut);
79855 sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
79856 sqlite3ExplainPop(pOut);
79857 if( pList->a[i].zName ){
79858 sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
79860 if( pList->a[i].bSpanIsTab ){
79861 sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
79863 if( i<pList->nExpr-1 ){
79864 sqlite3ExplainNL(pOut);
79867 sqlite3ExplainPop(pOut);
79870 #endif /* SQLITE_DEBUG */
79873 ** Generate code that pushes the value of every element of the given
79874 ** expression list into a sequence of registers beginning at target.
79876 ** Return the number of elements evaluated.
79878 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
79879 ** filled using OP_SCopy. OP_Copy must be used instead.
79881 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
79882 ** factored out into initialization code.
79884 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
79885 Parse *pParse, /* Parsing context */
79886 ExprList *pList, /* The expression list to be coded */
79887 int target, /* Where to write results */
79888 u8 flags /* SQLITE_ECEL_* flags */
79890 struct ExprList_item *pItem;
79891 int i, n;
79892 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
79893 assert( pList!=0 );
79894 assert( target>0 );
79895 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
79896 n = pList->nExpr;
79897 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
79898 for(pItem=pList->a, i=0; i<n; i++, pItem++){
79899 Expr *pExpr = pItem->pExpr;
79900 if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
79901 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
79902 }else{
79903 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
79904 if( inReg!=target+i ){
79905 VdbeOp *pOp;
79906 Vdbe *v = pParse->pVdbe;
79907 if( copyOp==OP_Copy
79908 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
79909 && pOp->p1+pOp->p3+1==inReg
79910 && pOp->p2+pOp->p3+1==target+i
79912 pOp->p3++;
79913 }else{
79914 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
79919 return n;
79923 ** Generate code for a BETWEEN operator.
79925 ** x BETWEEN y AND z
79927 ** The above is equivalent to
79929 ** x>=y AND x<=z
79931 ** Code it as such, taking care to do the common subexpression
79932 ** elementation of x.
79934 static void exprCodeBetween(
79935 Parse *pParse, /* Parsing and code generating context */
79936 Expr *pExpr, /* The BETWEEN expression */
79937 int dest, /* Jump here if the jump is taken */
79938 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
79939 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
79941 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
79942 Expr compLeft; /* The x>=y term */
79943 Expr compRight; /* The x<=z term */
79944 Expr exprX; /* The x subexpression */
79945 int regFree1 = 0; /* Temporary use register */
79947 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79948 exprX = *pExpr->pLeft;
79949 exprAnd.op = TK_AND;
79950 exprAnd.pLeft = &compLeft;
79951 exprAnd.pRight = &compRight;
79952 compLeft.op = TK_GE;
79953 compLeft.pLeft = &exprX;
79954 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
79955 compRight.op = TK_LE;
79956 compRight.pLeft = &exprX;
79957 compRight.pRight = pExpr->x.pList->a[1].pExpr;
79958 exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
79959 if( jumpIfTrue ){
79960 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
79961 }else{
79962 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
79964 sqlite3ReleaseTempReg(pParse, regFree1);
79966 /* Ensure adequate test coverage */
79967 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
79968 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
79969 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
79970 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
79971 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
79972 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
79973 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
79974 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
79978 ** Generate code for a boolean expression such that a jump is made
79979 ** to the label "dest" if the expression is true but execution
79980 ** continues straight thru if the expression is false.
79982 ** If the expression evaluates to NULL (neither true nor false), then
79983 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
79985 ** This code depends on the fact that certain token values (ex: TK_EQ)
79986 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
79987 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
79988 ** the make process cause these values to align. Assert()s in the code
79989 ** below verify that the numbers are aligned correctly.
79991 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
79992 Vdbe *v = pParse->pVdbe;
79993 int op = 0;
79994 int regFree1 = 0;
79995 int regFree2 = 0;
79996 int r1, r2;
79998 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
79999 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
80000 if( NEVER(pExpr==0) ) return; /* No way this can happen */
80001 op = pExpr->op;
80002 switch( op ){
80003 case TK_AND: {
80004 int d2 = sqlite3VdbeMakeLabel(v);
80005 testcase( jumpIfNull==0 );
80006 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
80007 sqlite3ExprCachePush(pParse);
80008 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
80009 sqlite3VdbeResolveLabel(v, d2);
80010 sqlite3ExprCachePop(pParse, 1);
80011 break;
80013 case TK_OR: {
80014 testcase( jumpIfNull==0 );
80015 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
80016 sqlite3ExprCachePush(pParse);
80017 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
80018 sqlite3ExprCachePop(pParse, 1);
80019 break;
80021 case TK_NOT: {
80022 testcase( jumpIfNull==0 );
80023 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
80024 break;
80026 case TK_LT:
80027 case TK_LE:
80028 case TK_GT:
80029 case TK_GE:
80030 case TK_NE:
80031 case TK_EQ: {
80032 assert( TK_LT==OP_Lt );
80033 assert( TK_LE==OP_Le );
80034 assert( TK_GT==OP_Gt );
80035 assert( TK_GE==OP_Ge );
80036 assert( TK_EQ==OP_Eq );
80037 assert( TK_NE==OP_Ne );
80038 testcase( op==TK_LT );
80039 testcase( op==TK_LE );
80040 testcase( op==TK_GT );
80041 testcase( op==TK_GE );
80042 testcase( op==TK_EQ );
80043 testcase( op==TK_NE );
80044 testcase( jumpIfNull==0 );
80045 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80046 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80047 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
80048 r1, r2, dest, jumpIfNull);
80049 testcase( regFree1==0 );
80050 testcase( regFree2==0 );
80051 break;
80053 case TK_IS:
80054 case TK_ISNOT: {
80055 testcase( op==TK_IS );
80056 testcase( op==TK_ISNOT );
80057 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80058 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80059 op = (op==TK_IS) ? TK_EQ : TK_NE;
80060 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
80061 r1, r2, dest, SQLITE_NULLEQ);
80062 testcase( regFree1==0 );
80063 testcase( regFree2==0 );
80064 break;
80066 case TK_ISNULL:
80067 case TK_NOTNULL: {
80068 assert( TK_ISNULL==OP_IsNull );
80069 assert( TK_NOTNULL==OP_NotNull );
80070 testcase( op==TK_ISNULL );
80071 testcase( op==TK_NOTNULL );
80072 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80073 sqlite3VdbeAddOp2(v, op, r1, dest);
80074 testcase( regFree1==0 );
80075 break;
80077 case TK_BETWEEN: {
80078 testcase( jumpIfNull==0 );
80079 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
80080 break;
80082 #ifndef SQLITE_OMIT_SUBQUERY
80083 case TK_IN: {
80084 int destIfFalse = sqlite3VdbeMakeLabel(v);
80085 int destIfNull = jumpIfNull ? dest : destIfFalse;
80086 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
80087 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
80088 sqlite3VdbeResolveLabel(v, destIfFalse);
80089 break;
80091 #endif
80092 default: {
80093 if( exprAlwaysTrue(pExpr) ){
80094 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
80095 }else if( exprAlwaysFalse(pExpr) ){
80096 /* No-op */
80097 }else{
80098 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
80099 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
80100 testcase( regFree1==0 );
80101 testcase( jumpIfNull==0 );
80103 break;
80106 sqlite3ReleaseTempReg(pParse, regFree1);
80107 sqlite3ReleaseTempReg(pParse, regFree2);
80111 ** Generate code for a boolean expression such that a jump is made
80112 ** to the label "dest" if the expression is false but execution
80113 ** continues straight thru if the expression is true.
80115 ** If the expression evaluates to NULL (neither true nor false) then
80116 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
80117 ** is 0.
80119 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
80120 Vdbe *v = pParse->pVdbe;
80121 int op = 0;
80122 int regFree1 = 0;
80123 int regFree2 = 0;
80124 int r1, r2;
80126 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
80127 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
80128 if( pExpr==0 ) return;
80130 /* The value of pExpr->op and op are related as follows:
80132 ** pExpr->op op
80133 ** --------- ----------
80134 ** TK_ISNULL OP_NotNull
80135 ** TK_NOTNULL OP_IsNull
80136 ** TK_NE OP_Eq
80137 ** TK_EQ OP_Ne
80138 ** TK_GT OP_Le
80139 ** TK_LE OP_Gt
80140 ** TK_GE OP_Lt
80141 ** TK_LT OP_Ge
80143 ** For other values of pExpr->op, op is undefined and unused.
80144 ** The value of TK_ and OP_ constants are arranged such that we
80145 ** can compute the mapping above using the following expression.
80146 ** Assert()s verify that the computation is correct.
80148 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
80150 /* Verify correct alignment of TK_ and OP_ constants
80152 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
80153 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
80154 assert( pExpr->op!=TK_NE || op==OP_Eq );
80155 assert( pExpr->op!=TK_EQ || op==OP_Ne );
80156 assert( pExpr->op!=TK_LT || op==OP_Ge );
80157 assert( pExpr->op!=TK_LE || op==OP_Gt );
80158 assert( pExpr->op!=TK_GT || op==OP_Le );
80159 assert( pExpr->op!=TK_GE || op==OP_Lt );
80161 switch( pExpr->op ){
80162 case TK_AND: {
80163 testcase( jumpIfNull==0 );
80164 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
80165 sqlite3ExprCachePush(pParse);
80166 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
80167 sqlite3ExprCachePop(pParse, 1);
80168 break;
80170 case TK_OR: {
80171 int d2 = sqlite3VdbeMakeLabel(v);
80172 testcase( jumpIfNull==0 );
80173 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
80174 sqlite3ExprCachePush(pParse);
80175 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
80176 sqlite3VdbeResolveLabel(v, d2);
80177 sqlite3ExprCachePop(pParse, 1);
80178 break;
80180 case TK_NOT: {
80181 testcase( jumpIfNull==0 );
80182 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
80183 break;
80185 case TK_LT:
80186 case TK_LE:
80187 case TK_GT:
80188 case TK_GE:
80189 case TK_NE:
80190 case TK_EQ: {
80191 testcase( op==TK_LT );
80192 testcase( op==TK_LE );
80193 testcase( op==TK_GT );
80194 testcase( op==TK_GE );
80195 testcase( op==TK_EQ );
80196 testcase( op==TK_NE );
80197 testcase( jumpIfNull==0 );
80198 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80199 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80200 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
80201 r1, r2, dest, jumpIfNull);
80202 testcase( regFree1==0 );
80203 testcase( regFree2==0 );
80204 break;
80206 case TK_IS:
80207 case TK_ISNOT: {
80208 testcase( pExpr->op==TK_IS );
80209 testcase( pExpr->op==TK_ISNOT );
80210 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80211 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
80212 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
80213 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
80214 r1, r2, dest, SQLITE_NULLEQ);
80215 testcase( regFree1==0 );
80216 testcase( regFree2==0 );
80217 break;
80219 case TK_ISNULL:
80220 case TK_NOTNULL: {
80221 testcase( op==TK_ISNULL );
80222 testcase( op==TK_NOTNULL );
80223 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
80224 sqlite3VdbeAddOp2(v, op, r1, dest);
80225 testcase( regFree1==0 );
80226 break;
80228 case TK_BETWEEN: {
80229 testcase( jumpIfNull==0 );
80230 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
80231 break;
80233 #ifndef SQLITE_OMIT_SUBQUERY
80234 case TK_IN: {
80235 if( jumpIfNull ){
80236 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
80237 }else{
80238 int destIfNull = sqlite3VdbeMakeLabel(v);
80239 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
80240 sqlite3VdbeResolveLabel(v, destIfNull);
80242 break;
80244 #endif
80245 default: {
80246 if( exprAlwaysFalse(pExpr) ){
80247 sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
80248 }else if( exprAlwaysTrue(pExpr) ){
80249 /* no-op */
80250 }else{
80251 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
80252 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
80253 testcase( regFree1==0 );
80254 testcase( jumpIfNull==0 );
80256 break;
80259 sqlite3ReleaseTempReg(pParse, regFree1);
80260 sqlite3ReleaseTempReg(pParse, regFree2);
80264 ** Do a deep comparison of two expression trees. Return 0 if the two
80265 ** expressions are completely identical. Return 1 if they differ only
80266 ** by a COLLATE operator at the top level. Return 2 if there are differences
80267 ** other than the top-level COLLATE operator.
80269 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
80270 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
80272 ** The pA side might be using TK_REGISTER. If that is the case and pB is
80273 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
80275 ** Sometimes this routine will return 2 even if the two expressions
80276 ** really are equivalent. If we cannot prove that the expressions are
80277 ** identical, we return 2 just to be safe. So if this routine
80278 ** returns 2, then you do not really know for certain if the two
80279 ** expressions are the same. But if you get a 0 or 1 return, then you
80280 ** can be sure the expressions are the same. In the places where
80281 ** this routine is used, it does not hurt to get an extra 2 - that
80282 ** just might result in some slightly slower code. But returning
80283 ** an incorrect 0 or 1 could lead to a malfunction.
80285 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
80286 u32 combinedFlags;
80287 if( pA==0 || pB==0 ){
80288 return pB==pA ? 0 : 2;
80290 combinedFlags = pA->flags | pB->flags;
80291 if( combinedFlags & EP_IntValue ){
80292 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
80293 return 0;
80295 return 2;
80297 if( pA->op!=pB->op ){
80298 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
80299 return 1;
80301 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
80302 return 1;
80304 return 2;
80306 if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
80307 if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
80308 return pA->op==TK_COLLATE ? 1 : 2;
80311 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
80312 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
80313 if( combinedFlags & EP_xIsSelect ) return 2;
80314 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
80315 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
80316 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
80317 if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
80318 if( pA->iColumn!=pB->iColumn ) return 2;
80319 if( pA->iTable!=pB->iTable
80320 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
80323 return 0;
80327 ** Compare two ExprList objects. Return 0 if they are identical and
80328 ** non-zero if they differ in any way.
80330 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
80331 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
80333 ** This routine might return non-zero for equivalent ExprLists. The
80334 ** only consequence will be disabled optimizations. But this routine
80335 ** must never return 0 if the two ExprList objects are different, or
80336 ** a malfunction will result.
80338 ** Two NULL pointers are considered to be the same. But a NULL pointer
80339 ** always differs from a non-NULL pointer.
80341 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
80342 int i;
80343 if( pA==0 && pB==0 ) return 0;
80344 if( pA==0 || pB==0 ) return 1;
80345 if( pA->nExpr!=pB->nExpr ) return 1;
80346 for(i=0; i<pA->nExpr; i++){
80347 Expr *pExprA = pA->a[i].pExpr;
80348 Expr *pExprB = pB->a[i].pExpr;
80349 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
80350 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
80352 return 0;
80356 ** Return true if we can prove the pE2 will always be true if pE1 is
80357 ** true. Return false if we cannot complete the proof or if pE2 might
80358 ** be false. Examples:
80360 ** pE1: x==5 pE2: x==5 Result: true
80361 ** pE1: x>0 pE2: x==5 Result: false
80362 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
80363 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
80364 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
80365 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
80366 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
80368 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
80369 ** Expr.iTable<0 then assume a table number given by iTab.
80371 ** When in doubt, return false. Returning true might give a performance
80372 ** improvement. Returning false might cause a performance reduction, but
80373 ** it will always give the correct answer and is hence always safe.
80375 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
80376 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
80377 return 1;
80379 if( pE2->op==TK_OR
80380 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
80381 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
80383 return 1;
80385 if( pE2->op==TK_NOTNULL
80386 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
80387 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
80389 return 1;
80391 return 0;
80395 ** An instance of the following structure is used by the tree walker
80396 ** to count references to table columns in the arguments of an
80397 ** aggregate function, in order to implement the
80398 ** sqlite3FunctionThisSrc() routine.
80400 struct SrcCount {
80401 SrcList *pSrc; /* One particular FROM clause in a nested query */
80402 int nThis; /* Number of references to columns in pSrcList */
80403 int nOther; /* Number of references to columns in other FROM clauses */
80407 ** Count the number of references to columns.
80409 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
80410 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
80411 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
80412 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
80413 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
80414 ** NEVER() will need to be removed. */
80415 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
80416 int i;
80417 struct SrcCount *p = pWalker->u.pSrcCount;
80418 SrcList *pSrc = p->pSrc;
80419 for(i=0; i<pSrc->nSrc; i++){
80420 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
80422 if( i<pSrc->nSrc ){
80423 p->nThis++;
80424 }else{
80425 p->nOther++;
80428 return WRC_Continue;
80432 ** Determine if any of the arguments to the pExpr Function reference
80433 ** pSrcList. Return true if they do. Also return true if the function
80434 ** has no arguments or has only constant arguments. Return false if pExpr
80435 ** references columns but not columns of tables found in pSrcList.
80437 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
80438 Walker w;
80439 struct SrcCount cnt;
80440 assert( pExpr->op==TK_AGG_FUNCTION );
80441 memset(&w, 0, sizeof(w));
80442 w.xExprCallback = exprSrcCount;
80443 w.u.pSrcCount = &cnt;
80444 cnt.pSrc = pSrcList;
80445 cnt.nThis = 0;
80446 cnt.nOther = 0;
80447 sqlite3WalkExprList(&w, pExpr->x.pList);
80448 return cnt.nThis>0 || cnt.nOther==0;
80452 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
80453 ** the new element. Return a negative number if malloc fails.
80455 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
80456 int i;
80457 pInfo->aCol = sqlite3ArrayAllocate(
80459 pInfo->aCol,
80460 sizeof(pInfo->aCol[0]),
80461 &pInfo->nColumn,
80464 return i;
80468 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
80469 ** the new element. Return a negative number if malloc fails.
80471 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
80472 int i;
80473 pInfo->aFunc = sqlite3ArrayAllocate(
80474 db,
80475 pInfo->aFunc,
80476 sizeof(pInfo->aFunc[0]),
80477 &pInfo->nFunc,
80480 return i;
80484 ** This is the xExprCallback for a tree walker. It is used to
80485 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
80486 ** for additional information.
80488 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
80489 int i;
80490 NameContext *pNC = pWalker->u.pNC;
80491 Parse *pParse = pNC->pParse;
80492 SrcList *pSrcList = pNC->pSrcList;
80493 AggInfo *pAggInfo = pNC->pAggInfo;
80495 switch( pExpr->op ){
80496 case TK_AGG_COLUMN:
80497 case TK_COLUMN: {
80498 testcase( pExpr->op==TK_AGG_COLUMN );
80499 testcase( pExpr->op==TK_COLUMN );
80500 /* Check to see if the column is in one of the tables in the FROM
80501 ** clause of the aggregate query */
80502 if( ALWAYS(pSrcList!=0) ){
80503 struct SrcList_item *pItem = pSrcList->a;
80504 for(i=0; i<pSrcList->nSrc; i++, pItem++){
80505 struct AggInfo_col *pCol;
80506 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
80507 if( pExpr->iTable==pItem->iCursor ){
80508 /* If we reach this point, it means that pExpr refers to a table
80509 ** that is in the FROM clause of the aggregate query.
80511 ** Make an entry for the column in pAggInfo->aCol[] if there
80512 ** is not an entry there already.
80514 int k;
80515 pCol = pAggInfo->aCol;
80516 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
80517 if( pCol->iTable==pExpr->iTable &&
80518 pCol->iColumn==pExpr->iColumn ){
80519 break;
80522 if( (k>=pAggInfo->nColumn)
80523 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
80525 pCol = &pAggInfo->aCol[k];
80526 pCol->pTab = pExpr->pTab;
80527 pCol->iTable = pExpr->iTable;
80528 pCol->iColumn = pExpr->iColumn;
80529 pCol->iMem = ++pParse->nMem;
80530 pCol->iSorterColumn = -1;
80531 pCol->pExpr = pExpr;
80532 if( pAggInfo->pGroupBy ){
80533 int j, n;
80534 ExprList *pGB = pAggInfo->pGroupBy;
80535 struct ExprList_item *pTerm = pGB->a;
80536 n = pGB->nExpr;
80537 for(j=0; j<n; j++, pTerm++){
80538 Expr *pE = pTerm->pExpr;
80539 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
80540 pE->iColumn==pExpr->iColumn ){
80541 pCol->iSorterColumn = j;
80542 break;
80546 if( pCol->iSorterColumn<0 ){
80547 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
80550 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
80551 ** because it was there before or because we just created it).
80552 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
80553 ** pAggInfo->aCol[] entry.
80555 ExprSetVVAProperty(pExpr, EP_NoReduce);
80556 pExpr->pAggInfo = pAggInfo;
80557 pExpr->op = TK_AGG_COLUMN;
80558 pExpr->iAgg = (i16)k;
80559 break;
80560 } /* endif pExpr->iTable==pItem->iCursor */
80561 } /* end loop over pSrcList */
80563 return WRC_Prune;
80565 case TK_AGG_FUNCTION: {
80566 if( (pNC->ncFlags & NC_InAggFunc)==0
80567 && pWalker->walkerDepth==pExpr->op2
80569 /* Check to see if pExpr is a duplicate of another aggregate
80570 ** function that is already in the pAggInfo structure
80572 struct AggInfo_func *pItem = pAggInfo->aFunc;
80573 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
80574 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
80575 break;
80578 if( i>=pAggInfo->nFunc ){
80579 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
80581 u8 enc = ENC(pParse->db);
80582 i = addAggInfoFunc(pParse->db, pAggInfo);
80583 if( i>=0 ){
80584 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
80585 pItem = &pAggInfo->aFunc[i];
80586 pItem->pExpr = pExpr;
80587 pItem->iMem = ++pParse->nMem;
80588 assert( !ExprHasProperty(pExpr, EP_IntValue) );
80589 pItem->pFunc = sqlite3FindFunction(pParse->db,
80590 pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
80591 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
80592 if( pExpr->flags & EP_Distinct ){
80593 pItem->iDistinct = pParse->nTab++;
80594 }else{
80595 pItem->iDistinct = -1;
80599 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
80601 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
80602 ExprSetVVAProperty(pExpr, EP_NoReduce);
80603 pExpr->iAgg = (i16)i;
80604 pExpr->pAggInfo = pAggInfo;
80605 return WRC_Prune;
80606 }else{
80607 return WRC_Continue;
80611 return WRC_Continue;
80613 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
80614 UNUSED_PARAMETER(pWalker);
80615 UNUSED_PARAMETER(pSelect);
80616 return WRC_Continue;
80620 ** Analyze the pExpr expression looking for aggregate functions and
80621 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
80622 ** points to. Additional entries are made on the AggInfo object as
80623 ** necessary.
80625 ** This routine should only be called after the expression has been
80626 ** analyzed by sqlite3ResolveExprNames().
80628 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
80629 Walker w;
80630 memset(&w, 0, sizeof(w));
80631 w.xExprCallback = analyzeAggregate;
80632 w.xSelectCallback = analyzeAggregatesInSelect;
80633 w.u.pNC = pNC;
80634 assert( pNC->pSrcList!=0 );
80635 sqlite3WalkExpr(&w, pExpr);
80639 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
80640 ** expression list. Return the number of errors.
80642 ** If an error is found, the analysis is cut short.
80644 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
80645 struct ExprList_item *pItem;
80646 int i;
80647 if( pList ){
80648 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
80649 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
80655 ** Allocate a single new register for use to hold some intermediate result.
80657 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
80658 if( pParse->nTempReg==0 ){
80659 return ++pParse->nMem;
80661 return pParse->aTempReg[--pParse->nTempReg];
80665 ** Deallocate a register, making available for reuse for some other
80666 ** purpose.
80668 ** If a register is currently being used by the column cache, then
80669 ** the dallocation is deferred until the column cache line that uses
80670 ** the register becomes stale.
80672 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
80673 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
80674 int i;
80675 struct yColCache *p;
80676 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
80677 if( p->iReg==iReg ){
80678 p->tempReg = 1;
80679 return;
80682 pParse->aTempReg[pParse->nTempReg++] = iReg;
80687 ** Allocate or deallocate a block of nReg consecutive registers
80689 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
80690 int i, n;
80691 i = pParse->iRangeReg;
80692 n = pParse->nRangeReg;
80693 if( nReg<=n ){
80694 assert( !usedAsColumnCache(pParse, i, i+n-1) );
80695 pParse->iRangeReg += nReg;
80696 pParse->nRangeReg -= nReg;
80697 }else{
80698 i = pParse->nMem+1;
80699 pParse->nMem += nReg;
80701 return i;
80703 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
80704 sqlite3ExprCacheRemove(pParse, iReg, nReg);
80705 if( nReg>pParse->nRangeReg ){
80706 pParse->nRangeReg = nReg;
80707 pParse->iRangeReg = iReg;
80712 ** Mark all temporary registers as being unavailable for reuse.
80714 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
80715 pParse->nTempReg = 0;
80716 pParse->nRangeReg = 0;
80719 /************** End of expr.c ************************************************/
80720 /************** Begin file alter.c *******************************************/
80722 ** 2005 February 15
80724 ** The author disclaims copyright to this source code. In place of
80725 ** a legal notice, here is a blessing:
80727 ** May you do good and not evil.
80728 ** May you find forgiveness for yourself and forgive others.
80729 ** May you share freely, never taking more than you give.
80731 *************************************************************************
80732 ** This file contains C code routines that used to generate VDBE code
80733 ** that implements the ALTER TABLE command.
80737 ** The code in this file only exists if we are not omitting the
80738 ** ALTER TABLE logic from the build.
80740 #ifndef SQLITE_OMIT_ALTERTABLE
80744 ** This function is used by SQL generated to implement the
80745 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
80746 ** CREATE INDEX command. The second is a table name. The table name in
80747 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
80748 ** argument and the result returned. Examples:
80750 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
80751 ** -> 'CREATE TABLE def(a, b, c)'
80753 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
80754 ** -> 'CREATE INDEX i ON def(a, b, c)'
80756 static void renameTableFunc(
80757 sqlite3_context *context,
80758 int NotUsed,
80759 sqlite3_value **argv
80761 unsigned char const *zSql = sqlite3_value_text(argv[0]);
80762 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
80764 int token;
80765 Token tname;
80766 unsigned char const *zCsr = zSql;
80767 int len = 0;
80768 char *zRet;
80770 sqlite3 *db = sqlite3_context_db_handle(context);
80772 UNUSED_PARAMETER(NotUsed);
80774 /* The principle used to locate the table name in the CREATE TABLE
80775 ** statement is that the table name is the first non-space token that
80776 ** is immediately followed by a TK_LP or TK_USING token.
80778 if( zSql ){
80779 do {
80780 if( !*zCsr ){
80781 /* Ran out of input before finding an opening bracket. Return NULL. */
80782 return;
80785 /* Store the token that zCsr points to in tname. */
80786 tname.z = (char*)zCsr;
80787 tname.n = len;
80789 /* Advance zCsr to the next token. Store that token type in 'token',
80790 ** and its length in 'len' (to be used next iteration of this loop).
80792 do {
80793 zCsr += len;
80794 len = sqlite3GetToken(zCsr, &token);
80795 } while( token==TK_SPACE );
80796 assert( len>0 );
80797 } while( token!=TK_LP && token!=TK_USING );
80799 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
80800 zTableName, tname.z+tname.n);
80801 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
80806 ** This C function implements an SQL user function that is used by SQL code
80807 ** generated by the ALTER TABLE ... RENAME command to modify the definition
80808 ** of any foreign key constraints that use the table being renamed as the
80809 ** parent table. It is passed three arguments:
80811 ** 1) The complete text of the CREATE TABLE statement being modified,
80812 ** 2) The old name of the table being renamed, and
80813 ** 3) The new name of the table being renamed.
80815 ** It returns the new CREATE TABLE statement. For example:
80817 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
80818 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
80820 #ifndef SQLITE_OMIT_FOREIGN_KEY
80821 static void renameParentFunc(
80822 sqlite3_context *context,
80823 int NotUsed,
80824 sqlite3_value **argv
80826 sqlite3 *db = sqlite3_context_db_handle(context);
80827 char *zOutput = 0;
80828 char *zResult;
80829 unsigned char const *zInput = sqlite3_value_text(argv[0]);
80830 unsigned char const *zOld = sqlite3_value_text(argv[1]);
80831 unsigned char const *zNew = sqlite3_value_text(argv[2]);
80833 unsigned const char *z; /* Pointer to token */
80834 int n; /* Length of token z */
80835 int token; /* Type of token */
80837 UNUSED_PARAMETER(NotUsed);
80838 for(z=zInput; *z; z=z+n){
80839 n = sqlite3GetToken(z, &token);
80840 if( token==TK_REFERENCES ){
80841 char *zParent;
80842 do {
80843 z += n;
80844 n = sqlite3GetToken(z, &token);
80845 }while( token==TK_SPACE );
80847 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
80848 if( zParent==0 ) break;
80849 sqlite3Dequote(zParent);
80850 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
80851 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
80852 (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
80854 sqlite3DbFree(db, zOutput);
80855 zOutput = zOut;
80856 zInput = &z[n];
80858 sqlite3DbFree(db, zParent);
80862 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
80863 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
80864 sqlite3DbFree(db, zOutput);
80866 #endif
80868 #ifndef SQLITE_OMIT_TRIGGER
80869 /* This function is used by SQL generated to implement the
80870 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
80871 ** statement. The second is a table name. The table name in the CREATE
80872 ** TRIGGER statement is replaced with the third argument and the result
80873 ** returned. This is analagous to renameTableFunc() above, except for CREATE
80874 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
80876 static void renameTriggerFunc(
80877 sqlite3_context *context,
80878 int NotUsed,
80879 sqlite3_value **argv
80881 unsigned char const *zSql = sqlite3_value_text(argv[0]);
80882 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
80884 int token;
80885 Token tname;
80886 int dist = 3;
80887 unsigned char const *zCsr = zSql;
80888 int len = 0;
80889 char *zRet;
80890 sqlite3 *db = sqlite3_context_db_handle(context);
80892 UNUSED_PARAMETER(NotUsed);
80894 /* The principle used to locate the table name in the CREATE TRIGGER
80895 ** statement is that the table name is the first token that is immediatedly
80896 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
80897 ** of TK_WHEN, TK_BEGIN or TK_FOR.
80899 if( zSql ){
80900 do {
80902 if( !*zCsr ){
80903 /* Ran out of input before finding the table name. Return NULL. */
80904 return;
80907 /* Store the token that zCsr points to in tname. */
80908 tname.z = (char*)zCsr;
80909 tname.n = len;
80911 /* Advance zCsr to the next token. Store that token type in 'token',
80912 ** and its length in 'len' (to be used next iteration of this loop).
80914 do {
80915 zCsr += len;
80916 len = sqlite3GetToken(zCsr, &token);
80917 }while( token==TK_SPACE );
80918 assert( len>0 );
80920 /* Variable 'dist' stores the number of tokens read since the most
80921 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
80922 ** token is read and 'dist' equals 2, the condition stated above
80923 ** to be met.
80925 ** Note that ON cannot be a database, table or column name, so
80926 ** there is no need to worry about syntax like
80927 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
80929 dist++;
80930 if( token==TK_DOT || token==TK_ON ){
80931 dist = 0;
80933 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
80935 /* Variable tname now contains the token that is the old table-name
80936 ** in the CREATE TRIGGER statement.
80938 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
80939 zTableName, tname.z+tname.n);
80940 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
80943 #endif /* !SQLITE_OMIT_TRIGGER */
80946 ** Register built-in functions used to help implement ALTER TABLE
80948 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
80949 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
80950 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
80951 #ifndef SQLITE_OMIT_TRIGGER
80952 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
80953 #endif
80954 #ifndef SQLITE_OMIT_FOREIGN_KEY
80955 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
80956 #endif
80958 int i;
80959 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
80960 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
80962 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
80963 sqlite3FuncDefInsert(pHash, &aFunc[i]);
80968 ** This function is used to create the text of expressions of the form:
80970 ** name=<constant1> OR name=<constant2> OR ...
80972 ** If argument zWhere is NULL, then a pointer string containing the text
80973 ** "name=<constant>" is returned, where <constant> is the quoted version
80974 ** of the string passed as argument zConstant. The returned buffer is
80975 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
80976 ** caller to ensure that it is eventually freed.
80978 ** If argument zWhere is not NULL, then the string returned is
80979 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
80980 ** In this case zWhere is passed to sqlite3DbFree() before returning.
80983 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
80984 char *zNew;
80985 if( !zWhere ){
80986 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
80987 }else{
80988 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
80989 sqlite3DbFree(db, zWhere);
80991 return zNew;
80994 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
80996 ** Generate the text of a WHERE expression which can be used to select all
80997 ** tables that have foreign key constraints that refer to table pTab (i.e.
80998 ** constraints for which pTab is the parent table) from the sqlite_master
80999 ** table.
81001 static char *whereForeignKeys(Parse *pParse, Table *pTab){
81002 FKey *p;
81003 char *zWhere = 0;
81004 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81005 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
81007 return zWhere;
81009 #endif
81012 ** Generate the text of a WHERE expression which can be used to select all
81013 ** temporary triggers on table pTab from the sqlite_temp_master table. If
81014 ** table pTab has no temporary triggers, or is itself stored in the
81015 ** temporary database, NULL is returned.
81017 static char *whereTempTriggers(Parse *pParse, Table *pTab){
81018 Trigger *pTrig;
81019 char *zWhere = 0;
81020 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
81022 /* If the table is not located in the temp-db (in which case NULL is
81023 ** returned, loop through the tables list of triggers. For each trigger
81024 ** that is not part of the temp-db schema, add a clause to the WHERE
81025 ** expression being built up in zWhere.
81027 if( pTab->pSchema!=pTempSchema ){
81028 sqlite3 *db = pParse->db;
81029 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
81030 if( pTrig->pSchema==pTempSchema ){
81031 zWhere = whereOrName(db, zWhere, pTrig->zName);
81035 if( zWhere ){
81036 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
81037 sqlite3DbFree(pParse->db, zWhere);
81038 zWhere = zNew;
81040 return zWhere;
81044 ** Generate code to drop and reload the internal representation of table
81045 ** pTab from the database, including triggers and temporary triggers.
81046 ** Argument zName is the name of the table in the database schema at
81047 ** the time the generated code is executed. This can be different from
81048 ** pTab->zName if this function is being called to code part of an
81049 ** "ALTER TABLE RENAME TO" statement.
81051 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
81052 Vdbe *v;
81053 char *zWhere;
81054 int iDb; /* Index of database containing pTab */
81055 #ifndef SQLITE_OMIT_TRIGGER
81056 Trigger *pTrig;
81057 #endif
81059 v = sqlite3GetVdbe(pParse);
81060 if( NEVER(v==0) ) return;
81061 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81062 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81063 assert( iDb>=0 );
81065 #ifndef SQLITE_OMIT_TRIGGER
81066 /* Drop any table triggers from the internal schema. */
81067 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
81068 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
81069 assert( iTrigDb==iDb || iTrigDb==1 );
81070 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
81072 #endif
81074 /* Drop the table and index from the internal schema. */
81075 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
81077 /* Reload the table, index and permanent trigger schemas. */
81078 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
81079 if( !zWhere ) return;
81080 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
81082 #ifndef SQLITE_OMIT_TRIGGER
81083 /* Now, if the table is not stored in the temp database, reload any temp
81084 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
81086 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
81087 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
81089 #endif
81093 ** Parameter zName is the name of a table that is about to be altered
81094 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
81095 ** If the table is a system table, this function leaves an error message
81096 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
81098 ** Or, if zName is not a system table, zero is returned.
81100 static int isSystemTable(Parse *pParse, const char *zName){
81101 if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
81102 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
81103 return 1;
81105 return 0;
81109 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
81110 ** command.
81112 SQLITE_PRIVATE void sqlite3AlterRenameTable(
81113 Parse *pParse, /* Parser context. */
81114 SrcList *pSrc, /* The table to rename. */
81115 Token *pName /* The new table name. */
81117 int iDb; /* Database that contains the table */
81118 char *zDb; /* Name of database iDb */
81119 Table *pTab; /* Table being renamed */
81120 char *zName = 0; /* NULL-terminated version of pName */
81121 sqlite3 *db = pParse->db; /* Database connection */
81122 int nTabName; /* Number of UTF-8 characters in zTabName */
81123 const char *zTabName; /* Original name of the table */
81124 Vdbe *v;
81125 #ifndef SQLITE_OMIT_TRIGGER
81126 char *zWhere = 0; /* Where clause to locate temp triggers */
81127 #endif
81128 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
81129 int savedDbFlags; /* Saved value of db->flags */
81131 savedDbFlags = db->flags;
81132 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
81133 assert( pSrc->nSrc==1 );
81134 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81136 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
81137 if( !pTab ) goto exit_rename_table;
81138 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81139 zDb = db->aDb[iDb].zName;
81140 db->flags |= SQLITE_PreferBuiltin;
81142 /* Get a NULL terminated version of the new table name. */
81143 zName = sqlite3NameFromToken(db, pName);
81144 if( !zName ) goto exit_rename_table;
81146 /* Check that a table or index named 'zName' does not already exist
81147 ** in database iDb. If so, this is an error.
81149 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
81150 sqlite3ErrorMsg(pParse,
81151 "there is already another table or index with this name: %s", zName);
81152 goto exit_rename_table;
81155 /* Make sure it is not a system table being altered, or a reserved name
81156 ** that the table is being renamed to.
81158 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
81159 goto exit_rename_table;
81161 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
81162 exit_rename_table;
81165 #ifndef SQLITE_OMIT_VIEW
81166 if( pTab->pSelect ){
81167 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
81168 goto exit_rename_table;
81170 #endif
81172 #ifndef SQLITE_OMIT_AUTHORIZATION
81173 /* Invoke the authorization callback. */
81174 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
81175 goto exit_rename_table;
81177 #endif
81179 #ifndef SQLITE_OMIT_VIRTUALTABLE
81180 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
81181 goto exit_rename_table;
81183 if( IsVirtual(pTab) ){
81184 pVTab = sqlite3GetVTable(db, pTab);
81185 if( pVTab->pVtab->pModule->xRename==0 ){
81186 pVTab = 0;
81189 #endif
81191 /* Begin a transaction and code the VerifyCookie for database iDb.
81192 ** Then modify the schema cookie (since the ALTER TABLE modifies the
81193 ** schema). Open a statement transaction if the table is a virtual
81194 ** table.
81196 v = sqlite3GetVdbe(pParse);
81197 if( v==0 ){
81198 goto exit_rename_table;
81200 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
81201 sqlite3ChangeCookie(pParse, iDb);
81203 /* If this is a virtual table, invoke the xRename() function if
81204 ** one is defined. The xRename() callback will modify the names
81205 ** of any resources used by the v-table implementation (including other
81206 ** SQLite tables) that are identified by the name of the virtual table.
81208 #ifndef SQLITE_OMIT_VIRTUALTABLE
81209 if( pVTab ){
81210 int i = ++pParse->nMem;
81211 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
81212 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
81213 sqlite3MayAbort(pParse);
81215 #endif
81217 /* figure out how many UTF-8 characters are in zName */
81218 zTabName = pTab->zName;
81219 nTabName = sqlite3Utf8CharLen(zTabName, -1);
81221 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
81222 if( db->flags&SQLITE_ForeignKeys ){
81223 /* If foreign-key support is enabled, rewrite the CREATE TABLE
81224 ** statements corresponding to all child tables of foreign key constraints
81225 ** for which the renamed table is the parent table. */
81226 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
81227 sqlite3NestedParse(pParse,
81228 "UPDATE \"%w\".%s SET "
81229 "sql = sqlite_rename_parent(sql, %Q, %Q) "
81230 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
81231 sqlite3DbFree(db, zWhere);
81234 #endif
81236 /* Modify the sqlite_master table to use the new table name. */
81237 sqlite3NestedParse(pParse,
81238 "UPDATE %Q.%s SET "
81239 #ifdef SQLITE_OMIT_TRIGGER
81240 "sql = sqlite_rename_table(sql, %Q), "
81241 #else
81242 "sql = CASE "
81243 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
81244 "ELSE sqlite_rename_table(sql, %Q) END, "
81245 #endif
81246 "tbl_name = %Q, "
81247 "name = CASE "
81248 "WHEN type='table' THEN %Q "
81249 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
81250 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
81251 "ELSE name END "
81252 "WHERE tbl_name=%Q COLLATE nocase AND "
81253 "(type='table' OR type='index' OR type='trigger');",
81254 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
81255 #ifndef SQLITE_OMIT_TRIGGER
81256 zName,
81257 #endif
81258 zName, nTabName, zTabName
81261 #ifndef SQLITE_OMIT_AUTOINCREMENT
81262 /* If the sqlite_sequence table exists in this database, then update
81263 ** it with the new table name.
81265 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
81266 sqlite3NestedParse(pParse,
81267 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
81268 zDb, zName, pTab->zName);
81270 #endif
81272 #ifndef SQLITE_OMIT_TRIGGER
81273 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
81274 ** table. Don't do this if the table being ALTERed is itself located in
81275 ** the temp database.
81277 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
81278 sqlite3NestedParse(pParse,
81279 "UPDATE sqlite_temp_master SET "
81280 "sql = sqlite_rename_trigger(sql, %Q), "
81281 "tbl_name = %Q "
81282 "WHERE %s;", zName, zName, zWhere);
81283 sqlite3DbFree(db, zWhere);
81285 #endif
81287 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
81288 if( db->flags&SQLITE_ForeignKeys ){
81289 FKey *p;
81290 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
81291 Table *pFrom = p->pFrom;
81292 if( pFrom!=pTab ){
81293 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
81297 #endif
81299 /* Drop and reload the internal table schema. */
81300 reloadTableSchema(pParse, pTab, zName);
81302 exit_rename_table:
81303 sqlite3SrcListDelete(db, pSrc);
81304 sqlite3DbFree(db, zName);
81305 db->flags = savedDbFlags;
81310 ** Generate code to make sure the file format number is at least minFormat.
81311 ** The generated code will increase the file format number if necessary.
81313 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
81314 Vdbe *v;
81315 v = sqlite3GetVdbe(pParse);
81316 /* The VDBE should have been allocated before this routine is called.
81317 ** If that allocation failed, we would have quit before reaching this
81318 ** point */
81319 if( ALWAYS(v) ){
81320 int r1 = sqlite3GetTempReg(pParse);
81321 int r2 = sqlite3GetTempReg(pParse);
81322 int j1;
81323 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
81324 sqlite3VdbeUsesBtree(v, iDb);
81325 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
81326 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
81327 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
81328 sqlite3VdbeJumpHere(v, j1);
81329 sqlite3ReleaseTempReg(pParse, r1);
81330 sqlite3ReleaseTempReg(pParse, r2);
81335 ** This function is called after an "ALTER TABLE ... ADD" statement
81336 ** has been parsed. Argument pColDef contains the text of the new
81337 ** column definition.
81339 ** The Table structure pParse->pNewTable was extended to include
81340 ** the new column during parsing.
81342 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
81343 Table *pNew; /* Copy of pParse->pNewTable */
81344 Table *pTab; /* Table being altered */
81345 int iDb; /* Database number */
81346 const char *zDb; /* Database name */
81347 const char *zTab; /* Table name */
81348 char *zCol; /* Null-terminated column definition */
81349 Column *pCol; /* The new column */
81350 Expr *pDflt; /* Default value for the new column */
81351 sqlite3 *db; /* The database connection; */
81353 db = pParse->db;
81354 if( pParse->nErr || db->mallocFailed ) return;
81355 pNew = pParse->pNewTable;
81356 assert( pNew );
81358 assert( sqlite3BtreeHoldsAllMutexes(db) );
81359 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
81360 zDb = db->aDb[iDb].zName;
81361 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
81362 pCol = &pNew->aCol[pNew->nCol-1];
81363 pDflt = pCol->pDflt;
81364 pTab = sqlite3FindTable(db, zTab, zDb);
81365 assert( pTab );
81367 #ifndef SQLITE_OMIT_AUTHORIZATION
81368 /* Invoke the authorization callback. */
81369 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
81370 return;
81372 #endif
81374 /* If the default value for the new column was specified with a
81375 ** literal NULL, then set pDflt to 0. This simplifies checking
81376 ** for an SQL NULL default below.
81378 if( pDflt && pDflt->op==TK_NULL ){
81379 pDflt = 0;
81382 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
81383 ** If there is a NOT NULL constraint, then the default value for the
81384 ** column must not be NULL.
81386 if( pCol->colFlags & COLFLAG_PRIMKEY ){
81387 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
81388 return;
81390 if( pNew->pIndex ){
81391 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
81392 return;
81394 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
81395 sqlite3ErrorMsg(pParse,
81396 "Cannot add a REFERENCES column with non-NULL default value");
81397 return;
81399 if( pCol->notNull && !pDflt ){
81400 sqlite3ErrorMsg(pParse,
81401 "Cannot add a NOT NULL column with default value NULL");
81402 return;
81405 /* Ensure the default expression is something that sqlite3ValueFromExpr()
81406 ** can handle (i.e. not CURRENT_TIME etc.)
81408 if( pDflt ){
81409 sqlite3_value *pVal = 0;
81410 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
81411 db->mallocFailed = 1;
81412 return;
81414 if( !pVal ){
81415 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
81416 return;
81418 sqlite3ValueFree(pVal);
81421 /* Modify the CREATE TABLE statement. */
81422 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
81423 if( zCol ){
81424 char *zEnd = &zCol[pColDef->n-1];
81425 int savedDbFlags = db->flags;
81426 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
81427 *zEnd-- = '\0';
81429 db->flags |= SQLITE_PreferBuiltin;
81430 sqlite3NestedParse(pParse,
81431 "UPDATE \"%w\".%s SET "
81432 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
81433 "WHERE type = 'table' AND name = %Q",
81434 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
81435 zTab
81437 sqlite3DbFree(db, zCol);
81438 db->flags = savedDbFlags;
81441 /* If the default value of the new column is NULL, then set the file
81442 ** format to 2. If the default value of the new column is not NULL,
81443 ** the file format becomes 3.
81445 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
81447 /* Reload the schema of the modified table. */
81448 reloadTableSchema(pParse, pTab, pTab->zName);
81452 ** This function is called by the parser after the table-name in
81453 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
81454 ** pSrc is the full-name of the table being altered.
81456 ** This routine makes a (partial) copy of the Table structure
81457 ** for the table being altered and sets Parse.pNewTable to point
81458 ** to it. Routines called by the parser as the column definition
81459 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
81460 ** the copy. The copy of the Table structure is deleted by tokenize.c
81461 ** after parsing is finished.
81463 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
81464 ** coding the "ALTER TABLE ... ADD" statement.
81466 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
81467 Table *pNew;
81468 Table *pTab;
81469 Vdbe *v;
81470 int iDb;
81471 int i;
81472 int nAlloc;
81473 sqlite3 *db = pParse->db;
81475 /* Look up the table being altered. */
81476 assert( pParse->pNewTable==0 );
81477 assert( sqlite3BtreeHoldsAllMutexes(db) );
81478 if( db->mallocFailed ) goto exit_begin_add_column;
81479 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
81480 if( !pTab ) goto exit_begin_add_column;
81482 #ifndef SQLITE_OMIT_VIRTUALTABLE
81483 if( IsVirtual(pTab) ){
81484 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
81485 goto exit_begin_add_column;
81487 #endif
81489 /* Make sure this is not an attempt to ALTER a view. */
81490 if( pTab->pSelect ){
81491 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
81492 goto exit_begin_add_column;
81494 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
81495 goto exit_begin_add_column;
81498 assert( pTab->addColOffset>0 );
81499 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81501 /* Put a copy of the Table struct in Parse.pNewTable for the
81502 ** sqlite3AddColumn() function and friends to modify. But modify
81503 ** the name by adding an "sqlite_altertab_" prefix. By adding this
81504 ** prefix, we insure that the name will not collide with an existing
81505 ** table because user table are not allowed to have the "sqlite_"
81506 ** prefix on their name.
81508 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
81509 if( !pNew ) goto exit_begin_add_column;
81510 pParse->pNewTable = pNew;
81511 pNew->nRef = 1;
81512 pNew->nCol = pTab->nCol;
81513 assert( pNew->nCol>0 );
81514 nAlloc = (((pNew->nCol-1)/8)*8)+8;
81515 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
81516 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
81517 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
81518 if( !pNew->aCol || !pNew->zName ){
81519 db->mallocFailed = 1;
81520 goto exit_begin_add_column;
81522 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
81523 for(i=0; i<pNew->nCol; i++){
81524 Column *pCol = &pNew->aCol[i];
81525 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
81526 pCol->zColl = 0;
81527 pCol->zType = 0;
81528 pCol->pDflt = 0;
81529 pCol->zDflt = 0;
81531 pNew->pSchema = db->aDb[iDb].pSchema;
81532 pNew->addColOffset = pTab->addColOffset;
81533 pNew->nRef = 1;
81535 /* Begin a transaction and increment the schema cookie. */
81536 sqlite3BeginWriteOperation(pParse, 0, iDb);
81537 v = sqlite3GetVdbe(pParse);
81538 if( !v ) goto exit_begin_add_column;
81539 sqlite3ChangeCookie(pParse, iDb);
81541 exit_begin_add_column:
81542 sqlite3SrcListDelete(db, pSrc);
81543 return;
81545 #endif /* SQLITE_ALTER_TABLE */
81547 /************** End of alter.c ***********************************************/
81548 /************** Begin file analyze.c *****************************************/
81550 ** 2005-07-08
81552 ** The author disclaims copyright to this source code. In place of
81553 ** a legal notice, here is a blessing:
81555 ** May you do good and not evil.
81556 ** May you find forgiveness for yourself and forgive others.
81557 ** May you share freely, never taking more than you give.
81559 *************************************************************************
81560 ** This file contains code associated with the ANALYZE command.
81562 ** The ANALYZE command gather statistics about the content of tables
81563 ** and indices. These statistics are made available to the query planner
81564 ** to help it make better decisions about how to perform queries.
81566 ** The following system tables are or have been supported:
81568 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
81569 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
81570 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
81571 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
81573 ** Additional tables might be added in future releases of SQLite.
81574 ** The sqlite_stat2 table is not created or used unless the SQLite version
81575 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
81576 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
81577 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
81578 ** created and used by SQLite versions 3.7.9 and later and with
81579 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
81580 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
81581 ** version of sqlite_stat3 and is only available when compiled with
81582 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
81583 ** not possible to enable both STAT3 and STAT4 at the same time. If they
81584 ** are both enabled, then STAT4 takes precedence.
81586 ** For most applications, sqlite_stat1 provides all the statisics required
81587 ** for the query planner to make good choices.
81589 ** Format of sqlite_stat1:
81591 ** There is normally one row per index, with the index identified by the
81592 ** name in the idx column. The tbl column is the name of the table to
81593 ** which the index belongs. In each such row, the stat column will be
81594 ** a string consisting of a list of integers. The first integer in this
81595 ** list is the number of rows in the index. (This is the same as the
81596 ** number of rows in the table, except for partial indices.) The second
81597 ** integer is the average number of rows in the index that have the same
81598 ** value in the first column of the index. The third integer is the average
81599 ** number of rows in the index that have the same value for the first two
81600 ** columns. The N-th integer (for N>1) is the average number of rows in
81601 ** the index which have the same value for the first N-1 columns. For
81602 ** a K-column index, there will be K+1 integers in the stat column. If
81603 ** the index is unique, then the last integer will be 1.
81605 ** The list of integers in the stat column can optionally be followed
81606 ** by the keyword "unordered". The "unordered" keyword, if it is present,
81607 ** must be separated from the last integer by a single space. If the
81608 ** "unordered" keyword is present, then the query planner assumes that
81609 ** the index is unordered and will not use the index for a range query.
81611 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
81612 ** column contains a single integer which is the (estimated) number of
81613 ** rows in the table identified by sqlite_stat1.tbl.
81615 ** Format of sqlite_stat2:
81617 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
81618 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
81619 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
81620 ** about the distribution of keys within an index. The index is identified by
81621 ** the "idx" column and the "tbl" column is the name of the table to which
81622 ** the index belongs. There are usually 10 rows in the sqlite_stat2
81623 ** table for each index.
81625 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
81626 ** inclusive are samples of the left-most key value in the index taken at
81627 ** evenly spaced points along the index. Let the number of samples be S
81628 ** (10 in the standard build) and let C be the number of rows in the index.
81629 ** Then the sampled rows are given by:
81631 ** rownumber = (i*C*2 + C)/(S*2)
81633 ** For i between 0 and S-1. Conceptually, the index space is divided into
81634 ** S uniform buckets and the samples are the middle row from each bucket.
81636 ** The format for sqlite_stat2 is recorded here for legacy reference. This
81637 ** version of SQLite does not support sqlite_stat2. It neither reads nor
81638 ** writes the sqlite_stat2 table. This version of SQLite only supports
81639 ** sqlite_stat3.
81641 ** Format for sqlite_stat3:
81643 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
81644 ** sqlite_stat4 format will be described first. Further information
81645 ** about sqlite_stat3 follows the sqlite_stat4 description.
81647 ** Format for sqlite_stat4:
81649 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
81650 ** to aid the query planner in choosing good indices based on the values
81651 ** that indexed columns are compared against in the WHERE clauses of
81652 ** queries.
81654 ** The sqlite_stat4 table contains multiple entries for each index.
81655 ** The idx column names the index and the tbl column is the table of the
81656 ** index. If the idx and tbl columns are the same, then the sample is
81657 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
81658 ** binary encoding of a key from the index. The nEq column is a
81659 ** list of integers. The first integer is the approximate number
81660 ** of entries in the index whose left-most column exactly matches
81661 ** the left-most column of the sample. The second integer in nEq
81662 ** is the approximate number of entries in the index where the
81663 ** first two columns match the first two columns of the sample.
81664 ** And so forth. nLt is another list of integers that show the approximate
81665 ** number of entries that are strictly less than the sample. The first
81666 ** integer in nLt contains the number of entries in the index where the
81667 ** left-most column is less than the left-most column of the sample.
81668 ** The K-th integer in the nLt entry is the number of index entries
81669 ** where the first K columns are less than the first K columns of the
81670 ** sample. The nDLt column is like nLt except that it contains the
81671 ** number of distinct entries in the index that are less than the
81672 ** sample.
81674 ** There can be an arbitrary number of sqlite_stat4 entries per index.
81675 ** The ANALYZE command will typically generate sqlite_stat4 tables
81676 ** that contain between 10 and 40 samples which are distributed across
81677 ** the key space, though not uniformly, and which include samples with
81678 ** large nEq values.
81680 ** Format for sqlite_stat3 redux:
81682 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
81683 ** looks at the left-most column of the index. The sqlite_stat3.sample
81684 ** column contains the actual value of the left-most column instead
81685 ** of a blob encoding of the complete index key as is found in
81686 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
81687 ** all contain just a single integer which is the same as the first
81688 ** integer in the equivalent columns in sqlite_stat4.
81690 #ifndef SQLITE_OMIT_ANALYZE
81692 #if defined(SQLITE_ENABLE_STAT4)
81693 # define IsStat4 1
81694 # define IsStat3 0
81695 #elif defined(SQLITE_ENABLE_STAT3)
81696 # define IsStat4 0
81697 # define IsStat3 1
81698 #else
81699 # define IsStat4 0
81700 # define IsStat3 0
81701 # undef SQLITE_STAT4_SAMPLES
81702 # define SQLITE_STAT4_SAMPLES 1
81703 #endif
81704 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
81707 ** This routine generates code that opens the sqlite_statN tables.
81708 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
81709 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
81710 ** appropriate compile-time options are provided.
81712 ** If the sqlite_statN tables do not previously exist, it is created.
81714 ** Argument zWhere may be a pointer to a buffer containing a table name,
81715 ** or it may be a NULL pointer. If it is not NULL, then all entries in
81716 ** the sqlite_statN tables associated with the named table are deleted.
81717 ** If zWhere==0, then code is generated to delete all stat table entries.
81719 static void openStatTable(
81720 Parse *pParse, /* Parsing context */
81721 int iDb, /* The database we are looking in */
81722 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
81723 const char *zWhere, /* Delete entries for this table or index */
81724 const char *zWhereType /* Either "tbl" or "idx" */
81726 static const struct {
81727 const char *zName;
81728 const char *zCols;
81729 } aTable[] = {
81730 { "sqlite_stat1", "tbl,idx,stat" },
81731 #if defined(SQLITE_ENABLE_STAT4)
81732 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
81733 { "sqlite_stat3", 0 },
81734 #elif defined(SQLITE_ENABLE_STAT3)
81735 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
81736 { "sqlite_stat4", 0 },
81737 #else
81738 { "sqlite_stat3", 0 },
81739 { "sqlite_stat4", 0 },
81740 #endif
81742 int i;
81743 sqlite3 *db = pParse->db;
81744 Db *pDb;
81745 Vdbe *v = sqlite3GetVdbe(pParse);
81746 int aRoot[ArraySize(aTable)];
81747 u8 aCreateTbl[ArraySize(aTable)];
81749 if( v==0 ) return;
81750 assert( sqlite3BtreeHoldsAllMutexes(db) );
81751 assert( sqlite3VdbeDb(v)==db );
81752 pDb = &db->aDb[iDb];
81754 /* Create new statistic tables if they do not exist, or clear them
81755 ** if they do already exist.
81757 for(i=0; i<ArraySize(aTable); i++){
81758 const char *zTab = aTable[i].zName;
81759 Table *pStat;
81760 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
81761 if( aTable[i].zCols ){
81762 /* The sqlite_statN table does not exist. Create it. Note that a
81763 ** side-effect of the CREATE TABLE statement is to leave the rootpage
81764 ** of the new table in register pParse->regRoot. This is important
81765 ** because the OpenWrite opcode below will be needing it. */
81766 sqlite3NestedParse(pParse,
81767 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
81769 aRoot[i] = pParse->regRoot;
81770 aCreateTbl[i] = OPFLAG_P2ISREG;
81772 }else{
81773 /* The table already exists. If zWhere is not NULL, delete all entries
81774 ** associated with the table zWhere. If zWhere is NULL, delete the
81775 ** entire contents of the table. */
81776 aRoot[i] = pStat->tnum;
81777 aCreateTbl[i] = 0;
81778 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
81779 if( zWhere ){
81780 sqlite3NestedParse(pParse,
81781 "DELETE FROM %Q.%s WHERE %s=%Q",
81782 pDb->zName, zTab, zWhereType, zWhere
81784 }else{
81785 /* The sqlite_stat[134] table already exists. Delete all rows. */
81786 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
81791 /* Open the sqlite_stat[134] tables for writing. */
81792 for(i=0; aTable[i].zCols; i++){
81793 assert( i<ArraySize(aTable) );
81794 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
81795 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
81800 ** Recommended number of samples for sqlite_stat4
81802 #ifndef SQLITE_STAT4_SAMPLES
81803 # define SQLITE_STAT4_SAMPLES 24
81804 #endif
81807 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
81808 ** share an instance of the following structure to hold their state
81809 ** information.
81811 typedef struct Stat4Accum Stat4Accum;
81812 typedef struct Stat4Sample Stat4Sample;
81813 struct Stat4Sample {
81814 tRowcnt *anEq; /* sqlite_stat4.nEq */
81815 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
81816 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81817 tRowcnt *anLt; /* sqlite_stat4.nLt */
81818 union {
81819 i64 iRowid; /* Rowid in main table of the key */
81820 u8 *aRowid; /* Key for WITHOUT ROWID tables */
81821 } u;
81822 u32 nRowid; /* Sizeof aRowid[] */
81823 u8 isPSample; /* True if a periodic sample */
81824 int iCol; /* If !isPSample, the reason for inclusion */
81825 u32 iHash; /* Tiebreaker hash */
81826 #endif
81828 struct Stat4Accum {
81829 tRowcnt nRow; /* Number of rows in the entire table */
81830 tRowcnt nPSample; /* How often to do a periodic sample */
81831 int nCol; /* Number of columns in index + rowid */
81832 int mxSample; /* Maximum number of samples to accumulate */
81833 Stat4Sample current; /* Current row as a Stat4Sample */
81834 u32 iPrn; /* Pseudo-random number used for sampling */
81835 Stat4Sample *aBest; /* Array of nCol best samples */
81836 int iMin; /* Index in a[] of entry with minimum score */
81837 int nSample; /* Current number of samples */
81838 int iGet; /* Index of current sample accessed by stat_get() */
81839 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
81840 sqlite3 *db; /* Database connection, for malloc() */
81843 /* Reclaim memory used by a Stat4Sample
81845 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81846 static void sampleClear(sqlite3 *db, Stat4Sample *p){
81847 assert( db!=0 );
81848 if( p->nRowid ){
81849 sqlite3DbFree(db, p->u.aRowid);
81850 p->nRowid = 0;
81853 #endif
81855 /* Initialize the BLOB value of a ROWID
81857 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81858 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
81859 assert( db!=0 );
81860 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
81861 p->u.aRowid = sqlite3DbMallocRaw(db, n);
81862 if( p->u.aRowid ){
81863 p->nRowid = n;
81864 memcpy(p->u.aRowid, pData, n);
81865 }else{
81866 p->nRowid = 0;
81869 #endif
81871 /* Initialize the INTEGER value of a ROWID.
81873 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81874 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
81875 assert( db!=0 );
81876 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
81877 p->nRowid = 0;
81878 p->u.iRowid = iRowid;
81880 #endif
81884 ** Copy the contents of object (*pFrom) into (*pTo).
81886 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81887 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
81888 pTo->isPSample = pFrom->isPSample;
81889 pTo->iCol = pFrom->iCol;
81890 pTo->iHash = pFrom->iHash;
81891 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
81892 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
81893 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
81894 if( pFrom->nRowid ){
81895 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
81896 }else{
81897 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
81900 #endif
81903 ** Reclaim all memory of a Stat4Accum structure.
81905 static void stat4Destructor(void *pOld){
81906 Stat4Accum *p = (Stat4Accum*)pOld;
81907 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81908 int i;
81909 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
81910 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
81911 sampleClear(p->db, &p->current);
81912 #endif
81913 sqlite3DbFree(p->db, p);
81917 ** Implementation of the stat_init(N,C) SQL function. The two parameters
81918 ** are the number of rows in the table or index (C) and the number of columns
81919 ** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
81921 ** This routine allocates the Stat4Accum object in heap memory. The return
81922 ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
81923 ** the size of the blob is sizeof(void*) bytes).
81925 static void statInit(
81926 sqlite3_context *context,
81927 int argc,
81928 sqlite3_value **argv
81930 Stat4Accum *p;
81931 int nCol; /* Number of columns in index being sampled */
81932 int nColUp; /* nCol rounded up for alignment */
81933 int n; /* Bytes of space to allocate */
81934 sqlite3 *db; /* Database connection */
81935 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81936 int mxSample = SQLITE_STAT4_SAMPLES;
81937 #endif
81939 /* Decode the three function arguments */
81940 UNUSED_PARAMETER(argc);
81941 nCol = sqlite3_value_int(argv[0]);
81942 assert( nCol>1 ); /* >1 because it includes the rowid column */
81943 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
81945 /* Allocate the space required for the Stat4Accum object */
81946 n = sizeof(*p)
81947 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
81948 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
81949 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81950 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
81951 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
81952 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
81953 #endif
81955 db = sqlite3_context_db_handle(context);
81956 p = sqlite3DbMallocZero(db, n);
81957 if( p==0 ){
81958 sqlite3_result_error_nomem(context);
81959 return;
81962 p->db = db;
81963 p->nRow = 0;
81964 p->nCol = nCol;
81965 p->current.anDLt = (tRowcnt*)&p[1];
81966 p->current.anEq = &p->current.anDLt[nColUp];
81968 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
81970 u8 *pSpace; /* Allocated space not yet assigned */
81971 int i; /* Used to iterate through p->aSample[] */
81973 p->iGet = -1;
81974 p->mxSample = mxSample;
81975 p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
81976 p->current.anLt = &p->current.anEq[nColUp];
81977 p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
81979 /* Set up the Stat4Accum.a[] and aBest[] arrays */
81980 p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
81981 p->aBest = &p->a[mxSample];
81982 pSpace = (u8*)(&p->a[mxSample+nCol]);
81983 for(i=0; i<(mxSample+nCol); i++){
81984 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
81985 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
81986 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
81988 assert( (pSpace - (u8*)p)==n );
81990 for(i=0; i<nCol; i++){
81991 p->aBest[i].iCol = i;
81994 #endif
81996 /* Return a pointer to the allocated object to the caller */
81997 sqlite3_result_blob(context, p, sizeof(p), stat4Destructor);
81999 static const FuncDef statInitFuncdef = {
82000 1+IsStat34, /* nArg */
82001 SQLITE_UTF8, /* funcFlags */
82002 0, /* pUserData */
82003 0, /* pNext */
82004 statInit, /* xFunc */
82005 0, /* xStep */
82006 0, /* xFinalize */
82007 "stat_init", /* zName */
82008 0, /* pHash */
82009 0 /* pDestructor */
82012 #ifdef SQLITE_ENABLE_STAT4
82014 ** pNew and pOld are both candidate non-periodic samples selected for
82015 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
82016 ** considering only any trailing columns and the sample hash value, this
82017 ** function returns true if sample pNew is to be preferred over pOld.
82018 ** In other words, if we assume that the cardinalities of the selected
82019 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
82021 ** This function assumes that for each argument sample, the contents of
82022 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
82024 static int sampleIsBetterPost(
82025 Stat4Accum *pAccum,
82026 Stat4Sample *pNew,
82027 Stat4Sample *pOld
82029 int nCol = pAccum->nCol;
82030 int i;
82031 assert( pNew->iCol==pOld->iCol );
82032 for(i=pNew->iCol+1; i<nCol; i++){
82033 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
82034 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
82036 if( pNew->iHash>pOld->iHash ) return 1;
82037 return 0;
82039 #endif
82041 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82043 ** Return true if pNew is to be preferred over pOld.
82045 ** This function assumes that for each argument sample, the contents of
82046 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
82048 static int sampleIsBetter(
82049 Stat4Accum *pAccum,
82050 Stat4Sample *pNew,
82051 Stat4Sample *pOld
82053 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
82054 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
82056 assert( pOld->isPSample==0 && pNew->isPSample==0 );
82057 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
82059 if( (nEqNew>nEqOld) ) return 1;
82060 #ifdef SQLITE_ENABLE_STAT4
82061 if( nEqNew==nEqOld ){
82062 if( pNew->iCol<pOld->iCol ) return 1;
82063 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
82065 return 0;
82066 #else
82067 return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
82068 #endif
82072 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
82073 ** remove the least desirable sample from p->a[] to make room.
82075 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
82076 Stat4Sample *pSample = 0;
82077 int i;
82079 assert( IsStat4 || nEqZero==0 );
82081 #ifdef SQLITE_ENABLE_STAT4
82082 if( pNew->isPSample==0 ){
82083 Stat4Sample *pUpgrade = 0;
82084 assert( pNew->anEq[pNew->iCol]>0 );
82086 /* This sample is being added because the prefix that ends in column
82087 ** iCol occurs many times in the table. However, if we have already
82088 ** added a sample that shares this prefix, there is no need to add
82089 ** this one. Instead, upgrade the priority of the highest priority
82090 ** existing sample that shares this prefix. */
82091 for(i=p->nSample-1; i>=0; i--){
82092 Stat4Sample *pOld = &p->a[i];
82093 if( pOld->anEq[pNew->iCol]==0 ){
82094 if( pOld->isPSample ) return;
82095 assert( pOld->iCol>pNew->iCol );
82096 assert( sampleIsBetter(p, pNew, pOld) );
82097 if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
82098 pUpgrade = pOld;
82102 if( pUpgrade ){
82103 pUpgrade->iCol = pNew->iCol;
82104 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
82105 goto find_new_min;
82108 #endif
82110 /* If necessary, remove sample iMin to make room for the new sample. */
82111 if( p->nSample>=p->mxSample ){
82112 Stat4Sample *pMin = &p->a[p->iMin];
82113 tRowcnt *anEq = pMin->anEq;
82114 tRowcnt *anLt = pMin->anLt;
82115 tRowcnt *anDLt = pMin->anDLt;
82116 sampleClear(p->db, pMin);
82117 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
82118 pSample = &p->a[p->nSample-1];
82119 pSample->nRowid = 0;
82120 pSample->anEq = anEq;
82121 pSample->anDLt = anDLt;
82122 pSample->anLt = anLt;
82123 p->nSample = p->mxSample-1;
82126 /* The "rows less-than" for the rowid column must be greater than that
82127 ** for the last sample in the p->a[] array. Otherwise, the samples would
82128 ** be out of order. */
82129 #ifdef SQLITE_ENABLE_STAT4
82130 assert( p->nSample==0
82131 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
82132 #endif
82134 /* Insert the new sample */
82135 pSample = &p->a[p->nSample];
82136 sampleCopy(p, pSample, pNew);
82137 p->nSample++;
82139 /* Zero the first nEqZero entries in the anEq[] array. */
82140 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
82142 #ifdef SQLITE_ENABLE_STAT4
82143 find_new_min:
82144 #endif
82145 if( p->nSample>=p->mxSample ){
82146 int iMin = -1;
82147 for(i=0; i<p->mxSample; i++){
82148 if( p->a[i].isPSample ) continue;
82149 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
82150 iMin = i;
82153 assert( iMin>=0 );
82154 p->iMin = iMin;
82157 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
82160 ** Field iChng of the index being scanned has changed. So at this point
82161 ** p->current contains a sample that reflects the previous row of the
82162 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
82163 ** correct at this point.
82165 static void samplePushPrevious(Stat4Accum *p, int iChng){
82166 #ifdef SQLITE_ENABLE_STAT4
82167 int i;
82169 /* Check if any samples from the aBest[] array should be pushed
82170 ** into IndexSample.a[] at this point. */
82171 for(i=(p->nCol-2); i>=iChng; i--){
82172 Stat4Sample *pBest = &p->aBest[i];
82173 pBest->anEq[i] = p->current.anEq[i];
82174 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
82175 sampleInsert(p, pBest, i);
82179 /* Update the anEq[] fields of any samples already collected. */
82180 for(i=p->nSample-1; i>=0; i--){
82181 int j;
82182 for(j=iChng; j<p->nCol; j++){
82183 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
82186 #endif
82188 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
82189 if( iChng==0 ){
82190 tRowcnt nLt = p->current.anLt[0];
82191 tRowcnt nEq = p->current.anEq[0];
82193 /* Check if this is to be a periodic sample. If so, add it. */
82194 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
82195 p->current.isPSample = 1;
82196 sampleInsert(p, &p->current, 0);
82197 p->current.isPSample = 0;
82198 }else
82200 /* Or if it is a non-periodic sample. Add it in this case too. */
82201 if( p->nSample<p->mxSample
82202 || sampleIsBetter(p, &p->current, &p->a[p->iMin])
82204 sampleInsert(p, &p->current, 0);
82207 #endif
82209 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
82210 UNUSED_PARAMETER( p );
82211 UNUSED_PARAMETER( iChng );
82212 #endif
82216 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
82217 ** Arguments:
82219 ** P Pointer to the Stat4Accum object created by stat_init()
82220 ** C Index of left-most column to differ from previous row
82221 ** R Rowid for the current row. Might be a key record for
82222 ** WITHOUT ROWID tables.
82224 ** The SQL function always returns NULL.
82226 ** The R parameter is only used for STAT3 and STAT4
82228 static void statPush(
82229 sqlite3_context *context,
82230 int argc,
82231 sqlite3_value **argv
82233 int i;
82235 /* The three function arguments */
82236 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
82237 int iChng = sqlite3_value_int(argv[1]);
82239 UNUSED_PARAMETER( argc );
82240 UNUSED_PARAMETER( context );
82241 assert( p->nCol>1 ); /* Includes rowid field */
82242 assert( iChng<p->nCol );
82244 if( p->nRow==0 ){
82245 /* This is the first call to this function. Do initialization. */
82246 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
82247 }else{
82248 /* Second and subsequent calls get processed here */
82249 samplePushPrevious(p, iChng);
82251 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
82252 ** to the current row of the index. */
82253 for(i=0; i<iChng; i++){
82254 p->current.anEq[i]++;
82256 for(i=iChng; i<p->nCol; i++){
82257 p->current.anDLt[i]++;
82258 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82259 p->current.anLt[i] += p->current.anEq[i];
82260 #endif
82261 p->current.anEq[i] = 1;
82264 p->nRow++;
82265 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82266 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
82267 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
82268 }else{
82269 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
82270 sqlite3_value_blob(argv[2]));
82272 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
82273 #endif
82275 #ifdef SQLITE_ENABLE_STAT4
82277 tRowcnt nLt = p->current.anLt[p->nCol-1];
82279 /* Check if this is to be a periodic sample. If so, add it. */
82280 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
82281 p->current.isPSample = 1;
82282 p->current.iCol = 0;
82283 sampleInsert(p, &p->current, p->nCol-1);
82284 p->current.isPSample = 0;
82287 /* Update the aBest[] array. */
82288 for(i=0; i<(p->nCol-1); i++){
82289 p->current.iCol = i;
82290 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
82291 sampleCopy(p, &p->aBest[i], &p->current);
82295 #endif
82297 static const FuncDef statPushFuncdef = {
82298 2+IsStat34, /* nArg */
82299 SQLITE_UTF8, /* funcFlags */
82300 0, /* pUserData */
82301 0, /* pNext */
82302 statPush, /* xFunc */
82303 0, /* xStep */
82304 0, /* xFinalize */
82305 "stat_push", /* zName */
82306 0, /* pHash */
82307 0 /* pDestructor */
82310 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
82311 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
82312 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
82313 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
82314 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
82317 ** Implementation of the stat_get(P,J) SQL function. This routine is
82318 ** used to query the results. Content is returned for parameter J
82319 ** which is one of the STAT_GET_xxxx values defined above.
82321 ** If neither STAT3 nor STAT4 are enabled, then J is always
82322 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
82323 ** a one-parameter function, stat_get(P), that always returns the
82324 ** stat1 table entry information.
82326 static void statGet(
82327 sqlite3_context *context,
82328 int argc,
82329 sqlite3_value **argv
82331 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
82332 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82333 /* STAT3 and STAT4 have a parameter on this routine. */
82334 int eCall = sqlite3_value_int(argv[1]);
82335 assert( argc==2 );
82336 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
82337 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
82338 || eCall==STAT_GET_NDLT
82340 if( eCall==STAT_GET_STAT1 )
82341 #else
82342 assert( argc==1 );
82343 #endif
82345 /* Return the value to store in the "stat" column of the sqlite_stat1
82346 ** table for this index.
82348 ** The value is a string composed of a list of integers describing
82349 ** the index. The first integer in the list is the total number of
82350 ** entries in the index. There is one additional integer in the list
82351 ** for each indexed column. This additional integer is an estimate of
82352 ** the number of rows matched by a stabbing query on the index using
82353 ** a key with the corresponding number of fields. In other words,
82354 ** if the index is on columns (a,b) and the sqlite_stat1 value is
82355 ** "100 10 2", then SQLite estimates that:
82357 ** * the index contains 100 rows,
82358 ** * "WHERE a=?" matches 10 rows, and
82359 ** * "WHERE a=? AND b=?" matches 2 rows.
82361 ** If D is the count of distinct values and K is the total number of
82362 ** rows, then each estimate is computed as:
82364 ** I = (K+D-1)/D
82366 char *z;
82367 int i;
82369 char *zRet = sqlite3MallocZero(p->nCol * 25);
82370 if( zRet==0 ){
82371 sqlite3_result_error_nomem(context);
82372 return;
82375 sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
82376 z = zRet + sqlite3Strlen30(zRet);
82377 for(i=0; i<(p->nCol-1); i++){
82378 u64 nDistinct = p->current.anDLt[i] + 1;
82379 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
82380 sqlite3_snprintf(24, z, " %llu", iVal);
82381 z += sqlite3Strlen30(z);
82382 assert( p->current.anEq[i] );
82384 assert( z[0]=='\0' && z>zRet );
82386 sqlite3_result_text(context, zRet, -1, sqlite3_free);
82388 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82389 else if( eCall==STAT_GET_ROWID ){
82390 if( p->iGet<0 ){
82391 samplePushPrevious(p, 0);
82392 p->iGet = 0;
82394 if( p->iGet<p->nSample ){
82395 Stat4Sample *pS = p->a + p->iGet;
82396 if( pS->nRowid==0 ){
82397 sqlite3_result_int64(context, pS->u.iRowid);
82398 }else{
82399 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
82400 SQLITE_TRANSIENT);
82403 }else{
82404 tRowcnt *aCnt = 0;
82406 assert( p->iGet<p->nSample );
82407 switch( eCall ){
82408 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
82409 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
82410 default: {
82411 aCnt = p->a[p->iGet].anDLt;
82412 p->iGet++;
82413 break;
82417 if( IsStat3 ){
82418 sqlite3_result_int64(context, (i64)aCnt[0]);
82419 }else{
82420 char *zRet = sqlite3MallocZero(p->nCol * 25);
82421 if( zRet==0 ){
82422 sqlite3_result_error_nomem(context);
82423 }else{
82424 int i;
82425 char *z = zRet;
82426 for(i=0; i<p->nCol; i++){
82427 sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
82428 z += sqlite3Strlen30(z);
82430 assert( z[0]=='\0' && z>zRet );
82431 z[-1] = '\0';
82432 sqlite3_result_text(context, zRet, -1, sqlite3_free);
82436 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
82437 #ifndef SQLITE_DEBUG
82438 UNUSED_PARAMETER( argc );
82439 #endif
82441 static const FuncDef statGetFuncdef = {
82442 1+IsStat34, /* nArg */
82443 SQLITE_UTF8, /* funcFlags */
82444 0, /* pUserData */
82445 0, /* pNext */
82446 statGet, /* xFunc */
82447 0, /* xStep */
82448 0, /* xFinalize */
82449 "stat_get", /* zName */
82450 0, /* pHash */
82451 0 /* pDestructor */
82454 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
82455 assert( regOut!=regStat4 && regOut!=regStat4+1 );
82456 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82457 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
82458 #elif SQLITE_DEBUG
82459 assert( iParam==STAT_GET_STAT1 );
82460 #else
82461 UNUSED_PARAMETER( iParam );
82462 #endif
82463 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
82464 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
82465 sqlite3VdbeChangeP5(v, 1 + IsStat34);
82469 ** Generate code to do an analysis of all indices associated with
82470 ** a single table.
82472 static void analyzeOneTable(
82473 Parse *pParse, /* Parser context */
82474 Table *pTab, /* Table whose indices are to be analyzed */
82475 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
82476 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
82477 int iMem, /* Available memory locations begin here */
82478 int iTab /* Next available cursor */
82480 sqlite3 *db = pParse->db; /* Database handle */
82481 Index *pIdx; /* An index to being analyzed */
82482 int iIdxCur; /* Cursor open on index being analyzed */
82483 int iTabCur; /* Table cursor */
82484 Vdbe *v; /* The virtual machine being built up */
82485 int i; /* Loop counter */
82486 int jZeroRows = -1; /* Jump from here if number of rows is zero */
82487 int iDb; /* Index of database containing pTab */
82488 u8 needTableCnt = 1; /* True to count the table */
82489 int regNewRowid = iMem++; /* Rowid for the inserted record */
82490 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
82491 int regChng = iMem++; /* Index of changed index field */
82492 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82493 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
82494 #endif
82495 int regTemp = iMem++; /* Temporary use register */
82496 int regTabname = iMem++; /* Register containing table name */
82497 int regIdxname = iMem++; /* Register containing index name */
82498 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
82499 int regPrev = iMem; /* MUST BE LAST (see below) */
82501 pParse->nMem = MAX(pParse->nMem, iMem);
82502 v = sqlite3GetVdbe(pParse);
82503 if( v==0 || NEVER(pTab==0) ){
82504 return;
82506 if( pTab->tnum==0 ){
82507 /* Do not gather statistics on views or virtual tables */
82508 return;
82510 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
82511 /* Do not gather statistics on system tables */
82512 return;
82514 assert( sqlite3BtreeHoldsAllMutexes(db) );
82515 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
82516 assert( iDb>=0 );
82517 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82518 #ifndef SQLITE_OMIT_AUTHORIZATION
82519 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
82520 db->aDb[iDb].zName ) ){
82521 return;
82523 #endif
82525 /* Establish a read-lock on the table at the shared-cache level.
82526 ** Open a read-only cursor on the table. Also allocate a cursor number
82527 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
82528 ** this time though. */
82529 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
82530 iTabCur = iTab++;
82531 iIdxCur = iTab++;
82532 pParse->nTab = MAX(pParse->nTab, iTab);
82533 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
82534 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
82536 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
82537 int nCol; /* Number of columns indexed by pIdx */
82538 int *aGotoChng; /* Array of jump instruction addresses */
82539 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
82540 int addrGotoChng0; /* Address of "Goto addr_chng_0" */
82541 int addrNextRow; /* Address of "next_row:" */
82542 const char *zIdxName; /* Name of the index */
82544 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
82545 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
82546 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
82547 nCol = pIdx->nKeyCol;
82548 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
82549 if( aGotoChng==0 ) continue;
82551 /* Populate the register containing the index name. */
82552 if( pIdx->autoIndex==2 && !HasRowid(pTab) ){
82553 zIdxName = pTab->zName;
82554 }else{
82555 zIdxName = pIdx->zName;
82557 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
82560 ** Pseudo-code for loop that calls stat_push():
82562 ** Rewind csr
82563 ** if eof(csr) goto end_of_scan;
82564 ** regChng = 0
82565 ** goto chng_addr_0;
82567 ** next_row:
82568 ** regChng = 0
82569 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
82570 ** regChng = 1
82571 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
82572 ** ...
82573 ** regChng = N
82574 ** goto chng_addr_N
82576 ** chng_addr_0:
82577 ** regPrev(0) = idx(0)
82578 ** chng_addr_1:
82579 ** regPrev(1) = idx(1)
82580 ** ...
82582 ** chng_addr_N:
82583 ** regRowid = idx(rowid)
82584 ** stat_push(P, regChng, regRowid)
82585 ** Next csr
82586 ** if !eof(csr) goto next_row;
82588 ** end_of_scan:
82591 /* Make sure there are enough memory cells allocated to accommodate
82592 ** the regPrev array and a trailing rowid (the rowid slot is required
82593 ** when building a record to insert into the sample column of
82594 ** the sqlite_stat4 table. */
82595 pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
82597 /* Open a read-only cursor on the index being analyzed. */
82598 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
82599 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
82600 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
82601 VdbeComment((v, "%s", pIdx->zName));
82603 /* Invoke the stat_init() function. The arguments are:
82605 ** (1) the number of columns in the index including the rowid,
82606 ** (2) the number of rows in the index,
82608 ** The second argument is only used for STAT3 and STAT4
82610 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82611 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
82612 #endif
82613 sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
82614 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
82615 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
82616 sqlite3VdbeChangeP5(v, 1+IsStat34);
82618 /* Implementation of the following:
82620 ** Rewind csr
82621 ** if eof(csr) goto end_of_scan;
82622 ** regChng = 0
82623 ** goto next_push_0;
82626 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
82627 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
82628 addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
82631 ** next_row:
82632 ** regChng = 0
82633 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
82634 ** regChng = 1
82635 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
82636 ** ...
82637 ** regChng = N
82638 ** goto chng_addr_N
82640 addrNextRow = sqlite3VdbeCurrentAddr(v);
82641 for(i=0; i<nCol; i++){
82642 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
82643 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
82644 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
82645 aGotoChng[i] =
82646 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
82647 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
82649 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
82650 aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
82653 ** chng_addr_0:
82654 ** regPrev(0) = idx(0)
82655 ** chng_addr_1:
82656 ** regPrev(1) = idx(1)
82657 ** ...
82659 sqlite3VdbeJumpHere(v, addrGotoChng0);
82660 for(i=0; i<nCol; i++){
82661 sqlite3VdbeJumpHere(v, aGotoChng[i]);
82662 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
82666 ** chng_addr_N:
82667 ** regRowid = idx(rowid) // STAT34 only
82668 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
82669 ** Next csr
82670 ** if !eof(csr) goto next_row;
82672 sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
82673 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82674 assert( regRowid==(regStat4+2) );
82675 if( HasRowid(pTab) ){
82676 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
82677 }else{
82678 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
82679 int j, k, regKey;
82680 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
82681 for(j=0; j<pPk->nKeyCol; j++){
82682 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
82683 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
82684 VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
82686 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
82687 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
82689 #endif
82690 assert( regChng==(regStat4+1) );
82691 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
82692 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
82693 sqlite3VdbeChangeP5(v, 2+IsStat34);
82694 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
82696 /* Add the entry to the stat1 table. */
82697 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
82698 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
82699 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
82700 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
82701 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82703 /* Add the entries to the stat3 or stat4 table. */
82704 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82706 int regEq = regStat1;
82707 int regLt = regStat1+1;
82708 int regDLt = regStat1+2;
82709 int regSample = regStat1+3;
82710 int regCol = regStat1+4;
82711 int regSampleRowid = regCol + nCol;
82712 int addrNext;
82713 int addrIsNull;
82714 u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
82716 pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
82718 addrNext = sqlite3VdbeCurrentAddr(v);
82719 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
82720 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
82721 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
82722 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
82723 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
82724 sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
82725 #ifdef SQLITE_ENABLE_STAT3
82726 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
82727 pIdx->aiColumn[0], regSample);
82728 #else
82729 for(i=0; i<nCol; i++){
82730 i16 iCol = pIdx->aiColumn[i];
82731 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
82733 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
82734 #endif
82735 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
82736 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
82737 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
82738 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
82739 sqlite3VdbeJumpHere(v, addrIsNull);
82741 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
82743 /* End of analysis */
82744 sqlite3VdbeJumpHere(v, addrRewind);
82745 sqlite3DbFree(db, aGotoChng);
82749 /* Create a single sqlite_stat1 entry containing NULL as the index
82750 ** name and the row count as the content.
82752 if( pOnlyIdx==0 && needTableCnt ){
82753 VdbeComment((v, "%s", pTab->zName));
82754 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
82755 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
82756 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
82757 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
82758 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
82759 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
82760 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82761 sqlite3VdbeJumpHere(v, jZeroRows);
82767 ** Generate code that will cause the most recent index analysis to
82768 ** be loaded into internal hash tables where is can be used.
82770 static void loadAnalysis(Parse *pParse, int iDb){
82771 Vdbe *v = sqlite3GetVdbe(pParse);
82772 if( v ){
82773 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
82778 ** Generate code that will do an analysis of an entire database
82780 static void analyzeDatabase(Parse *pParse, int iDb){
82781 sqlite3 *db = pParse->db;
82782 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
82783 HashElem *k;
82784 int iStatCur;
82785 int iMem;
82786 int iTab;
82788 sqlite3BeginWriteOperation(pParse, 0, iDb);
82789 iStatCur = pParse->nTab;
82790 pParse->nTab += 3;
82791 openStatTable(pParse, iDb, iStatCur, 0, 0);
82792 iMem = pParse->nMem+1;
82793 iTab = pParse->nTab;
82794 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82795 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
82796 Table *pTab = (Table*)sqliteHashData(k);
82797 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
82799 loadAnalysis(pParse, iDb);
82803 ** Generate code that will do an analysis of a single table in
82804 ** a database. If pOnlyIdx is not NULL then it is a single index
82805 ** in pTab that should be analyzed.
82807 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
82808 int iDb;
82809 int iStatCur;
82811 assert( pTab!=0 );
82812 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
82813 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82814 sqlite3BeginWriteOperation(pParse, 0, iDb);
82815 iStatCur = pParse->nTab;
82816 pParse->nTab += 3;
82817 if( pOnlyIdx ){
82818 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
82819 }else{
82820 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
82822 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
82823 loadAnalysis(pParse, iDb);
82827 ** Generate code for the ANALYZE command. The parser calls this routine
82828 ** when it recognizes an ANALYZE command.
82830 ** ANALYZE -- 1
82831 ** ANALYZE <database> -- 2
82832 ** ANALYZE ?<database>.?<tablename> -- 3
82834 ** Form 1 causes all indices in all attached databases to be analyzed.
82835 ** Form 2 analyzes all indices the single database named.
82836 ** Form 3 analyzes all indices associated with the named table.
82838 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
82839 sqlite3 *db = pParse->db;
82840 int iDb;
82841 int i;
82842 char *z, *zDb;
82843 Table *pTab;
82844 Index *pIdx;
82845 Token *pTableName;
82847 /* Read the database schema. If an error occurs, leave an error message
82848 ** and code in pParse and return NULL. */
82849 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
82850 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82851 return;
82854 assert( pName2!=0 || pName1==0 );
82855 if( pName1==0 ){
82856 /* Form 1: Analyze everything */
82857 for(i=0; i<db->nDb; i++){
82858 if( i==1 ) continue; /* Do not analyze the TEMP database */
82859 analyzeDatabase(pParse, i);
82861 }else if( pName2->n==0 ){
82862 /* Form 2: Analyze the database or table named */
82863 iDb = sqlite3FindDb(db, pName1);
82864 if( iDb>=0 ){
82865 analyzeDatabase(pParse, iDb);
82866 }else{
82867 z = sqlite3NameFromToken(db, pName1);
82868 if( z ){
82869 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
82870 analyzeTable(pParse, pIdx->pTable, pIdx);
82871 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
82872 analyzeTable(pParse, pTab, 0);
82874 sqlite3DbFree(db, z);
82877 }else{
82878 /* Form 3: Analyze the fully qualified table name */
82879 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
82880 if( iDb>=0 ){
82881 zDb = db->aDb[iDb].zName;
82882 z = sqlite3NameFromToken(db, pTableName);
82883 if( z ){
82884 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
82885 analyzeTable(pParse, pIdx->pTable, pIdx);
82886 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
82887 analyzeTable(pParse, pTab, 0);
82889 sqlite3DbFree(db, z);
82896 ** Used to pass information from the analyzer reader through to the
82897 ** callback routine.
82899 typedef struct analysisInfo analysisInfo;
82900 struct analysisInfo {
82901 sqlite3 *db;
82902 const char *zDatabase;
82906 ** The first argument points to a nul-terminated string containing a
82907 ** list of space separated integers. Read the first nOut of these into
82908 ** the array aOut[].
82910 static void decodeIntArray(
82911 char *zIntArray, /* String containing int array to decode */
82912 int nOut, /* Number of slots in aOut[] */
82913 tRowcnt *aOut, /* Store integers here */
82914 Index *pIndex /* Handle extra flags for this index, if not NULL */
82916 char *z = zIntArray;
82917 int c;
82918 int i;
82919 tRowcnt v;
82921 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
82922 if( z==0 ) z = "";
82923 #else
82924 if( NEVER(z==0) ) z = "";
82925 #endif
82926 for(i=0; *z && i<nOut; i++){
82927 v = 0;
82928 while( (c=z[0])>='0' && c<='9' ){
82929 v = v*10 + c - '0';
82930 z++;
82932 aOut[i] = v;
82933 if( *z==' ' ) z++;
82935 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
82936 assert( pIndex!=0 );
82937 #else
82938 if( pIndex )
82939 #endif
82941 if( strcmp(z, "unordered")==0 ){
82942 pIndex->bUnordered = 1;
82943 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
82944 int v32 = 0;
82945 sqlite3GetInt32(z+3, &v32);
82946 pIndex->szIdxRow = sqlite3LogEst(v32);
82952 ** This callback is invoked once for each index when reading the
82953 ** sqlite_stat1 table.
82955 ** argv[0] = name of the table
82956 ** argv[1] = name of the index (might be NULL)
82957 ** argv[2] = results of analysis - on integer for each column
82959 ** Entries for which argv[1]==NULL simply record the number of rows in
82960 ** the table.
82962 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
82963 analysisInfo *pInfo = (analysisInfo*)pData;
82964 Index *pIndex;
82965 Table *pTable;
82966 const char *z;
82968 assert( argc==3 );
82969 UNUSED_PARAMETER2(NotUsed, argc);
82971 if( argv==0 || argv[0]==0 || argv[2]==0 ){
82972 return 0;
82974 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
82975 if( pTable==0 ){
82976 return 0;
82978 if( argv[1]==0 ){
82979 pIndex = 0;
82980 }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
82981 pIndex = sqlite3PrimaryKeyIndex(pTable);
82982 }else{
82983 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
82985 z = argv[2];
82987 if( pIndex ){
82988 decodeIntArray((char*)z, pIndex->nKeyCol+1, pIndex->aiRowEst, pIndex);
82989 if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
82990 }else{
82991 Index fakeIdx;
82992 fakeIdx.szIdxRow = pTable->szTabRow;
82993 decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
82994 pTable->szTabRow = fakeIdx.szIdxRow;
82997 return 0;
83001 ** If the Index.aSample variable is not NULL, delete the aSample[] array
83002 ** and its contents.
83004 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
83005 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83006 if( pIdx->aSample ){
83007 int j;
83008 for(j=0; j<pIdx->nSample; j++){
83009 IndexSample *p = &pIdx->aSample[j];
83010 sqlite3DbFree(db, p->p);
83012 sqlite3DbFree(db, pIdx->aSample);
83014 if( db && db->pnBytesFreed==0 ){
83015 pIdx->nSample = 0;
83016 pIdx->aSample = 0;
83018 #else
83019 UNUSED_PARAMETER(db);
83020 UNUSED_PARAMETER(pIdx);
83021 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
83024 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83026 ** Populate the pIdx->aAvgEq[] array based on the samples currently
83027 ** stored in pIdx->aSample[].
83029 static void initAvgEq(Index *pIdx){
83030 if( pIdx ){
83031 IndexSample *aSample = pIdx->aSample;
83032 IndexSample *pFinal = &aSample[pIdx->nSample-1];
83033 int iCol;
83034 for(iCol=0; iCol<pIdx->nKeyCol; iCol++){
83035 int i; /* Used to iterate through samples */
83036 tRowcnt sumEq = 0; /* Sum of the nEq values */
83037 tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
83038 tRowcnt avgEq = 0;
83039 tRowcnt nDLt = pFinal->anDLt[iCol];
83041 /* Set nSum to the number of distinct (iCol+1) field prefixes that
83042 ** occur in the stat4 table for this index before pFinal. Set
83043 ** sumEq to the sum of the nEq values for column iCol for the same
83044 ** set (adding the value only once where there exist dupicate
83045 ** prefixes). */
83046 for(i=0; i<(pIdx->nSample-1); i++){
83047 if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
83048 sumEq += aSample[i].anEq[iCol];
83049 nSum++;
83052 if( nDLt>nSum ){
83053 avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
83055 if( avgEq==0 ) avgEq = 1;
83056 pIdx->aAvgEq[iCol] = avgEq;
83057 if( pIdx->nSampleCol==1 ) break;
83063 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
83064 ** is supplied instead, find the PRIMARY KEY index for that table.
83066 static Index *findIndexOrPrimaryKey(
83067 sqlite3 *db,
83068 const char *zName,
83069 const char *zDb
83071 Index *pIdx = sqlite3FindIndex(db, zName, zDb);
83072 if( pIdx==0 ){
83073 Table *pTab = sqlite3FindTable(db, zName, zDb);
83074 if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
83076 return pIdx;
83080 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
83081 ** into the relevant Index.aSample[] arrays.
83083 ** Arguments zSql1 and zSql2 must point to SQL statements that return
83084 ** data equivalent to the following (statements are different for stat3,
83085 ** see the caller of this function for details):
83087 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
83088 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
83090 ** where %Q is replaced with the database name before the SQL is executed.
83092 static int loadStatTbl(
83093 sqlite3 *db, /* Database handle */
83094 int bStat3, /* Assume single column records only */
83095 const char *zSql1, /* SQL statement 1 (see above) */
83096 const char *zSql2, /* SQL statement 2 (see above) */
83097 const char *zDb /* Database name (e.g. "main") */
83099 int rc; /* Result codes from subroutines */
83100 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
83101 char *zSql; /* Text of the SQL statement */
83102 Index *pPrevIdx = 0; /* Previous index in the loop */
83103 IndexSample *pSample; /* A slot in pIdx->aSample[] */
83105 assert( db->lookaside.bEnabled==0 );
83106 zSql = sqlite3MPrintf(db, zSql1, zDb);
83107 if( !zSql ){
83108 return SQLITE_NOMEM;
83110 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
83111 sqlite3DbFree(db, zSql);
83112 if( rc ) return rc;
83114 while( sqlite3_step(pStmt)==SQLITE_ROW ){
83115 int nIdxCol = 1; /* Number of columns in stat4 records */
83116 int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
83118 char *zIndex; /* Index name */
83119 Index *pIdx; /* Pointer to the index object */
83120 int nSample; /* Number of samples */
83121 int nByte; /* Bytes of space required */
83122 int i; /* Bytes of space required */
83123 tRowcnt *pSpace;
83125 zIndex = (char *)sqlite3_column_text(pStmt, 0);
83126 if( zIndex==0 ) continue;
83127 nSample = sqlite3_column_int(pStmt, 1);
83128 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
83129 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
83130 /* Index.nSample is non-zero at this point if data has already been
83131 ** loaded from the stat4 table. In this case ignore stat3 data. */
83132 if( pIdx==0 || pIdx->nSample ) continue;
83133 if( bStat3==0 ){
83134 nIdxCol = pIdx->nKeyCol+1;
83135 nAvgCol = pIdx->nKeyCol;
83137 pIdx->nSampleCol = nIdxCol;
83138 nByte = sizeof(IndexSample) * nSample;
83139 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
83140 nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
83142 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
83143 if( pIdx->aSample==0 ){
83144 sqlite3_finalize(pStmt);
83145 return SQLITE_NOMEM;
83147 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
83148 pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
83149 for(i=0; i<nSample; i++){
83150 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
83151 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
83152 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
83154 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
83156 rc = sqlite3_finalize(pStmt);
83157 if( rc ) return rc;
83159 zSql = sqlite3MPrintf(db, zSql2, zDb);
83160 if( !zSql ){
83161 return SQLITE_NOMEM;
83163 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
83164 sqlite3DbFree(db, zSql);
83165 if( rc ) return rc;
83167 while( sqlite3_step(pStmt)==SQLITE_ROW ){
83168 char *zIndex; /* Index name */
83169 Index *pIdx; /* Pointer to the index object */
83170 int nCol = 1; /* Number of columns in index */
83172 zIndex = (char *)sqlite3_column_text(pStmt, 0);
83173 if( zIndex==0 ) continue;
83174 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
83175 if( pIdx==0 ) continue;
83176 /* This next condition is true if data has already been loaded from
83177 ** the sqlite_stat4 table. In this case ignore stat3 data. */
83178 nCol = pIdx->nSampleCol;
83179 if( bStat3 && nCol>1 ) continue;
83180 if( pIdx!=pPrevIdx ){
83181 initAvgEq(pPrevIdx);
83182 pPrevIdx = pIdx;
83184 pSample = &pIdx->aSample[pIdx->nSample];
83185 decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
83186 decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
83187 decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
83189 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
83190 ** This is in case the sample record is corrupted. In that case, the
83191 ** sqlite3VdbeRecordCompare() may read up to two varints past the
83192 ** end of the allocated buffer before it realizes it is dealing with
83193 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
83194 ** a buffer overread. */
83195 pSample->n = sqlite3_column_bytes(pStmt, 4);
83196 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
83197 if( pSample->p==0 ){
83198 sqlite3_finalize(pStmt);
83199 return SQLITE_NOMEM;
83201 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
83202 pIdx->nSample++;
83204 rc = sqlite3_finalize(pStmt);
83205 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
83206 return rc;
83210 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
83211 ** the Index.aSample[] arrays of all indices.
83213 static int loadStat4(sqlite3 *db, const char *zDb){
83214 int rc = SQLITE_OK; /* Result codes from subroutines */
83216 assert( db->lookaside.bEnabled==0 );
83217 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
83218 rc = loadStatTbl(db, 0,
83219 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
83220 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
83225 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
83226 rc = loadStatTbl(db, 1,
83227 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
83228 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
83233 return rc;
83235 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
83238 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
83239 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
83240 ** arrays. The contents of sqlite_stat3/4 are used to populate the
83241 ** Index.aSample[] arrays.
83243 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
83244 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
83245 ** during compilation and the sqlite_stat3/4 table is present, no data is
83246 ** read from it.
83248 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
83249 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
83250 ** returned. However, in this case, data is read from the sqlite_stat1
83251 ** table (if it is present) before returning.
83253 ** If an OOM error occurs, this function always sets db->mallocFailed.
83254 ** This means if the caller does not care about other errors, the return
83255 ** code may be ignored.
83257 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
83258 analysisInfo sInfo;
83259 HashElem *i;
83260 char *zSql;
83261 int rc;
83263 assert( iDb>=0 && iDb<db->nDb );
83264 assert( db->aDb[iDb].pBt!=0 );
83266 /* Clear any prior statistics */
83267 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83268 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
83269 Index *pIdx = sqliteHashData(i);
83270 sqlite3DefaultRowEst(pIdx);
83271 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83272 sqlite3DeleteIndexSamples(db, pIdx);
83273 pIdx->aSample = 0;
83274 #endif
83277 /* Check to make sure the sqlite_stat1 table exists */
83278 sInfo.db = db;
83279 sInfo.zDatabase = db->aDb[iDb].zName;
83280 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
83281 return SQLITE_ERROR;
83284 /* Load new statistics out of the sqlite_stat1 table */
83285 zSql = sqlite3MPrintf(db,
83286 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
83287 if( zSql==0 ){
83288 rc = SQLITE_NOMEM;
83289 }else{
83290 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
83291 sqlite3DbFree(db, zSql);
83295 /* Load the statistics from the sqlite_stat4 table. */
83296 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
83297 if( rc==SQLITE_OK ){
83298 int lookasideEnabled = db->lookaside.bEnabled;
83299 db->lookaside.bEnabled = 0;
83300 rc = loadStat4(db, sInfo.zDatabase);
83301 db->lookaside.bEnabled = lookasideEnabled;
83303 #endif
83305 if( rc==SQLITE_NOMEM ){
83306 db->mallocFailed = 1;
83308 return rc;
83312 #endif /* SQLITE_OMIT_ANALYZE */
83314 /************** End of analyze.c *********************************************/
83315 /************** Begin file attach.c ******************************************/
83317 ** 2003 April 6
83319 ** The author disclaims copyright to this source code. In place of
83320 ** a legal notice, here is a blessing:
83322 ** May you do good and not evil.
83323 ** May you find forgiveness for yourself and forgive others.
83324 ** May you share freely, never taking more than you give.
83326 *************************************************************************
83327 ** This file contains code used to implement the ATTACH and DETACH commands.
83330 #ifndef SQLITE_OMIT_ATTACH
83332 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
83333 ** is slightly different from resolving a normal SQL expression, because simple
83334 ** identifiers are treated as strings, not possible column names or aliases.
83336 ** i.e. if the parser sees:
83338 ** ATTACH DATABASE abc AS def
83340 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
83341 ** looking for columns of the same name.
83343 ** This only applies to the root node of pExpr, so the statement:
83345 ** ATTACH DATABASE abc||def AS 'db2'
83347 ** will fail because neither abc or def can be resolved.
83349 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
83351 int rc = SQLITE_OK;
83352 if( pExpr ){
83353 if( pExpr->op!=TK_ID ){
83354 rc = sqlite3ResolveExprNames(pName, pExpr);
83355 }else{
83356 pExpr->op = TK_STRING;
83359 return rc;
83363 ** An SQL user-function registered to do the work of an ATTACH statement. The
83364 ** three arguments to the function come directly from an attach statement:
83366 ** ATTACH DATABASE x AS y KEY z
83368 ** SELECT sqlite_attach(x, y, z)
83370 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
83371 ** third argument.
83373 static void attachFunc(
83374 sqlite3_context *context,
83375 int NotUsed,
83376 sqlite3_value **argv
83378 int i;
83379 int rc = 0;
83380 sqlite3 *db = sqlite3_context_db_handle(context);
83381 const char *zName;
83382 const char *zFile;
83383 char *zPath = 0;
83384 char *zErr = 0;
83385 unsigned int flags;
83386 Db *aNew;
83387 char *zErrDyn = 0;
83388 sqlite3_vfs *pVfs;
83390 UNUSED_PARAMETER(NotUsed);
83392 zFile = (const char *)sqlite3_value_text(argv[0]);
83393 zName = (const char *)sqlite3_value_text(argv[1]);
83394 if( zFile==0 ) zFile = "";
83395 if( zName==0 ) zName = "";
83397 /* Check for the following errors:
83399 ** * Too many attached databases,
83400 ** * Transaction currently open
83401 ** * Specified database name already being used.
83403 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
83404 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
83405 db->aLimit[SQLITE_LIMIT_ATTACHED]
83407 goto attach_error;
83409 if( !db->autoCommit ){
83410 zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
83411 goto attach_error;
83413 for(i=0; i<db->nDb; i++){
83414 char *z = db->aDb[i].zName;
83415 assert( z && zName );
83416 if( sqlite3StrICmp(z, zName)==0 ){
83417 zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
83418 goto attach_error;
83422 /* Allocate the new entry in the db->aDb[] array and initialize the schema
83423 ** hash tables.
83425 if( db->aDb==db->aDbStatic ){
83426 aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
83427 if( aNew==0 ) return;
83428 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
83429 }else{
83430 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
83431 if( aNew==0 ) return;
83433 db->aDb = aNew;
83434 aNew = &db->aDb[db->nDb];
83435 memset(aNew, 0, sizeof(*aNew));
83437 /* Open the database file. If the btree is successfully opened, use
83438 ** it to obtain the database schema. At this point the schema may
83439 ** or may not be initialized.
83441 flags = db->openFlags;
83442 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
83443 if( rc!=SQLITE_OK ){
83444 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
83445 sqlite3_result_error(context, zErr, -1);
83446 sqlite3_free(zErr);
83447 return;
83449 assert( pVfs );
83450 flags |= SQLITE_OPEN_MAIN_DB;
83451 rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
83452 sqlite3_free( zPath );
83453 db->nDb++;
83454 if( rc==SQLITE_CONSTRAINT ){
83455 rc = SQLITE_ERROR;
83456 zErrDyn = sqlite3MPrintf(db, "database is already attached");
83457 }else if( rc==SQLITE_OK ){
83458 Pager *pPager;
83459 aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
83460 if( !aNew->pSchema ){
83461 rc = SQLITE_NOMEM;
83462 }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
83463 zErrDyn = sqlite3MPrintf(db,
83464 "attached databases must use the same text encoding as main database");
83465 rc = SQLITE_ERROR;
83467 pPager = sqlite3BtreePager(aNew->pBt);
83468 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
83469 sqlite3BtreeSecureDelete(aNew->pBt,
83470 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
83471 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83472 sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
83473 #endif
83475 aNew->safety_level = 3;
83476 aNew->zName = sqlite3DbStrDup(db, zName);
83477 if( rc==SQLITE_OK && aNew->zName==0 ){
83478 rc = SQLITE_NOMEM;
83482 #ifdef SQLITE_HAS_CODEC
83483 if( rc==SQLITE_OK ){
83484 extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
83485 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
83486 int nKey;
83487 char *zKey;
83488 int t = sqlite3_value_type(argv[2]);
83489 switch( t ){
83490 case SQLITE_INTEGER:
83491 case SQLITE_FLOAT:
83492 zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
83493 rc = SQLITE_ERROR;
83494 break;
83496 case SQLITE_TEXT:
83497 case SQLITE_BLOB:
83498 nKey = sqlite3_value_bytes(argv[2]);
83499 zKey = (char *)sqlite3_value_blob(argv[2]);
83500 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
83501 break;
83503 case SQLITE_NULL:
83504 /* No key specified. Use the key from the main database */
83505 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
83506 if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
83507 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
83509 break;
83512 #endif
83514 /* If the file was opened successfully, read the schema for the new database.
83515 ** If this fails, or if opening the file failed, then close the file and
83516 ** remove the entry from the db->aDb[] array. i.e. put everything back the way
83517 ** we found it.
83519 if( rc==SQLITE_OK ){
83520 sqlite3BtreeEnterAll(db);
83521 rc = sqlite3Init(db, &zErrDyn);
83522 sqlite3BtreeLeaveAll(db);
83524 if( rc ){
83525 int iDb = db->nDb - 1;
83526 assert( iDb>=2 );
83527 if( db->aDb[iDb].pBt ){
83528 sqlite3BtreeClose(db->aDb[iDb].pBt);
83529 db->aDb[iDb].pBt = 0;
83530 db->aDb[iDb].pSchema = 0;
83532 sqlite3ResetAllSchemasOfConnection(db);
83533 db->nDb = iDb;
83534 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
83535 db->mallocFailed = 1;
83536 sqlite3DbFree(db, zErrDyn);
83537 zErrDyn = sqlite3MPrintf(db, "out of memory");
83538 }else if( zErrDyn==0 ){
83539 zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
83541 goto attach_error;
83544 return;
83546 attach_error:
83547 /* Return an error if we get here */
83548 if( zErrDyn ){
83549 sqlite3_result_error(context, zErrDyn, -1);
83550 sqlite3DbFree(db, zErrDyn);
83552 if( rc ) sqlite3_result_error_code(context, rc);
83556 ** An SQL user-function registered to do the work of an DETACH statement. The
83557 ** three arguments to the function come directly from a detach statement:
83559 ** DETACH DATABASE x
83561 ** SELECT sqlite_detach(x)
83563 static void detachFunc(
83564 sqlite3_context *context,
83565 int NotUsed,
83566 sqlite3_value **argv
83568 const char *zName = (const char *)sqlite3_value_text(argv[0]);
83569 sqlite3 *db = sqlite3_context_db_handle(context);
83570 int i;
83571 Db *pDb = 0;
83572 char zErr[128];
83574 UNUSED_PARAMETER(NotUsed);
83576 if( zName==0 ) zName = "";
83577 for(i=0; i<db->nDb; i++){
83578 pDb = &db->aDb[i];
83579 if( pDb->pBt==0 ) continue;
83580 if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
83583 if( i>=db->nDb ){
83584 sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
83585 goto detach_error;
83587 if( i<2 ){
83588 sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
83589 goto detach_error;
83591 if( !db->autoCommit ){
83592 sqlite3_snprintf(sizeof(zErr), zErr,
83593 "cannot DETACH database within transaction");
83594 goto detach_error;
83596 if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
83597 sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
83598 goto detach_error;
83601 sqlite3BtreeClose(pDb->pBt);
83602 pDb->pBt = 0;
83603 pDb->pSchema = 0;
83604 sqlite3ResetAllSchemasOfConnection(db);
83605 return;
83607 detach_error:
83608 sqlite3_result_error(context, zErr, -1);
83612 ** This procedure generates VDBE code for a single invocation of either the
83613 ** sqlite_detach() or sqlite_attach() SQL user functions.
83615 static void codeAttach(
83616 Parse *pParse, /* The parser context */
83617 int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
83618 FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
83619 Expr *pAuthArg, /* Expression to pass to authorization callback */
83620 Expr *pFilename, /* Name of database file */
83621 Expr *pDbname, /* Name of the database to use internally */
83622 Expr *pKey /* Database key for encryption extension */
83624 int rc;
83625 NameContext sName;
83626 Vdbe *v;
83627 sqlite3* db = pParse->db;
83628 int regArgs;
83630 memset(&sName, 0, sizeof(NameContext));
83631 sName.pParse = pParse;
83633 if(
83634 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
83635 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
83636 SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
83638 pParse->nErr++;
83639 goto attach_end;
83642 #ifndef SQLITE_OMIT_AUTHORIZATION
83643 if( pAuthArg ){
83644 char *zAuthArg;
83645 if( pAuthArg->op==TK_STRING ){
83646 zAuthArg = pAuthArg->u.zToken;
83647 }else{
83648 zAuthArg = 0;
83650 rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
83651 if(rc!=SQLITE_OK ){
83652 goto attach_end;
83655 #endif /* SQLITE_OMIT_AUTHORIZATION */
83658 v = sqlite3GetVdbe(pParse);
83659 regArgs = sqlite3GetTempRange(pParse, 4);
83660 sqlite3ExprCode(pParse, pFilename, regArgs);
83661 sqlite3ExprCode(pParse, pDbname, regArgs+1);
83662 sqlite3ExprCode(pParse, pKey, regArgs+2);
83664 assert( v || db->mallocFailed );
83665 if( v ){
83666 sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
83667 assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
83668 sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
83669 sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
83671 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
83672 ** statement only). For DETACH, set it to false (expire all existing
83673 ** statements).
83675 sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
83678 attach_end:
83679 sqlite3ExprDelete(db, pFilename);
83680 sqlite3ExprDelete(db, pDbname);
83681 sqlite3ExprDelete(db, pKey);
83685 ** Called by the parser to compile a DETACH statement.
83687 ** DETACH pDbname
83689 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
83690 static const FuncDef detach_func = {
83691 1, /* nArg */
83692 SQLITE_UTF8, /* funcFlags */
83693 0, /* pUserData */
83694 0, /* pNext */
83695 detachFunc, /* xFunc */
83696 0, /* xStep */
83697 0, /* xFinalize */
83698 "sqlite_detach", /* zName */
83699 0, /* pHash */
83700 0 /* pDestructor */
83702 codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
83706 ** Called by the parser to compile an ATTACH statement.
83708 ** ATTACH p AS pDbname KEY pKey
83710 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
83711 static const FuncDef attach_func = {
83712 3, /* nArg */
83713 SQLITE_UTF8, /* funcFlags */
83714 0, /* pUserData */
83715 0, /* pNext */
83716 attachFunc, /* xFunc */
83717 0, /* xStep */
83718 0, /* xFinalize */
83719 "sqlite_attach", /* zName */
83720 0, /* pHash */
83721 0 /* pDestructor */
83723 codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
83725 #endif /* SQLITE_OMIT_ATTACH */
83728 ** Initialize a DbFixer structure. This routine must be called prior
83729 ** to passing the structure to one of the sqliteFixAAAA() routines below.
83731 SQLITE_PRIVATE void sqlite3FixInit(
83732 DbFixer *pFix, /* The fixer to be initialized */
83733 Parse *pParse, /* Error messages will be written here */
83734 int iDb, /* This is the database that must be used */
83735 const char *zType, /* "view", "trigger", or "index" */
83736 const Token *pName /* Name of the view, trigger, or index */
83738 sqlite3 *db;
83740 db = pParse->db;
83741 assert( db->nDb>iDb );
83742 pFix->pParse = pParse;
83743 pFix->zDb = db->aDb[iDb].zName;
83744 pFix->pSchema = db->aDb[iDb].pSchema;
83745 pFix->zType = zType;
83746 pFix->pName = pName;
83747 pFix->bVarOnly = (iDb==1);
83751 ** The following set of routines walk through the parse tree and assign
83752 ** a specific database to all table references where the database name
83753 ** was left unspecified in the original SQL statement. The pFix structure
83754 ** must have been initialized by a prior call to sqlite3FixInit().
83756 ** These routines are used to make sure that an index, trigger, or
83757 ** view in one database does not refer to objects in a different database.
83758 ** (Exception: indices, triggers, and views in the TEMP database are
83759 ** allowed to refer to anything.) If a reference is explicitly made
83760 ** to an object in a different database, an error message is added to
83761 ** pParse->zErrMsg and these routines return non-zero. If everything
83762 ** checks out, these routines return 0.
83764 SQLITE_PRIVATE int sqlite3FixSrcList(
83765 DbFixer *pFix, /* Context of the fixation */
83766 SrcList *pList /* The Source list to check and modify */
83768 int i;
83769 const char *zDb;
83770 struct SrcList_item *pItem;
83772 if( NEVER(pList==0) ) return 0;
83773 zDb = pFix->zDb;
83774 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
83775 if( pFix->bVarOnly==0 ){
83776 if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
83777 sqlite3ErrorMsg(pFix->pParse,
83778 "%s %T cannot reference objects in database %s",
83779 pFix->zType, pFix->pName, pItem->zDatabase);
83780 return 1;
83782 sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
83783 pItem->zDatabase = 0;
83784 pItem->pSchema = pFix->pSchema;
83786 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
83787 if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
83788 if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
83789 #endif
83791 return 0;
83793 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
83794 SQLITE_PRIVATE int sqlite3FixSelect(
83795 DbFixer *pFix, /* Context of the fixation */
83796 Select *pSelect /* The SELECT statement to be fixed to one database */
83798 while( pSelect ){
83799 if( sqlite3FixExprList(pFix, pSelect->pEList) ){
83800 return 1;
83802 if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
83803 return 1;
83805 if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
83806 return 1;
83808 if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
83809 return 1;
83811 if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
83812 return 1;
83814 if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
83815 return 1;
83817 if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
83818 return 1;
83820 if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
83821 return 1;
83823 pSelect = pSelect->pPrior;
83825 return 0;
83827 SQLITE_PRIVATE int sqlite3FixExpr(
83828 DbFixer *pFix, /* Context of the fixation */
83829 Expr *pExpr /* The expression to be fixed to one database */
83831 while( pExpr ){
83832 if( pExpr->op==TK_VARIABLE ){
83833 if( pFix->pParse->db->init.busy ){
83834 pExpr->op = TK_NULL;
83835 }else{
83836 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
83837 return 1;
83840 if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
83841 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
83842 if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
83843 }else{
83844 if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
83846 if( sqlite3FixExpr(pFix, pExpr->pRight) ){
83847 return 1;
83849 pExpr = pExpr->pLeft;
83851 return 0;
83853 SQLITE_PRIVATE int sqlite3FixExprList(
83854 DbFixer *pFix, /* Context of the fixation */
83855 ExprList *pList /* The expression to be fixed to one database */
83857 int i;
83858 struct ExprList_item *pItem;
83859 if( pList==0 ) return 0;
83860 for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
83861 if( sqlite3FixExpr(pFix, pItem->pExpr) ){
83862 return 1;
83865 return 0;
83867 #endif
83869 #ifndef SQLITE_OMIT_TRIGGER
83870 SQLITE_PRIVATE int sqlite3FixTriggerStep(
83871 DbFixer *pFix, /* Context of the fixation */
83872 TriggerStep *pStep /* The trigger step be fixed to one database */
83874 while( pStep ){
83875 if( sqlite3FixSelect(pFix, pStep->pSelect) ){
83876 return 1;
83878 if( sqlite3FixExpr(pFix, pStep->pWhere) ){
83879 return 1;
83881 if( sqlite3FixExprList(pFix, pStep->pExprList) ){
83882 return 1;
83884 pStep = pStep->pNext;
83886 return 0;
83888 #endif
83890 /************** End of attach.c **********************************************/
83891 /************** Begin file auth.c ********************************************/
83893 ** 2003 January 11
83895 ** The author disclaims copyright to this source code. In place of
83896 ** a legal notice, here is a blessing:
83898 ** May you do good and not evil.
83899 ** May you find forgiveness for yourself and forgive others.
83900 ** May you share freely, never taking more than you give.
83902 *************************************************************************
83903 ** This file contains code used to implement the sqlite3_set_authorizer()
83904 ** API. This facility is an optional feature of the library. Embedded
83905 ** systems that do not need this facility may omit it by recompiling
83906 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
83910 ** All of the code in this file may be omitted by defining a single
83911 ** macro.
83913 #ifndef SQLITE_OMIT_AUTHORIZATION
83916 ** Set or clear the access authorization function.
83918 ** The access authorization function is be called during the compilation
83919 ** phase to verify that the user has read and/or write access permission on
83920 ** various fields of the database. The first argument to the auth function
83921 ** is a copy of the 3rd argument to this routine. The second argument
83922 ** to the auth function is one of these constants:
83924 ** SQLITE_CREATE_INDEX
83925 ** SQLITE_CREATE_TABLE
83926 ** SQLITE_CREATE_TEMP_INDEX
83927 ** SQLITE_CREATE_TEMP_TABLE
83928 ** SQLITE_CREATE_TEMP_TRIGGER
83929 ** SQLITE_CREATE_TEMP_VIEW
83930 ** SQLITE_CREATE_TRIGGER
83931 ** SQLITE_CREATE_VIEW
83932 ** SQLITE_DELETE
83933 ** SQLITE_DROP_INDEX
83934 ** SQLITE_DROP_TABLE
83935 ** SQLITE_DROP_TEMP_INDEX
83936 ** SQLITE_DROP_TEMP_TABLE
83937 ** SQLITE_DROP_TEMP_TRIGGER
83938 ** SQLITE_DROP_TEMP_VIEW
83939 ** SQLITE_DROP_TRIGGER
83940 ** SQLITE_DROP_VIEW
83941 ** SQLITE_INSERT
83942 ** SQLITE_PRAGMA
83943 ** SQLITE_READ
83944 ** SQLITE_SELECT
83945 ** SQLITE_TRANSACTION
83946 ** SQLITE_UPDATE
83948 ** The third and fourth arguments to the auth function are the name of
83949 ** the table and the column that are being accessed. The auth function
83950 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
83951 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
83952 ** means that the SQL statement will never-run - the sqlite3_exec() call
83953 ** will return with an error. SQLITE_IGNORE means that the SQL statement
83954 ** should run but attempts to read the specified column will return NULL
83955 ** and attempts to write the column will be ignored.
83957 ** Setting the auth function to NULL disables this hook. The default
83958 ** setting of the auth function is NULL.
83960 SQLITE_API int sqlite3_set_authorizer(
83961 sqlite3 *db,
83962 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
83963 void *pArg
83965 sqlite3_mutex_enter(db->mutex);
83966 db->xAuth = xAuth;
83967 db->pAuthArg = pArg;
83968 sqlite3ExpirePreparedStatements(db);
83969 sqlite3_mutex_leave(db->mutex);
83970 return SQLITE_OK;
83974 ** Write an error message into pParse->zErrMsg that explains that the
83975 ** user-supplied authorization function returned an illegal value.
83977 static void sqliteAuthBadReturnCode(Parse *pParse){
83978 sqlite3ErrorMsg(pParse, "authorizer malfunction");
83979 pParse->rc = SQLITE_ERROR;
83983 ** Invoke the authorization callback for permission to read column zCol from
83984 ** table zTab in database zDb. This function assumes that an authorization
83985 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
83987 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
83988 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
83989 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
83991 SQLITE_PRIVATE int sqlite3AuthReadCol(
83992 Parse *pParse, /* The parser context */
83993 const char *zTab, /* Table name */
83994 const char *zCol, /* Column name */
83995 int iDb /* Index of containing database. */
83997 sqlite3 *db = pParse->db; /* Database handle */
83998 char *zDb = db->aDb[iDb].zName; /* Name of attached database */
83999 int rc; /* Auth callback return code */
84001 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
84002 if( rc==SQLITE_DENY ){
84003 if( db->nDb>2 || iDb!=0 ){
84004 sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
84005 }else{
84006 sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
84008 pParse->rc = SQLITE_AUTH;
84009 }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
84010 sqliteAuthBadReturnCode(pParse);
84012 return rc;
84016 ** The pExpr should be a TK_COLUMN expression. The table referred to
84017 ** is in pTabList or else it is the NEW or OLD table of a trigger.
84018 ** Check to see if it is OK to read this particular column.
84020 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
84021 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
84022 ** then generate an error.
84024 SQLITE_PRIVATE void sqlite3AuthRead(
84025 Parse *pParse, /* The parser context */
84026 Expr *pExpr, /* The expression to check authorization on */
84027 Schema *pSchema, /* The schema of the expression */
84028 SrcList *pTabList /* All table that pExpr might refer to */
84030 sqlite3 *db = pParse->db;
84031 Table *pTab = 0; /* The table being read */
84032 const char *zCol; /* Name of the column of the table */
84033 int iSrc; /* Index in pTabList->a[] of table being read */
84034 int iDb; /* The index of the database the expression refers to */
84035 int iCol; /* Index of column in table */
84037 if( db->xAuth==0 ) return;
84038 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
84039 if( iDb<0 ){
84040 /* An attempt to read a column out of a subquery or other
84041 ** temporary table. */
84042 return;
84045 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
84046 if( pExpr->op==TK_TRIGGER ){
84047 pTab = pParse->pTriggerTab;
84048 }else{
84049 assert( pTabList );
84050 for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
84051 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
84052 pTab = pTabList->a[iSrc].pTab;
84053 break;
84057 iCol = pExpr->iColumn;
84058 if( NEVER(pTab==0) ) return;
84060 if( iCol>=0 ){
84061 assert( iCol<pTab->nCol );
84062 zCol = pTab->aCol[iCol].zName;
84063 }else if( pTab->iPKey>=0 ){
84064 assert( pTab->iPKey<pTab->nCol );
84065 zCol = pTab->aCol[pTab->iPKey].zName;
84066 }else{
84067 zCol = "ROWID";
84069 assert( iDb>=0 && iDb<db->nDb );
84070 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
84071 pExpr->op = TK_NULL;
84076 ** Do an authorization check using the code and arguments given. Return
84077 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
84078 ** is returned, then the error count and error message in pParse are
84079 ** modified appropriately.
84081 SQLITE_PRIVATE int sqlite3AuthCheck(
84082 Parse *pParse,
84083 int code,
84084 const char *zArg1,
84085 const char *zArg2,
84086 const char *zArg3
84088 sqlite3 *db = pParse->db;
84089 int rc;
84091 /* Don't do any authorization checks if the database is initialising
84092 ** or if the parser is being invoked from within sqlite3_declare_vtab.
84094 if( db->init.busy || IN_DECLARE_VTAB ){
84095 return SQLITE_OK;
84098 if( db->xAuth==0 ){
84099 return SQLITE_OK;
84101 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
84102 if( rc==SQLITE_DENY ){
84103 sqlite3ErrorMsg(pParse, "not authorized");
84104 pParse->rc = SQLITE_AUTH;
84105 }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
84106 rc = SQLITE_DENY;
84107 sqliteAuthBadReturnCode(pParse);
84109 return rc;
84113 ** Push an authorization context. After this routine is called, the
84114 ** zArg3 argument to authorization callbacks will be zContext until
84115 ** popped. Or if pParse==0, this routine is a no-op.
84117 SQLITE_PRIVATE void sqlite3AuthContextPush(
84118 Parse *pParse,
84119 AuthContext *pContext,
84120 const char *zContext
84122 assert( pParse );
84123 pContext->pParse = pParse;
84124 pContext->zAuthContext = pParse->zAuthContext;
84125 pParse->zAuthContext = zContext;
84129 ** Pop an authorization context that was previously pushed
84130 ** by sqlite3AuthContextPush
84132 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
84133 if( pContext->pParse ){
84134 pContext->pParse->zAuthContext = pContext->zAuthContext;
84135 pContext->pParse = 0;
84139 #endif /* SQLITE_OMIT_AUTHORIZATION */
84141 /************** End of auth.c ************************************************/
84142 /************** Begin file build.c *******************************************/
84144 ** 2001 September 15
84146 ** The author disclaims copyright to this source code. In place of
84147 ** a legal notice, here is a blessing:
84149 ** May you do good and not evil.
84150 ** May you find forgiveness for yourself and forgive others.
84151 ** May you share freely, never taking more than you give.
84153 *************************************************************************
84154 ** This file contains C code routines that are called by the SQLite parser
84155 ** when syntax rules are reduced. The routines in this file handle the
84156 ** following kinds of SQL syntax:
84158 ** CREATE TABLE
84159 ** DROP TABLE
84160 ** CREATE INDEX
84161 ** DROP INDEX
84162 ** creating ID lists
84163 ** BEGIN TRANSACTION
84164 ** COMMIT
84165 ** ROLLBACK
84169 ** This routine is called when a new SQL statement is beginning to
84170 ** be parsed. Initialize the pParse structure as needed.
84172 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
84173 pParse->explain = (u8)explainFlag;
84174 pParse->nVar = 0;
84177 #ifndef SQLITE_OMIT_SHARED_CACHE
84179 ** The TableLock structure is only used by the sqlite3TableLock() and
84180 ** codeTableLocks() functions.
84182 struct TableLock {
84183 int iDb; /* The database containing the table to be locked */
84184 int iTab; /* The root page of the table to be locked */
84185 u8 isWriteLock; /* True for write lock. False for a read lock */
84186 const char *zName; /* Name of the table */
84190 ** Record the fact that we want to lock a table at run-time.
84192 ** The table to be locked has root page iTab and is found in database iDb.
84193 ** A read or a write lock can be taken depending on isWritelock.
84195 ** This routine just records the fact that the lock is desired. The
84196 ** code to make the lock occur is generated by a later call to
84197 ** codeTableLocks() which occurs during sqlite3FinishCoding().
84199 SQLITE_PRIVATE void sqlite3TableLock(
84200 Parse *pParse, /* Parsing context */
84201 int iDb, /* Index of the database containing the table to lock */
84202 int iTab, /* Root page number of the table to be locked */
84203 u8 isWriteLock, /* True for a write lock */
84204 const char *zName /* Name of the table to be locked */
84206 Parse *pToplevel = sqlite3ParseToplevel(pParse);
84207 int i;
84208 int nBytes;
84209 TableLock *p;
84210 assert( iDb>=0 );
84212 for(i=0; i<pToplevel->nTableLock; i++){
84213 p = &pToplevel->aTableLock[i];
84214 if( p->iDb==iDb && p->iTab==iTab ){
84215 p->isWriteLock = (p->isWriteLock || isWriteLock);
84216 return;
84220 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
84221 pToplevel->aTableLock =
84222 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
84223 if( pToplevel->aTableLock ){
84224 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
84225 p->iDb = iDb;
84226 p->iTab = iTab;
84227 p->isWriteLock = isWriteLock;
84228 p->zName = zName;
84229 }else{
84230 pToplevel->nTableLock = 0;
84231 pToplevel->db->mallocFailed = 1;
84236 ** Code an OP_TableLock instruction for each table locked by the
84237 ** statement (configured by calls to sqlite3TableLock()).
84239 static void codeTableLocks(Parse *pParse){
84240 int i;
84241 Vdbe *pVdbe;
84243 pVdbe = sqlite3GetVdbe(pParse);
84244 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
84246 for(i=0; i<pParse->nTableLock; i++){
84247 TableLock *p = &pParse->aTableLock[i];
84248 int p1 = p->iDb;
84249 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
84250 p->zName, P4_STATIC);
84253 #else
84254 #define codeTableLocks(x)
84255 #endif
84258 ** This routine is called after a single SQL statement has been
84259 ** parsed and a VDBE program to execute that statement has been
84260 ** prepared. This routine puts the finishing touches on the
84261 ** VDBE program and resets the pParse structure for the next
84262 ** parse.
84264 ** Note that if an error occurred, it might be the case that
84265 ** no VDBE code was generated.
84267 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
84268 sqlite3 *db;
84269 Vdbe *v;
84271 assert( pParse->pToplevel==0 );
84272 db = pParse->db;
84273 if( db->mallocFailed ) return;
84274 if( pParse->nested ) return;
84275 if( pParse->nErr ) return;
84277 /* Begin by generating some termination code at the end of the
84278 ** vdbe program
84280 v = sqlite3GetVdbe(pParse);
84281 assert( !pParse->isMultiWrite
84282 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
84283 if( v ){
84284 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
84285 sqlite3VdbeAddOp0(v, OP_Halt);
84287 /* The cookie mask contains one bit for each database file open.
84288 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
84289 ** set for each database that is used. Generate code to start a
84290 ** transaction on each used database and to verify the schema cookie
84291 ** on each used database.
84293 if( pParse->cookieGoto>0 ){
84294 yDbMask mask;
84295 int iDb, i, addr;
84296 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
84297 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
84298 if( (mask & pParse->cookieMask)==0 ) continue;
84299 sqlite3VdbeUsesBtree(v, iDb);
84300 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
84301 if( db->init.busy==0 ){
84302 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84303 sqlite3VdbeAddOp3(v, OP_VerifyCookie,
84304 iDb, pParse->cookieValue[iDb],
84305 db->aDb[iDb].pSchema->iGeneration);
84308 #ifndef SQLITE_OMIT_VIRTUALTABLE
84309 for(i=0; i<pParse->nVtabLock; i++){
84310 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
84311 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
84313 pParse->nVtabLock = 0;
84314 #endif
84316 /* Once all the cookies have been verified and transactions opened,
84317 ** obtain the required table-locks. This is a no-op unless the
84318 ** shared-cache feature is enabled.
84320 codeTableLocks(pParse);
84322 /* Initialize any AUTOINCREMENT data structures required.
84324 sqlite3AutoincrementBegin(pParse);
84326 /* Code constant expressions that where factored out of inner loops */
84327 addr = pParse->cookieGoto;
84328 if( pParse->pConstExpr ){
84329 ExprList *pEL = pParse->pConstExpr;
84330 pParse->cookieGoto = 0;
84331 for(i=0; i<pEL->nExpr; i++){
84332 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
84336 /* Finally, jump back to the beginning of the executable code. */
84337 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
84342 /* Get the VDBE program ready for execution
84344 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
84345 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
84346 /* A minimum of one cursor is required if autoincrement is used
84347 * See ticket [a696379c1f08866] */
84348 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
84349 sqlite3VdbeMakeReady(v, pParse);
84350 pParse->rc = SQLITE_DONE;
84351 pParse->colNamesSet = 0;
84352 }else{
84353 pParse->rc = SQLITE_ERROR;
84355 pParse->nTab = 0;
84356 pParse->nMem = 0;
84357 pParse->nSet = 0;
84358 pParse->nVar = 0;
84359 pParse->cookieMask = 0;
84360 pParse->cookieGoto = 0;
84364 ** Run the parser and code generator recursively in order to generate
84365 ** code for the SQL statement given onto the end of the pParse context
84366 ** currently under construction. When the parser is run recursively
84367 ** this way, the final OP_Halt is not appended and other initialization
84368 ** and finalization steps are omitted because those are handling by the
84369 ** outermost parser.
84371 ** Not everything is nestable. This facility is designed to permit
84372 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
84373 ** care if you decide to try to use this routine for some other purposes.
84375 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
84376 va_list ap;
84377 char *zSql;
84378 char *zErrMsg = 0;
84379 sqlite3 *db = pParse->db;
84380 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
84381 char saveBuf[SAVE_SZ];
84383 if( pParse->nErr ) return;
84384 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
84385 va_start(ap, zFormat);
84386 zSql = sqlite3VMPrintf(db, zFormat, ap);
84387 va_end(ap);
84388 if( zSql==0 ){
84389 return; /* A malloc must have failed */
84391 pParse->nested++;
84392 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
84393 memset(&pParse->nVar, 0, SAVE_SZ);
84394 sqlite3RunParser(pParse, zSql, &zErrMsg);
84395 sqlite3DbFree(db, zErrMsg);
84396 sqlite3DbFree(db, zSql);
84397 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
84398 pParse->nested--;
84402 ** Locate the in-memory structure that describes a particular database
84403 ** table given the name of that table and (optionally) the name of the
84404 ** database containing the table. Return NULL if not found.
84406 ** If zDatabase is 0, all databases are searched for the table and the
84407 ** first matching table is returned. (No checking for duplicate table
84408 ** names is done.) The search order is TEMP first, then MAIN, then any
84409 ** auxiliary databases added using the ATTACH command.
84411 ** See also sqlite3LocateTable().
84413 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
84414 Table *p = 0;
84415 int i;
84416 int nName;
84417 assert( zName!=0 );
84418 nName = sqlite3Strlen30(zName);
84419 /* All mutexes are required for schema access. Make sure we hold them. */
84420 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
84421 for(i=OMIT_TEMPDB; i<db->nDb; i++){
84422 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
84423 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
84424 assert( sqlite3SchemaMutexHeld(db, j, 0) );
84425 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
84426 if( p ) break;
84428 return p;
84432 ** Locate the in-memory structure that describes a particular database
84433 ** table given the name of that table and (optionally) the name of the
84434 ** database containing the table. Return NULL if not found. Also leave an
84435 ** error message in pParse->zErrMsg.
84437 ** The difference between this routine and sqlite3FindTable() is that this
84438 ** routine leaves an error message in pParse->zErrMsg where
84439 ** sqlite3FindTable() does not.
84441 SQLITE_PRIVATE Table *sqlite3LocateTable(
84442 Parse *pParse, /* context in which to report errors */
84443 int isView, /* True if looking for a VIEW rather than a TABLE */
84444 const char *zName, /* Name of the table we are looking for */
84445 const char *zDbase /* Name of the database. Might be NULL */
84447 Table *p;
84449 /* Read the database schema. If an error occurs, leave an error message
84450 ** and code in pParse and return NULL. */
84451 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84452 return 0;
84455 p = sqlite3FindTable(pParse->db, zName, zDbase);
84456 if( p==0 ){
84457 const char *zMsg = isView ? "no such view" : "no such table";
84458 if( zDbase ){
84459 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
84460 }else{
84461 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
84463 pParse->checkSchema = 1;
84465 return p;
84469 ** Locate the table identified by *p.
84471 ** This is a wrapper around sqlite3LocateTable(). The difference between
84472 ** sqlite3LocateTable() and this function is that this function restricts
84473 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
84474 ** non-NULL if it is part of a view or trigger program definition. See
84475 ** sqlite3FixSrcList() for details.
84477 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
84478 Parse *pParse,
84479 int isView,
84480 struct SrcList_item *p
84482 const char *zDb;
84483 assert( p->pSchema==0 || p->zDatabase==0 );
84484 if( p->pSchema ){
84485 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
84486 zDb = pParse->db->aDb[iDb].zName;
84487 }else{
84488 zDb = p->zDatabase;
84490 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
84494 ** Locate the in-memory structure that describes
84495 ** a particular index given the name of that index
84496 ** and the name of the database that contains the index.
84497 ** Return NULL if not found.
84499 ** If zDatabase is 0, all databases are searched for the
84500 ** table and the first matching index is returned. (No checking
84501 ** for duplicate index names is done.) The search order is
84502 ** TEMP first, then MAIN, then any auxiliary databases added
84503 ** using the ATTACH command.
84505 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
84506 Index *p = 0;
84507 int i;
84508 int nName = sqlite3Strlen30(zName);
84509 /* All mutexes are required for schema access. Make sure we hold them. */
84510 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
84511 for(i=OMIT_TEMPDB; i<db->nDb; i++){
84512 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
84513 Schema *pSchema = db->aDb[j].pSchema;
84514 assert( pSchema );
84515 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
84516 assert( sqlite3SchemaMutexHeld(db, j, 0) );
84517 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
84518 if( p ) break;
84520 return p;
84524 ** Reclaim the memory used by an index
84526 static void freeIndex(sqlite3 *db, Index *p){
84527 #ifndef SQLITE_OMIT_ANALYZE
84528 sqlite3DeleteIndexSamples(db, p);
84529 #endif
84530 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
84531 sqlite3ExprDelete(db, p->pPartIdxWhere);
84532 sqlite3DbFree(db, p->zColAff);
84533 if( p->isResized ) sqlite3DbFree(db, p->azColl);
84534 sqlite3DbFree(db, p);
84538 ** For the index called zIdxName which is found in the database iDb,
84539 ** unlike that index from its Table then remove the index from
84540 ** the index hash table and free all memory structures associated
84541 ** with the index.
84543 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
84544 Index *pIndex;
84545 int len;
84546 Hash *pHash;
84548 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84549 pHash = &db->aDb[iDb].pSchema->idxHash;
84550 len = sqlite3Strlen30(zIdxName);
84551 pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
84552 if( ALWAYS(pIndex) ){
84553 if( pIndex->pTable->pIndex==pIndex ){
84554 pIndex->pTable->pIndex = pIndex->pNext;
84555 }else{
84556 Index *p;
84557 /* Justification of ALWAYS(); The index must be on the list of
84558 ** indices. */
84559 p = pIndex->pTable->pIndex;
84560 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
84561 if( ALWAYS(p && p->pNext==pIndex) ){
84562 p->pNext = pIndex->pNext;
84565 freeIndex(db, pIndex);
84567 db->flags |= SQLITE_InternChanges;
84571 ** Look through the list of open database files in db->aDb[] and if
84572 ** any have been closed, remove them from the list. Reallocate the
84573 ** db->aDb[] structure to a smaller size, if possible.
84575 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
84576 ** are never candidates for being collapsed.
84578 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
84579 int i, j;
84580 for(i=j=2; i<db->nDb; i++){
84581 struct Db *pDb = &db->aDb[i];
84582 if( pDb->pBt==0 ){
84583 sqlite3DbFree(db, pDb->zName);
84584 pDb->zName = 0;
84585 continue;
84587 if( j<i ){
84588 db->aDb[j] = db->aDb[i];
84590 j++;
84592 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
84593 db->nDb = j;
84594 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
84595 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
84596 sqlite3DbFree(db, db->aDb);
84597 db->aDb = db->aDbStatic;
84602 ** Reset the schema for the database at index iDb. Also reset the
84603 ** TEMP schema.
84605 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
84606 Db *pDb;
84607 assert( iDb<db->nDb );
84609 /* Case 1: Reset the single schema identified by iDb */
84610 pDb = &db->aDb[iDb];
84611 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84612 assert( pDb->pSchema!=0 );
84613 sqlite3SchemaClear(pDb->pSchema);
84615 /* If any database other than TEMP is reset, then also reset TEMP
84616 ** since TEMP might be holding triggers that reference tables in the
84617 ** other database.
84619 if( iDb!=1 ){
84620 pDb = &db->aDb[1];
84621 assert( pDb->pSchema!=0 );
84622 sqlite3SchemaClear(pDb->pSchema);
84624 return;
84628 ** Erase all schema information from all attached databases (including
84629 ** "main" and "temp") for a single database connection.
84631 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
84632 int i;
84633 sqlite3BtreeEnterAll(db);
84634 for(i=0; i<db->nDb; i++){
84635 Db *pDb = &db->aDb[i];
84636 if( pDb->pSchema ){
84637 sqlite3SchemaClear(pDb->pSchema);
84640 db->flags &= ~SQLITE_InternChanges;
84641 sqlite3VtabUnlockList(db);
84642 sqlite3BtreeLeaveAll(db);
84643 sqlite3CollapseDatabaseArray(db);
84647 ** This routine is called when a commit occurs.
84649 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
84650 db->flags &= ~SQLITE_InternChanges;
84654 ** Delete memory allocated for the column names of a table or view (the
84655 ** Table.aCol[] array).
84657 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
84658 int i;
84659 Column *pCol;
84660 assert( pTable!=0 );
84661 if( (pCol = pTable->aCol)!=0 ){
84662 for(i=0; i<pTable->nCol; i++, pCol++){
84663 sqlite3DbFree(db, pCol->zName);
84664 sqlite3ExprDelete(db, pCol->pDflt);
84665 sqlite3DbFree(db, pCol->zDflt);
84666 sqlite3DbFree(db, pCol->zType);
84667 sqlite3DbFree(db, pCol->zColl);
84669 sqlite3DbFree(db, pTable->aCol);
84674 ** Remove the memory data structures associated with the given
84675 ** Table. No changes are made to disk by this routine.
84677 ** This routine just deletes the data structure. It does not unlink
84678 ** the table data structure from the hash table. But it does destroy
84679 ** memory structures of the indices and foreign keys associated with
84680 ** the table.
84682 ** The db parameter is optional. It is needed if the Table object
84683 ** contains lookaside memory. (Table objects in the schema do not use
84684 ** lookaside memory, but some ephemeral Table objects do.) Or the
84685 ** db parameter can be used with db->pnBytesFreed to measure the memory
84686 ** used by the Table object.
84688 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
84689 Index *pIndex, *pNext;
84690 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
84692 assert( !pTable || pTable->nRef>0 );
84694 /* Do not delete the table until the reference count reaches zero. */
84695 if( !pTable ) return;
84696 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
84698 /* Record the number of outstanding lookaside allocations in schema Tables
84699 ** prior to doing any free() operations. Since schema Tables do not use
84700 ** lookaside, this number should not change. */
84701 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
84702 db->lookaside.nOut : 0 );
84704 /* Delete all indices associated with this table. */
84705 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
84706 pNext = pIndex->pNext;
84707 assert( pIndex->pSchema==pTable->pSchema );
84708 if( !db || db->pnBytesFreed==0 ){
84709 char *zName = pIndex->zName;
84710 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
84711 &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
84713 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
84714 assert( pOld==pIndex || pOld==0 );
84716 freeIndex(db, pIndex);
84719 /* Delete any foreign keys attached to this table. */
84720 sqlite3FkDelete(db, pTable);
84722 /* Delete the Table structure itself.
84724 sqliteDeleteColumnNames(db, pTable);
84725 sqlite3DbFree(db, pTable->zName);
84726 sqlite3DbFree(db, pTable->zColAff);
84727 sqlite3SelectDelete(db, pTable->pSelect);
84728 #ifndef SQLITE_OMIT_CHECK
84729 sqlite3ExprListDelete(db, pTable->pCheck);
84730 #endif
84731 #ifndef SQLITE_OMIT_VIRTUALTABLE
84732 sqlite3VtabClear(db, pTable);
84733 #endif
84734 sqlite3DbFree(db, pTable);
84736 /* Verify that no lookaside memory was used by schema tables */
84737 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
84741 ** Unlink the given table from the hash tables and the delete the
84742 ** table structure with all its indices and foreign keys.
84744 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
84745 Table *p;
84746 Db *pDb;
84748 assert( db!=0 );
84749 assert( iDb>=0 && iDb<db->nDb );
84750 assert( zTabName );
84751 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84752 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
84753 pDb = &db->aDb[iDb];
84754 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
84755 sqlite3Strlen30(zTabName),0);
84756 sqlite3DeleteTable(db, p);
84757 db->flags |= SQLITE_InternChanges;
84761 ** Given a token, return a string that consists of the text of that
84762 ** token. Space to hold the returned string
84763 ** is obtained from sqliteMalloc() and must be freed by the calling
84764 ** function.
84766 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
84767 ** surround the body of the token are removed.
84769 ** Tokens are often just pointers into the original SQL text and so
84770 ** are not \000 terminated and are not persistent. The returned string
84771 ** is \000 terminated and is persistent.
84773 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
84774 char *zName;
84775 if( pName ){
84776 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
84777 sqlite3Dequote(zName);
84778 }else{
84779 zName = 0;
84781 return zName;
84785 ** Open the sqlite_master table stored in database number iDb for
84786 ** writing. The table is opened using cursor 0.
84788 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
84789 Vdbe *v = sqlite3GetVdbe(p);
84790 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
84791 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
84792 if( p->nTab==0 ){
84793 p->nTab = 1;
84798 ** Parameter zName points to a nul-terminated buffer containing the name
84799 ** of a database ("main", "temp" or the name of an attached db). This
84800 ** function returns the index of the named database in db->aDb[], or
84801 ** -1 if the named db cannot be found.
84803 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
84804 int i = -1; /* Database number */
84805 if( zName ){
84806 Db *pDb;
84807 int n = sqlite3Strlen30(zName);
84808 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
84809 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
84810 0==sqlite3StrICmp(pDb->zName, zName) ){
84811 break;
84815 return i;
84819 ** The token *pName contains the name of a database (either "main" or
84820 ** "temp" or the name of an attached db). This routine returns the
84821 ** index of the named database in db->aDb[], or -1 if the named db
84822 ** does not exist.
84824 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
84825 int i; /* Database number */
84826 char *zName; /* Name we are searching for */
84827 zName = sqlite3NameFromToken(db, pName);
84828 i = sqlite3FindDbName(db, zName);
84829 sqlite3DbFree(db, zName);
84830 return i;
84833 /* The table or view or trigger name is passed to this routine via tokens
84834 ** pName1 and pName2. If the table name was fully qualified, for example:
84836 ** CREATE TABLE xxx.yyy (...);
84838 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
84839 ** the table name is not fully qualified, i.e.:
84841 ** CREATE TABLE yyy(...);
84843 ** Then pName1 is set to "yyy" and pName2 is "".
84845 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
84846 ** pName2) that stores the unqualified table name. The index of the
84847 ** database "xxx" is returned.
84849 SQLITE_PRIVATE int sqlite3TwoPartName(
84850 Parse *pParse, /* Parsing and code generating context */
84851 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
84852 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
84853 Token **pUnqual /* Write the unqualified object name here */
84855 int iDb; /* Database holding the object */
84856 sqlite3 *db = pParse->db;
84858 if( ALWAYS(pName2!=0) && pName2->n>0 ){
84859 if( db->init.busy ) {
84860 sqlite3ErrorMsg(pParse, "corrupt database");
84861 pParse->nErr++;
84862 return -1;
84864 *pUnqual = pName2;
84865 iDb = sqlite3FindDb(db, pName1);
84866 if( iDb<0 ){
84867 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
84868 pParse->nErr++;
84869 return -1;
84871 }else{
84872 assert( db->init.iDb==0 || db->init.busy );
84873 iDb = db->init.iDb;
84874 *pUnqual = pName1;
84876 return iDb;
84880 ** This routine is used to check if the UTF-8 string zName is a legal
84881 ** unqualified name for a new schema object (table, index, view or
84882 ** trigger). All names are legal except those that begin with the string
84883 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
84884 ** is reserved for internal use.
84886 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
84887 if( !pParse->db->init.busy && pParse->nested==0
84888 && (pParse->db->flags & SQLITE_WriteSchema)==0
84889 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
84890 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
84891 return SQLITE_ERROR;
84893 return SQLITE_OK;
84897 ** Return the PRIMARY KEY index of a table
84899 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
84900 Index *p;
84901 for(p=pTab->pIndex; p && p->autoIndex!=2; p=p->pNext){}
84902 return p;
84906 ** Return the column of index pIdx that corresponds to table
84907 ** column iCol. Return -1 if not found.
84909 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
84910 int i;
84911 for(i=0; i<pIdx->nColumn; i++){
84912 if( iCol==pIdx->aiColumn[i] ) return i;
84914 return -1;
84918 ** Begin constructing a new table representation in memory. This is
84919 ** the first of several action routines that get called in response
84920 ** to a CREATE TABLE statement. In particular, this routine is called
84921 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
84922 ** flag is true if the table should be stored in the auxiliary database
84923 ** file instead of in the main database file. This is normally the case
84924 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
84925 ** CREATE and TABLE.
84927 ** The new table record is initialized and put in pParse->pNewTable.
84928 ** As more of the CREATE TABLE statement is parsed, additional action
84929 ** routines will be called to add more information to this record.
84930 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
84931 ** is called to complete the construction of the new table record.
84933 SQLITE_PRIVATE void sqlite3StartTable(
84934 Parse *pParse, /* Parser context */
84935 Token *pName1, /* First part of the name of the table or view */
84936 Token *pName2, /* Second part of the name of the table or view */
84937 int isTemp, /* True if this is a TEMP table */
84938 int isView, /* True if this is a VIEW */
84939 int isVirtual, /* True if this is a VIRTUAL table */
84940 int noErr /* Do nothing if table already exists */
84942 Table *pTable;
84943 char *zName = 0; /* The name of the new table */
84944 sqlite3 *db = pParse->db;
84945 Vdbe *v;
84946 int iDb; /* Database number to create the table in */
84947 Token *pName; /* Unqualified name of the table to create */
84949 /* The table or view name to create is passed to this routine via tokens
84950 ** pName1 and pName2. If the table name was fully qualified, for example:
84952 ** CREATE TABLE xxx.yyy (...);
84954 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
84955 ** the table name is not fully qualified, i.e.:
84957 ** CREATE TABLE yyy(...);
84959 ** Then pName1 is set to "yyy" and pName2 is "".
84961 ** The call below sets the pName pointer to point at the token (pName1 or
84962 ** pName2) that stores the unqualified table name. The variable iDb is
84963 ** set to the index of the database that the table or view is to be
84964 ** created in.
84966 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84967 if( iDb<0 ) return;
84968 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
84969 /* If creating a temp table, the name may not be qualified. Unless
84970 ** the database name is "temp" anyway. */
84971 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
84972 return;
84974 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
84976 pParse->sNameToken = *pName;
84977 zName = sqlite3NameFromToken(db, pName);
84978 if( zName==0 ) return;
84979 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
84980 goto begin_table_error;
84982 if( db->init.iDb==1 ) isTemp = 1;
84983 #ifndef SQLITE_OMIT_AUTHORIZATION
84984 assert( (isTemp & 1)==isTemp );
84986 int code;
84987 char *zDb = db->aDb[iDb].zName;
84988 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
84989 goto begin_table_error;
84991 if( isView ){
84992 if( !OMIT_TEMPDB && isTemp ){
84993 code = SQLITE_CREATE_TEMP_VIEW;
84994 }else{
84995 code = SQLITE_CREATE_VIEW;
84997 }else{
84998 if( !OMIT_TEMPDB && isTemp ){
84999 code = SQLITE_CREATE_TEMP_TABLE;
85000 }else{
85001 code = SQLITE_CREATE_TABLE;
85004 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
85005 goto begin_table_error;
85008 #endif
85010 /* Make sure the new table name does not collide with an existing
85011 ** index or table name in the same database. Issue an error message if
85012 ** it does. The exception is if the statement being parsed was passed
85013 ** to an sqlite3_declare_vtab() call. In that case only the column names
85014 ** and types will be used, so there is no need to test for namespace
85015 ** collisions.
85017 if( !IN_DECLARE_VTAB ){
85018 char *zDb = db->aDb[iDb].zName;
85019 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85020 goto begin_table_error;
85022 pTable = sqlite3FindTable(db, zName, zDb);
85023 if( pTable ){
85024 if( !noErr ){
85025 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
85026 }else{
85027 assert( !db->init.busy );
85028 sqlite3CodeVerifySchema(pParse, iDb);
85030 goto begin_table_error;
85032 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
85033 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
85034 goto begin_table_error;
85038 pTable = sqlite3DbMallocZero(db, sizeof(Table));
85039 if( pTable==0 ){
85040 db->mallocFailed = 1;
85041 pParse->rc = SQLITE_NOMEM;
85042 pParse->nErr++;
85043 goto begin_table_error;
85045 pTable->zName = zName;
85046 pTable->iPKey = -1;
85047 pTable->pSchema = db->aDb[iDb].pSchema;
85048 pTable->nRef = 1;
85049 pTable->nRowEst = 1048576;
85050 assert( pParse->pNewTable==0 );
85051 pParse->pNewTable = pTable;
85053 /* If this is the magic sqlite_sequence table used by autoincrement,
85054 ** then record a pointer to this table in the main database structure
85055 ** so that INSERT can find the table easily.
85057 #ifndef SQLITE_OMIT_AUTOINCREMENT
85058 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
85059 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85060 pTable->pSchema->pSeqTab = pTable;
85062 #endif
85064 /* Begin generating the code that will insert the table record into
85065 ** the SQLITE_MASTER table. Note in particular that we must go ahead
85066 ** and allocate the record number for the table entry now. Before any
85067 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
85068 ** indices to be created and the table record must come before the
85069 ** indices. Hence, the record number for the table must be allocated
85070 ** now.
85072 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
85073 int j1;
85074 int fileFormat;
85075 int reg1, reg2, reg3;
85076 sqlite3BeginWriteOperation(pParse, 0, iDb);
85078 #ifndef SQLITE_OMIT_VIRTUALTABLE
85079 if( isVirtual ){
85080 sqlite3VdbeAddOp0(v, OP_VBegin);
85082 #endif
85084 /* If the file format and encoding in the database have not been set,
85085 ** set them now.
85087 reg1 = pParse->regRowid = ++pParse->nMem;
85088 reg2 = pParse->regRoot = ++pParse->nMem;
85089 reg3 = ++pParse->nMem;
85090 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
85091 sqlite3VdbeUsesBtree(v, iDb);
85092 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
85093 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
85094 1 : SQLITE_MAX_FILE_FORMAT;
85095 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
85096 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
85097 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
85098 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
85099 sqlite3VdbeJumpHere(v, j1);
85101 /* This just creates a place-holder record in the sqlite_master table.
85102 ** The record created does not contain anything yet. It will be replaced
85103 ** by the real entry in code generated at sqlite3EndTable().
85105 ** The rowid for the new entry is left in register pParse->regRowid.
85106 ** The root page number of the new table is left in reg pParse->regRoot.
85107 ** The rowid and root page number values are needed by the code that
85108 ** sqlite3EndTable will generate.
85110 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
85111 if( isView || isVirtual ){
85112 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
85113 }else
85114 #endif
85116 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
85118 sqlite3OpenMasterTable(pParse, iDb);
85119 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
85120 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
85121 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
85122 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
85123 sqlite3VdbeAddOp0(v, OP_Close);
85126 /* Normal (non-error) return. */
85127 return;
85129 /* If an error occurs, we jump here */
85130 begin_table_error:
85131 sqlite3DbFree(db, zName);
85132 return;
85136 ** This macro is used to compare two strings in a case-insensitive manner.
85137 ** It is slightly faster than calling sqlite3StrICmp() directly, but
85138 ** produces larger code.
85140 ** WARNING: This macro is not compatible with the strcmp() family. It
85141 ** returns true if the two strings are equal, otherwise false.
85143 #define STRICMP(x, y) (\
85144 sqlite3UpperToLower[*(unsigned char *)(x)]== \
85145 sqlite3UpperToLower[*(unsigned char *)(y)] \
85146 && sqlite3StrICmp((x)+1,(y)+1)==0 )
85149 ** Add a new column to the table currently being constructed.
85151 ** The parser calls this routine once for each column declaration
85152 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
85153 ** first to get things going. Then this routine is called for each
85154 ** column.
85156 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
85157 Table *p;
85158 int i;
85159 char *z;
85160 Column *pCol;
85161 sqlite3 *db = pParse->db;
85162 if( (p = pParse->pNewTable)==0 ) return;
85163 #if SQLITE_MAX_COLUMN
85164 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
85165 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
85166 return;
85168 #endif
85169 z = sqlite3NameFromToken(db, pName);
85170 if( z==0 ) return;
85171 for(i=0; i<p->nCol; i++){
85172 if( STRICMP(z, p->aCol[i].zName) ){
85173 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
85174 sqlite3DbFree(db, z);
85175 return;
85178 if( (p->nCol & 0x7)==0 ){
85179 Column *aNew;
85180 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
85181 if( aNew==0 ){
85182 sqlite3DbFree(db, z);
85183 return;
85185 p->aCol = aNew;
85187 pCol = &p->aCol[p->nCol];
85188 memset(pCol, 0, sizeof(p->aCol[0]));
85189 pCol->zName = z;
85191 /* If there is no type specified, columns have the default affinity
85192 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
85193 ** be called next to set pCol->affinity correctly.
85195 pCol->affinity = SQLITE_AFF_NONE;
85196 pCol->szEst = 1;
85197 p->nCol++;
85201 ** This routine is called by the parser while in the middle of
85202 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
85203 ** been seen on a column. This routine sets the notNull flag on
85204 ** the column currently under construction.
85206 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
85207 Table *p;
85208 p = pParse->pNewTable;
85209 if( p==0 || NEVER(p->nCol<1) ) return;
85210 p->aCol[p->nCol-1].notNull = (u8)onError;
85214 ** Scan the column type name zType (length nType) and return the
85215 ** associated affinity type.
85217 ** This routine does a case-independent search of zType for the
85218 ** substrings in the following table. If one of the substrings is
85219 ** found, the corresponding affinity is returned. If zType contains
85220 ** more than one of the substrings, entries toward the top of
85221 ** the table take priority. For example, if zType is 'BLOBINT',
85222 ** SQLITE_AFF_INTEGER is returned.
85224 ** Substring | Affinity
85225 ** --------------------------------
85226 ** 'INT' | SQLITE_AFF_INTEGER
85227 ** 'CHAR' | SQLITE_AFF_TEXT
85228 ** 'CLOB' | SQLITE_AFF_TEXT
85229 ** 'TEXT' | SQLITE_AFF_TEXT
85230 ** 'BLOB' | SQLITE_AFF_NONE
85231 ** 'REAL' | SQLITE_AFF_REAL
85232 ** 'FLOA' | SQLITE_AFF_REAL
85233 ** 'DOUB' | SQLITE_AFF_REAL
85235 ** If none of the substrings in the above table are found,
85236 ** SQLITE_AFF_NUMERIC is returned.
85238 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
85239 u32 h = 0;
85240 char aff = SQLITE_AFF_NUMERIC;
85241 const char *zChar = 0;
85243 if( zIn==0 ) return aff;
85244 while( zIn[0] ){
85245 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
85246 zIn++;
85247 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
85248 aff = SQLITE_AFF_TEXT;
85249 zChar = zIn;
85250 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
85251 aff = SQLITE_AFF_TEXT;
85252 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
85253 aff = SQLITE_AFF_TEXT;
85254 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
85255 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
85256 aff = SQLITE_AFF_NONE;
85257 if( zIn[0]=='(' ) zChar = zIn;
85258 #ifndef SQLITE_OMIT_FLOATING_POINT
85259 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
85260 && aff==SQLITE_AFF_NUMERIC ){
85261 aff = SQLITE_AFF_REAL;
85262 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
85263 && aff==SQLITE_AFF_NUMERIC ){
85264 aff = SQLITE_AFF_REAL;
85265 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
85266 && aff==SQLITE_AFF_NUMERIC ){
85267 aff = SQLITE_AFF_REAL;
85268 #endif
85269 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
85270 aff = SQLITE_AFF_INTEGER;
85271 break;
85275 /* If pszEst is not NULL, store an estimate of the field size. The
85276 ** estimate is scaled so that the size of an integer is 1. */
85277 if( pszEst ){
85278 *pszEst = 1; /* default size is approx 4 bytes */
85279 if( aff<=SQLITE_AFF_NONE ){
85280 if( zChar ){
85281 while( zChar[0] ){
85282 if( sqlite3Isdigit(zChar[0]) ){
85283 int v = 0;
85284 sqlite3GetInt32(zChar, &v);
85285 v = v/4 + 1;
85286 if( v>255 ) v = 255;
85287 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
85288 break;
85290 zChar++;
85292 }else{
85293 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
85297 return aff;
85301 ** This routine is called by the parser while in the middle of
85302 ** parsing a CREATE TABLE statement. The pFirst token is the first
85303 ** token in the sequence of tokens that describe the type of the
85304 ** column currently under construction. pLast is the last token
85305 ** in the sequence. Use this information to construct a string
85306 ** that contains the typename of the column and store that string
85307 ** in zType.
85309 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
85310 Table *p;
85311 Column *pCol;
85313 p = pParse->pNewTable;
85314 if( p==0 || NEVER(p->nCol<1) ) return;
85315 pCol = &p->aCol[p->nCol-1];
85316 assert( pCol->zType==0 );
85317 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
85318 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
85322 ** The expression is the default value for the most recently added column
85323 ** of the table currently under construction.
85325 ** Default value expressions must be constant. Raise an exception if this
85326 ** is not the case.
85328 ** This routine is called by the parser while in the middle of
85329 ** parsing a CREATE TABLE statement.
85331 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
85332 Table *p;
85333 Column *pCol;
85334 sqlite3 *db = pParse->db;
85335 p = pParse->pNewTable;
85336 if( p!=0 ){
85337 pCol = &(p->aCol[p->nCol-1]);
85338 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
85339 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
85340 pCol->zName);
85341 }else{
85342 /* A copy of pExpr is used instead of the original, as pExpr contains
85343 ** tokens that point to volatile memory. The 'span' of the expression
85344 ** is required by pragma table_info.
85346 sqlite3ExprDelete(db, pCol->pDflt);
85347 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
85348 sqlite3DbFree(db, pCol->zDflt);
85349 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
85350 (int)(pSpan->zEnd - pSpan->zStart));
85353 sqlite3ExprDelete(db, pSpan->pExpr);
85357 ** Designate the PRIMARY KEY for the table. pList is a list of names
85358 ** of columns that form the primary key. If pList is NULL, then the
85359 ** most recently added column of the table is the primary key.
85361 ** A table can have at most one primary key. If the table already has
85362 ** a primary key (and this is the second primary key) then create an
85363 ** error.
85365 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
85366 ** then we will try to use that column as the rowid. Set the Table.iPKey
85367 ** field of the table under construction to be the index of the
85368 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
85369 ** no INTEGER PRIMARY KEY.
85371 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
85372 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
85374 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
85375 Parse *pParse, /* Parsing context */
85376 ExprList *pList, /* List of field names to be indexed */
85377 int onError, /* What to do with a uniqueness conflict */
85378 int autoInc, /* True if the AUTOINCREMENT keyword is present */
85379 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
85381 Table *pTab = pParse->pNewTable;
85382 char *zType = 0;
85383 int iCol = -1, i;
85384 int nTerm;
85385 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
85386 if( pTab->tabFlags & TF_HasPrimaryKey ){
85387 sqlite3ErrorMsg(pParse,
85388 "table \"%s\" has more than one primary key", pTab->zName);
85389 goto primary_key_exit;
85391 pTab->tabFlags |= TF_HasPrimaryKey;
85392 if( pList==0 ){
85393 iCol = pTab->nCol - 1;
85394 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
85395 zType = pTab->aCol[iCol].zType;
85396 nTerm = 1;
85397 }else{
85398 nTerm = pList->nExpr;
85399 for(i=0; i<nTerm; i++){
85400 for(iCol=0; iCol<pTab->nCol; iCol++){
85401 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
85402 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
85403 zType = pTab->aCol[iCol].zType;
85404 break;
85409 if( nTerm==1
85410 && zType && sqlite3StrICmp(zType, "INTEGER")==0
85411 && sortOrder==SQLITE_SO_ASC
85413 pTab->iPKey = iCol;
85414 pTab->keyConf = (u8)onError;
85415 assert( autoInc==0 || autoInc==1 );
85416 pTab->tabFlags |= autoInc*TF_Autoincrement;
85417 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
85418 }else if( autoInc ){
85419 #ifndef SQLITE_OMIT_AUTOINCREMENT
85420 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
85421 "INTEGER PRIMARY KEY");
85422 #endif
85423 }else{
85424 Vdbe *v = pParse->pVdbe;
85425 Index *p;
85426 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
85427 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
85428 0, sortOrder, 0);
85429 if( p ){
85430 p->autoIndex = 2;
85431 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
85433 pList = 0;
85436 primary_key_exit:
85437 sqlite3ExprListDelete(pParse->db, pList);
85438 return;
85442 ** Add a new CHECK constraint to the table currently under construction.
85444 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
85445 Parse *pParse, /* Parsing context */
85446 Expr *pCheckExpr /* The check expression */
85448 #ifndef SQLITE_OMIT_CHECK
85449 Table *pTab = pParse->pNewTable;
85450 if( pTab && !IN_DECLARE_VTAB ){
85451 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
85452 if( pParse->constraintName.n ){
85453 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
85455 }else
85456 #endif
85458 sqlite3ExprDelete(pParse->db, pCheckExpr);
85463 ** Set the collation function of the most recently parsed table column
85464 ** to the CollSeq given.
85466 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
85467 Table *p;
85468 int i;
85469 char *zColl; /* Dequoted name of collation sequence */
85470 sqlite3 *db;
85472 if( (p = pParse->pNewTable)==0 ) return;
85473 i = p->nCol-1;
85474 db = pParse->db;
85475 zColl = sqlite3NameFromToken(db, pToken);
85476 if( !zColl ) return;
85478 if( sqlite3LocateCollSeq(pParse, zColl) ){
85479 Index *pIdx;
85480 sqlite3DbFree(db, p->aCol[i].zColl);
85481 p->aCol[i].zColl = zColl;
85483 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
85484 ** then an index may have been created on this column before the
85485 ** collation type was added. Correct this if it is the case.
85487 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
85488 assert( pIdx->nKeyCol==1 );
85489 if( pIdx->aiColumn[0]==i ){
85490 pIdx->azColl[0] = p->aCol[i].zColl;
85493 }else{
85494 sqlite3DbFree(db, zColl);
85499 ** This function returns the collation sequence for database native text
85500 ** encoding identified by the string zName, length nName.
85502 ** If the requested collation sequence is not available, or not available
85503 ** in the database native encoding, the collation factory is invoked to
85504 ** request it. If the collation factory does not supply such a sequence,
85505 ** and the sequence is available in another text encoding, then that is
85506 ** returned instead.
85508 ** If no versions of the requested collations sequence are available, or
85509 ** another error occurs, NULL is returned and an error message written into
85510 ** pParse.
85512 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
85513 ** invokes the collation factory if the named collation cannot be found
85514 ** and generates an error message.
85516 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
85518 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
85519 sqlite3 *db = pParse->db;
85520 u8 enc = ENC(db);
85521 u8 initbusy = db->init.busy;
85522 CollSeq *pColl;
85524 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
85525 if( !initbusy && (!pColl || !pColl->xCmp) ){
85526 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
85529 return pColl;
85534 ** Generate code that will increment the schema cookie.
85536 ** The schema cookie is used to determine when the schema for the
85537 ** database changes. After each schema change, the cookie value
85538 ** changes. When a process first reads the schema it records the
85539 ** cookie. Thereafter, whenever it goes to access the database,
85540 ** it checks the cookie to make sure the schema has not changed
85541 ** since it was last read.
85543 ** This plan is not completely bullet-proof. It is possible for
85544 ** the schema to change multiple times and for the cookie to be
85545 ** set back to prior value. But schema changes are infrequent
85546 ** and the probability of hitting the same cookie value is only
85547 ** 1 chance in 2^32. So we're safe enough.
85549 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
85550 int r1 = sqlite3GetTempReg(pParse);
85551 sqlite3 *db = pParse->db;
85552 Vdbe *v = pParse->pVdbe;
85553 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85554 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
85555 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
85556 sqlite3ReleaseTempReg(pParse, r1);
85560 ** Measure the number of characters needed to output the given
85561 ** identifier. The number returned includes any quotes used
85562 ** but does not include the null terminator.
85564 ** The estimate is conservative. It might be larger that what is
85565 ** really needed.
85567 static int identLength(const char *z){
85568 int n;
85569 for(n=0; *z; n++, z++){
85570 if( *z=='"' ){ n++; }
85572 return n + 2;
85576 ** The first parameter is a pointer to an output buffer. The second
85577 ** parameter is a pointer to an integer that contains the offset at
85578 ** which to write into the output buffer. This function copies the
85579 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
85580 ** to the specified offset in the buffer and updates *pIdx to refer
85581 ** to the first byte after the last byte written before returning.
85583 ** If the string zSignedIdent consists entirely of alpha-numeric
85584 ** characters, does not begin with a digit and is not an SQL keyword,
85585 ** then it is copied to the output buffer exactly as it is. Otherwise,
85586 ** it is quoted using double-quotes.
85588 static void identPut(char *z, int *pIdx, char *zSignedIdent){
85589 unsigned char *zIdent = (unsigned char*)zSignedIdent;
85590 int i, j, needQuote;
85591 i = *pIdx;
85593 for(j=0; zIdent[j]; j++){
85594 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
85596 needQuote = sqlite3Isdigit(zIdent[0])
85597 || sqlite3KeywordCode(zIdent, j)!=TK_ID
85598 || zIdent[j]!=0
85599 || j==0;
85601 if( needQuote ) z[i++] = '"';
85602 for(j=0; zIdent[j]; j++){
85603 z[i++] = zIdent[j];
85604 if( zIdent[j]=='"' ) z[i++] = '"';
85606 if( needQuote ) z[i++] = '"';
85607 z[i] = 0;
85608 *pIdx = i;
85612 ** Generate a CREATE TABLE statement appropriate for the given
85613 ** table. Memory to hold the text of the statement is obtained
85614 ** from sqliteMalloc() and must be freed by the calling function.
85616 static char *createTableStmt(sqlite3 *db, Table *p){
85617 int i, k, n;
85618 char *zStmt;
85619 char *zSep, *zSep2, *zEnd;
85620 Column *pCol;
85621 n = 0;
85622 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
85623 n += identLength(pCol->zName) + 5;
85625 n += identLength(p->zName);
85626 if( n<50 ){
85627 zSep = "";
85628 zSep2 = ",";
85629 zEnd = ")";
85630 }else{
85631 zSep = "\n ";
85632 zSep2 = ",\n ";
85633 zEnd = "\n)";
85635 n += 35 + 6*p->nCol;
85636 zStmt = sqlite3DbMallocRaw(0, n);
85637 if( zStmt==0 ){
85638 db->mallocFailed = 1;
85639 return 0;
85641 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
85642 k = sqlite3Strlen30(zStmt);
85643 identPut(zStmt, &k, p->zName);
85644 zStmt[k++] = '(';
85645 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
85646 static const char * const azType[] = {
85647 /* SQLITE_AFF_TEXT */ " TEXT",
85648 /* SQLITE_AFF_NONE */ "",
85649 /* SQLITE_AFF_NUMERIC */ " NUM",
85650 /* SQLITE_AFF_INTEGER */ " INT",
85651 /* SQLITE_AFF_REAL */ " REAL"
85653 int len;
85654 const char *zType;
85656 sqlite3_snprintf(n-k, &zStmt[k], zSep);
85657 k += sqlite3Strlen30(&zStmt[k]);
85658 zSep = zSep2;
85659 identPut(zStmt, &k, pCol->zName);
85660 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
85661 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
85662 testcase( pCol->affinity==SQLITE_AFF_TEXT );
85663 testcase( pCol->affinity==SQLITE_AFF_NONE );
85664 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
85665 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
85666 testcase( pCol->affinity==SQLITE_AFF_REAL );
85668 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
85669 len = sqlite3Strlen30(zType);
85670 assert( pCol->affinity==SQLITE_AFF_NONE
85671 || pCol->affinity==sqlite3AffinityType(zType, 0) );
85672 memcpy(&zStmt[k], zType, len);
85673 k += len;
85674 assert( k<=n );
85676 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
85677 return zStmt;
85681 ** Resize an Index object to hold N columns total. Return SQLITE_OK
85682 ** on success and SQLITE_NOMEM on an OOM error.
85684 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
85685 char *zExtra;
85686 int nByte;
85687 if( pIdx->nColumn>=N ) return SQLITE_OK;
85688 assert( pIdx->isResized==0 );
85689 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
85690 zExtra = sqlite3DbMallocZero(db, nByte);
85691 if( zExtra==0 ) return SQLITE_NOMEM;
85692 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
85693 pIdx->azColl = (char**)zExtra;
85694 zExtra += sizeof(char*)*N;
85695 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
85696 pIdx->aiColumn = (i16*)zExtra;
85697 zExtra += sizeof(i16)*N;
85698 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
85699 pIdx->aSortOrder = (u8*)zExtra;
85700 pIdx->nColumn = N;
85701 pIdx->isResized = 1;
85702 return SQLITE_OK;
85706 ** Estimate the total row width for a table.
85708 static void estimateTableWidth(Table *pTab){
85709 unsigned wTable = 0;
85710 const Column *pTabCol;
85711 int i;
85712 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
85713 wTable += pTabCol->szEst;
85715 if( pTab->iPKey<0 ) wTable++;
85716 pTab->szTabRow = sqlite3LogEst(wTable*4);
85720 ** Estimate the average size of a row for an index.
85722 static void estimateIndexWidth(Index *pIdx){
85723 unsigned wIndex = 0;
85724 int i;
85725 const Column *aCol = pIdx->pTable->aCol;
85726 for(i=0; i<pIdx->nColumn; i++){
85727 i16 x = pIdx->aiColumn[i];
85728 assert( x<pIdx->pTable->nCol );
85729 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
85731 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
85734 /* Return true if value x is found any of the first nCol entries of aiCol[]
85736 static int hasColumn(const i16 *aiCol, int nCol, int x){
85737 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
85738 return 0;
85742 ** This routine runs at the end of parsing a CREATE TABLE statement that
85743 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
85744 ** internal schema data structures and the generated VDBE code so that they
85745 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
85746 ** Changes include:
85748 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
85749 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
85750 ** data storage is a covering index btree.
85751 ** (2) Bypass the creation of the sqlite_master table entry
85752 ** for the PRIMARY KEY as the the primary key index is now
85753 ** identified by the sqlite_master table entry of the table itself.
85754 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
85755 ** schema to the rootpage from the main table.
85756 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
85757 ** (5) Add all table columns to the PRIMARY KEY Index object
85758 ** so that the PRIMARY KEY is a covering index. The surplus
85759 ** columns are part of KeyInfo.nXField and are not used for
85760 ** sorting or lookup or uniqueness checks.
85761 ** (6) Replace the rowid tail on all automatically generated UNIQUE
85762 ** indices with the PRIMARY KEY columns.
85764 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
85765 Index *pIdx;
85766 Index *pPk;
85767 int nPk;
85768 int i, j;
85769 sqlite3 *db = pParse->db;
85770 Vdbe *v = pParse->pVdbe;
85772 /* Convert the OP_CreateTable opcode that would normally create the
85773 ** root-page for the table into a OP_CreateIndex opcode. The index
85774 ** created will become the PRIMARY KEY index.
85776 if( pParse->addrCrTab ){
85777 assert( v );
85778 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
85781 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
85782 ** table entry.
85784 if( pParse->addrSkipPK ){
85785 assert( v );
85786 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
85789 /* Locate the PRIMARY KEY index. Or, if this table was originally
85790 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
85792 if( pTab->iPKey>=0 ){
85793 ExprList *pList;
85794 pList = sqlite3ExprListAppend(pParse, 0, 0);
85795 if( pList==0 ) return;
85796 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
85797 pTab->aCol[pTab->iPKey].zName);
85798 pList->a[0].sortOrder = pParse->iPkSortOrder;
85799 assert( pParse->pNewTable==pTab );
85800 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
85801 if( pPk==0 ) return;
85802 pPk->autoIndex = 2;
85803 pTab->iPKey = -1;
85804 }else{
85805 pPk = sqlite3PrimaryKeyIndex(pTab);
85807 pPk->isCovering = 1;
85808 assert( pPk!=0 );
85809 nPk = pPk->nKeyCol;
85811 /* Make sure every column of the PRIMARY KEY is NOT NULL */
85812 for(i=0; i<nPk; i++){
85813 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
85815 pPk->uniqNotNull = 1;
85817 /* The root page of the PRIMARY KEY is the table root page */
85818 pPk->tnum = pTab->tnum;
85820 /* Update the in-memory representation of all UNIQUE indices by converting
85821 ** the final rowid column into one or more columns of the PRIMARY KEY.
85823 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85824 int n;
85825 if( pIdx->autoIndex==2 ) continue;
85826 for(i=n=0; i<nPk; i++){
85827 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
85829 if( n==0 ){
85830 /* This index is a superset of the primary key */
85831 pIdx->nColumn = pIdx->nKeyCol;
85832 continue;
85834 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
85835 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
85836 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
85837 pIdx->aiColumn[j] = pPk->aiColumn[i];
85838 pIdx->azColl[j] = pPk->azColl[i];
85839 j++;
85842 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
85843 assert( pIdx->nColumn>=j );
85846 /* Add all table columns to the PRIMARY KEY index
85848 if( nPk<pTab->nCol ){
85849 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
85850 for(i=0, j=nPk; i<pTab->nCol; i++){
85851 if( !hasColumn(pPk->aiColumn, j, i) ){
85852 assert( j<pPk->nColumn );
85853 pPk->aiColumn[j] = i;
85854 pPk->azColl[j] = "BINARY";
85855 j++;
85858 assert( pPk->nColumn==j );
85859 assert( pTab->nCol==j );
85860 }else{
85861 pPk->nColumn = pTab->nCol;
85866 ** This routine is called to report the final ")" that terminates
85867 ** a CREATE TABLE statement.
85869 ** The table structure that other action routines have been building
85870 ** is added to the internal hash tables, assuming no errors have
85871 ** occurred.
85873 ** An entry for the table is made in the master table on disk, unless
85874 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
85875 ** it means we are reading the sqlite_master table because we just
85876 ** connected to the database or because the sqlite_master table has
85877 ** recently changed, so the entry for this table already exists in
85878 ** the sqlite_master table. We do not want to create it again.
85880 ** If the pSelect argument is not NULL, it means that this routine
85881 ** was called to create a table generated from a
85882 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
85883 ** the new table will match the result set of the SELECT.
85885 SQLITE_PRIVATE void sqlite3EndTable(
85886 Parse *pParse, /* Parse context */
85887 Token *pCons, /* The ',' token after the last column defn. */
85888 Token *pEnd, /* The ')' before options in the CREATE TABLE */
85889 u8 tabOpts, /* Extra table options. Usually 0. */
85890 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
85892 Table *p; /* The new table */
85893 sqlite3 *db = pParse->db; /* The database connection */
85894 int iDb; /* Database in which the table lives */
85895 Index *pIdx; /* An implied index of the table */
85897 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
85898 return;
85900 p = pParse->pNewTable;
85901 if( p==0 ) return;
85903 assert( !db->init.busy || !pSelect );
85905 /* If the db->init.busy is 1 it means we are reading the SQL off the
85906 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
85907 ** So do not write to the disk again. Extract the root page number
85908 ** for the table from the db->init.newTnum field. (The page number
85909 ** should have been put there by the sqliteOpenCb routine.)
85911 if( db->init.busy ){
85912 p->tnum = db->init.newTnum;
85915 /* Special processing for WITHOUT ROWID Tables */
85916 if( tabOpts & TF_WithoutRowid ){
85917 if( (p->tabFlags & TF_Autoincrement) ){
85918 sqlite3ErrorMsg(pParse,
85919 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
85920 return;
85922 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
85923 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
85924 }else{
85925 p->tabFlags |= TF_WithoutRowid;
85926 convertToWithoutRowidTable(pParse, p);
85930 iDb = sqlite3SchemaToIndex(db, p->pSchema);
85932 #ifndef SQLITE_OMIT_CHECK
85933 /* Resolve names in all CHECK constraint expressions.
85935 if( p->pCheck ){
85936 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
85938 #endif /* !defined(SQLITE_OMIT_CHECK) */
85940 /* Estimate the average row size for the table and for all implied indices */
85941 estimateTableWidth(p);
85942 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
85943 estimateIndexWidth(pIdx);
85946 /* If not initializing, then create a record for the new table
85947 ** in the SQLITE_MASTER table of the database.
85949 ** If this is a TEMPORARY table, write the entry into the auxiliary
85950 ** file instead of into the main database file.
85952 if( !db->init.busy ){
85953 int n;
85954 Vdbe *v;
85955 char *zType; /* "view" or "table" */
85956 char *zType2; /* "VIEW" or "TABLE" */
85957 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
85959 v = sqlite3GetVdbe(pParse);
85960 if( NEVER(v==0) ) return;
85962 sqlite3VdbeAddOp1(v, OP_Close, 0);
85965 ** Initialize zType for the new view or table.
85967 if( p->pSelect==0 ){
85968 /* A regular table */
85969 zType = "table";
85970 zType2 = "TABLE";
85971 #ifndef SQLITE_OMIT_VIEW
85972 }else{
85973 /* A view */
85974 zType = "view";
85975 zType2 = "VIEW";
85976 #endif
85979 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
85980 ** statement to populate the new table. The root-page number for the
85981 ** new table is in register pParse->regRoot.
85983 ** Once the SELECT has been coded by sqlite3Select(), it is in a
85984 ** suitable state to query for the column names and types to be used
85985 ** by the new table.
85987 ** A shared-cache write-lock is not required to write to the new table,
85988 ** as a schema-lock must have already been obtained to create it. Since
85989 ** a schema-lock excludes all other database users, the write-lock would
85990 ** be redundant.
85992 if( pSelect ){
85993 SelectDest dest;
85994 Table *pSelTab;
85996 assert(pParse->nTab==1);
85997 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
85998 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
85999 pParse->nTab = 2;
86000 sqlite3SelectDestInit(&dest, SRT_Table, 1);
86001 sqlite3Select(pParse, pSelect, &dest);
86002 sqlite3VdbeAddOp1(v, OP_Close, 1);
86003 if( pParse->nErr==0 ){
86004 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
86005 if( pSelTab==0 ) return;
86006 assert( p->aCol==0 );
86007 p->nCol = pSelTab->nCol;
86008 p->aCol = pSelTab->aCol;
86009 pSelTab->nCol = 0;
86010 pSelTab->aCol = 0;
86011 sqlite3DeleteTable(db, pSelTab);
86015 /* Compute the complete text of the CREATE statement */
86016 if( pSelect ){
86017 zStmt = createTableStmt(db, p);
86018 }else{
86019 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
86020 n = (int)(pEnd2->z - pParse->sNameToken.z);
86021 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
86022 zStmt = sqlite3MPrintf(db,
86023 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
86027 /* A slot for the record has already been allocated in the
86028 ** SQLITE_MASTER table. We just need to update that slot with all
86029 ** the information we've collected.
86031 sqlite3NestedParse(pParse,
86032 "UPDATE %Q.%s "
86033 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
86034 "WHERE rowid=#%d",
86035 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
86036 zType,
86037 p->zName,
86038 p->zName,
86039 pParse->regRoot,
86040 zStmt,
86041 pParse->regRowid
86043 sqlite3DbFree(db, zStmt);
86044 sqlite3ChangeCookie(pParse, iDb);
86046 #ifndef SQLITE_OMIT_AUTOINCREMENT
86047 /* Check to see if we need to create an sqlite_sequence table for
86048 ** keeping track of autoincrement keys.
86050 if( p->tabFlags & TF_Autoincrement ){
86051 Db *pDb = &db->aDb[iDb];
86052 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86053 if( pDb->pSchema->pSeqTab==0 ){
86054 sqlite3NestedParse(pParse,
86055 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
86056 pDb->zName
86060 #endif
86062 /* Reparse everything to update our internal data structures */
86063 sqlite3VdbeAddParseSchemaOp(v, iDb,
86064 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
86068 /* Add the table to the in-memory representation of the database.
86070 if( db->init.busy ){
86071 Table *pOld;
86072 Schema *pSchema = p->pSchema;
86073 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86074 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
86075 sqlite3Strlen30(p->zName),p);
86076 if( pOld ){
86077 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
86078 db->mallocFailed = 1;
86079 return;
86081 pParse->pNewTable = 0;
86082 db->flags |= SQLITE_InternChanges;
86084 #ifndef SQLITE_OMIT_ALTERTABLE
86085 if( !p->pSelect ){
86086 const char *zName = (const char *)pParse->sNameToken.z;
86087 int nName;
86088 assert( !pSelect && pCons && pEnd );
86089 if( pCons->z==0 ){
86090 pCons = pEnd;
86092 nName = (int)((const char *)pCons->z - zName);
86093 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
86095 #endif
86099 #ifndef SQLITE_OMIT_VIEW
86101 ** The parser calls this routine in order to create a new VIEW
86103 SQLITE_PRIVATE void sqlite3CreateView(
86104 Parse *pParse, /* The parsing context */
86105 Token *pBegin, /* The CREATE token that begins the statement */
86106 Token *pName1, /* The token that holds the name of the view */
86107 Token *pName2, /* The token that holds the name of the view */
86108 Select *pSelect, /* A SELECT statement that will become the new view */
86109 int isTemp, /* TRUE for a TEMPORARY view */
86110 int noErr /* Suppress error messages if VIEW already exists */
86112 Table *p;
86113 int n;
86114 const char *z;
86115 Token sEnd;
86116 DbFixer sFix;
86117 Token *pName = 0;
86118 int iDb;
86119 sqlite3 *db = pParse->db;
86121 if( pParse->nVar>0 ){
86122 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
86123 sqlite3SelectDelete(db, pSelect);
86124 return;
86126 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
86127 p = pParse->pNewTable;
86128 if( p==0 || pParse->nErr ){
86129 sqlite3SelectDelete(db, pSelect);
86130 return;
86132 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
86133 iDb = sqlite3SchemaToIndex(db, p->pSchema);
86134 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
86135 if( sqlite3FixSelect(&sFix, pSelect) ){
86136 sqlite3SelectDelete(db, pSelect);
86137 return;
86140 /* Make a copy of the entire SELECT statement that defines the view.
86141 ** This will force all the Expr.token.z values to be dynamically
86142 ** allocated rather than point to the input string - which means that
86143 ** they will persist after the current sqlite3_exec() call returns.
86145 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
86146 sqlite3SelectDelete(db, pSelect);
86147 if( db->mallocFailed ){
86148 return;
86150 if( !db->init.busy ){
86151 sqlite3ViewGetColumnNames(pParse, p);
86154 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
86155 ** the end.
86157 sEnd = pParse->sLastToken;
86158 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
86159 sEnd.z += sEnd.n;
86161 sEnd.n = 0;
86162 n = (int)(sEnd.z - pBegin->z);
86163 z = pBegin->z;
86164 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
86165 sEnd.z = &z[n-1];
86166 sEnd.n = 1;
86168 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
86169 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
86170 return;
86172 #endif /* SQLITE_OMIT_VIEW */
86174 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
86176 ** The Table structure pTable is really a VIEW. Fill in the names of
86177 ** the columns of the view in the pTable structure. Return the number
86178 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
86180 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
86181 Table *pSelTab; /* A fake table from which we get the result set */
86182 Select *pSel; /* Copy of the SELECT that implements the view */
86183 int nErr = 0; /* Number of errors encountered */
86184 int n; /* Temporarily holds the number of cursors assigned */
86185 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
86186 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
86188 assert( pTable );
86190 #ifndef SQLITE_OMIT_VIRTUALTABLE
86191 if( sqlite3VtabCallConnect(pParse, pTable) ){
86192 return SQLITE_ERROR;
86194 if( IsVirtual(pTable) ) return 0;
86195 #endif
86197 #ifndef SQLITE_OMIT_VIEW
86198 /* A positive nCol means the columns names for this view are
86199 ** already known.
86201 if( pTable->nCol>0 ) return 0;
86203 /* A negative nCol is a special marker meaning that we are currently
86204 ** trying to compute the column names. If we enter this routine with
86205 ** a negative nCol, it means two or more views form a loop, like this:
86207 ** CREATE VIEW one AS SELECT * FROM two;
86208 ** CREATE VIEW two AS SELECT * FROM one;
86210 ** Actually, the error above is now caught prior to reaching this point.
86211 ** But the following test is still important as it does come up
86212 ** in the following:
86214 ** CREATE TABLE main.ex1(a);
86215 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
86216 ** SELECT * FROM temp.ex1;
86218 if( pTable->nCol<0 ){
86219 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
86220 return 1;
86222 assert( pTable->nCol>=0 );
86224 /* If we get this far, it means we need to compute the table names.
86225 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
86226 ** "*" elements in the results set of the view and will assign cursors
86227 ** to the elements of the FROM clause. But we do not want these changes
86228 ** to be permanent. So the computation is done on a copy of the SELECT
86229 ** statement that defines the view.
86231 assert( pTable->pSelect );
86232 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
86233 if( pSel ){
86234 u8 enableLookaside = db->lookaside.bEnabled;
86235 n = pParse->nTab;
86236 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
86237 pTable->nCol = -1;
86238 db->lookaside.bEnabled = 0;
86239 #ifndef SQLITE_OMIT_AUTHORIZATION
86240 xAuth = db->xAuth;
86241 db->xAuth = 0;
86242 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
86243 db->xAuth = xAuth;
86244 #else
86245 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
86246 #endif
86247 db->lookaside.bEnabled = enableLookaside;
86248 pParse->nTab = n;
86249 if( pSelTab ){
86250 assert( pTable->aCol==0 );
86251 pTable->nCol = pSelTab->nCol;
86252 pTable->aCol = pSelTab->aCol;
86253 pSelTab->nCol = 0;
86254 pSelTab->aCol = 0;
86255 sqlite3DeleteTable(db, pSelTab);
86256 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
86257 pTable->pSchema->flags |= DB_UnresetViews;
86258 }else{
86259 pTable->nCol = 0;
86260 nErr++;
86262 sqlite3SelectDelete(db, pSel);
86263 } else {
86264 nErr++;
86266 #endif /* SQLITE_OMIT_VIEW */
86267 return nErr;
86269 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
86271 #ifndef SQLITE_OMIT_VIEW
86273 ** Clear the column names from every VIEW in database idx.
86275 static void sqliteViewResetAll(sqlite3 *db, int idx){
86276 HashElem *i;
86277 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
86278 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
86279 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
86280 Table *pTab = sqliteHashData(i);
86281 if( pTab->pSelect ){
86282 sqliteDeleteColumnNames(db, pTab);
86283 pTab->aCol = 0;
86284 pTab->nCol = 0;
86287 DbClearProperty(db, idx, DB_UnresetViews);
86289 #else
86290 # define sqliteViewResetAll(A,B)
86291 #endif /* SQLITE_OMIT_VIEW */
86294 ** This function is called by the VDBE to adjust the internal schema
86295 ** used by SQLite when the btree layer moves a table root page. The
86296 ** root-page of a table or index in database iDb has changed from iFrom
86297 ** to iTo.
86299 ** Ticket #1728: The symbol table might still contain information
86300 ** on tables and/or indices that are the process of being deleted.
86301 ** If you are unlucky, one of those deleted indices or tables might
86302 ** have the same rootpage number as the real table or index that is
86303 ** being moved. So we cannot stop searching after the first match
86304 ** because the first match might be for one of the deleted indices
86305 ** or tables and not the table/index that is actually being moved.
86306 ** We must continue looping until all tables and indices with
86307 ** rootpage==iFrom have been converted to have a rootpage of iTo
86308 ** in order to be certain that we got the right one.
86310 #ifndef SQLITE_OMIT_AUTOVACUUM
86311 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
86312 HashElem *pElem;
86313 Hash *pHash;
86314 Db *pDb;
86316 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
86317 pDb = &db->aDb[iDb];
86318 pHash = &pDb->pSchema->tblHash;
86319 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
86320 Table *pTab = sqliteHashData(pElem);
86321 if( pTab->tnum==iFrom ){
86322 pTab->tnum = iTo;
86325 pHash = &pDb->pSchema->idxHash;
86326 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
86327 Index *pIdx = sqliteHashData(pElem);
86328 if( pIdx->tnum==iFrom ){
86329 pIdx->tnum = iTo;
86333 #endif
86336 ** Write code to erase the table with root-page iTable from database iDb.
86337 ** Also write code to modify the sqlite_master table and internal schema
86338 ** if a root-page of another table is moved by the btree-layer whilst
86339 ** erasing iTable (this can happen with an auto-vacuum database).
86341 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
86342 Vdbe *v = sqlite3GetVdbe(pParse);
86343 int r1 = sqlite3GetTempReg(pParse);
86344 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
86345 sqlite3MayAbort(pParse);
86346 #ifndef SQLITE_OMIT_AUTOVACUUM
86347 /* OP_Destroy stores an in integer r1. If this integer
86348 ** is non-zero, then it is the root page number of a table moved to
86349 ** location iTable. The following code modifies the sqlite_master table to
86350 ** reflect this.
86352 ** The "#NNN" in the SQL is a special constant that means whatever value
86353 ** is in register NNN. See grammar rules associated with the TK_REGISTER
86354 ** token for additional information.
86356 sqlite3NestedParse(pParse,
86357 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
86358 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
86359 #endif
86360 sqlite3ReleaseTempReg(pParse, r1);
86364 ** Write VDBE code to erase table pTab and all associated indices on disk.
86365 ** Code to update the sqlite_master tables and internal schema definitions
86366 ** in case a root-page belonging to another table is moved by the btree layer
86367 ** is also added (this can happen with an auto-vacuum database).
86369 static void destroyTable(Parse *pParse, Table *pTab){
86370 #ifdef SQLITE_OMIT_AUTOVACUUM
86371 Index *pIdx;
86372 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86373 destroyRootPage(pParse, pTab->tnum, iDb);
86374 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86375 destroyRootPage(pParse, pIdx->tnum, iDb);
86377 #else
86378 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
86379 ** is not defined), then it is important to call OP_Destroy on the
86380 ** table and index root-pages in order, starting with the numerically
86381 ** largest root-page number. This guarantees that none of the root-pages
86382 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
86383 ** following were coded:
86385 ** OP_Destroy 4 0
86386 ** ...
86387 ** OP_Destroy 5 0
86389 ** and root page 5 happened to be the largest root-page number in the
86390 ** database, then root page 5 would be moved to page 4 by the
86391 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
86392 ** a free-list page.
86394 int iTab = pTab->tnum;
86395 int iDestroyed = 0;
86397 while( 1 ){
86398 Index *pIdx;
86399 int iLargest = 0;
86401 if( iDestroyed==0 || iTab<iDestroyed ){
86402 iLargest = iTab;
86404 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86405 int iIdx = pIdx->tnum;
86406 assert( pIdx->pSchema==pTab->pSchema );
86407 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
86408 iLargest = iIdx;
86411 if( iLargest==0 ){
86412 return;
86413 }else{
86414 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
86415 assert( iDb>=0 && iDb<pParse->db->nDb );
86416 destroyRootPage(pParse, iLargest, iDb);
86417 iDestroyed = iLargest;
86420 #endif
86424 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
86425 ** after a DROP INDEX or DROP TABLE command.
86427 static void sqlite3ClearStatTables(
86428 Parse *pParse, /* The parsing context */
86429 int iDb, /* The database number */
86430 const char *zType, /* "idx" or "tbl" */
86431 const char *zName /* Name of index or table */
86433 int i;
86434 const char *zDbName = pParse->db->aDb[iDb].zName;
86435 for(i=1; i<=4; i++){
86436 char zTab[24];
86437 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
86438 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
86439 sqlite3NestedParse(pParse,
86440 "DELETE FROM %Q.%s WHERE %s=%Q",
86441 zDbName, zTab, zType, zName
86448 ** Generate code to drop a table.
86450 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
86451 Vdbe *v;
86452 sqlite3 *db = pParse->db;
86453 Trigger *pTrigger;
86454 Db *pDb = &db->aDb[iDb];
86456 v = sqlite3GetVdbe(pParse);
86457 assert( v!=0 );
86458 sqlite3BeginWriteOperation(pParse, 1, iDb);
86460 #ifndef SQLITE_OMIT_VIRTUALTABLE
86461 if( IsVirtual(pTab) ){
86462 sqlite3VdbeAddOp0(v, OP_VBegin);
86464 #endif
86466 /* Drop all triggers associated with the table being dropped. Code
86467 ** is generated to remove entries from sqlite_master and/or
86468 ** sqlite_temp_master if required.
86470 pTrigger = sqlite3TriggerList(pParse, pTab);
86471 while( pTrigger ){
86472 assert( pTrigger->pSchema==pTab->pSchema ||
86473 pTrigger->pSchema==db->aDb[1].pSchema );
86474 sqlite3DropTriggerPtr(pParse, pTrigger);
86475 pTrigger = pTrigger->pNext;
86478 #ifndef SQLITE_OMIT_AUTOINCREMENT
86479 /* Remove any entries of the sqlite_sequence table associated with
86480 ** the table being dropped. This is done before the table is dropped
86481 ** at the btree level, in case the sqlite_sequence table needs to
86482 ** move as a result of the drop (can happen in auto-vacuum mode).
86484 if( pTab->tabFlags & TF_Autoincrement ){
86485 sqlite3NestedParse(pParse,
86486 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
86487 pDb->zName, pTab->zName
86490 #endif
86492 /* Drop all SQLITE_MASTER table and index entries that refer to the
86493 ** table. The program name loops through the master table and deletes
86494 ** every row that refers to a table of the same name as the one being
86495 ** dropped. Triggers are handled separately because a trigger can be
86496 ** created in the temp database that refers to a table in another
86497 ** database.
86499 sqlite3NestedParse(pParse,
86500 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
86501 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
86502 if( !isView && !IsVirtual(pTab) ){
86503 destroyTable(pParse, pTab);
86506 /* Remove the table entry from SQLite's internal schema and modify
86507 ** the schema cookie.
86509 if( IsVirtual(pTab) ){
86510 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
86512 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
86513 sqlite3ChangeCookie(pParse, iDb);
86514 sqliteViewResetAll(db, iDb);
86518 ** This routine is called to do the work of a DROP TABLE statement.
86519 ** pName is the name of the table to be dropped.
86521 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
86522 Table *pTab;
86523 Vdbe *v;
86524 sqlite3 *db = pParse->db;
86525 int iDb;
86527 if( db->mallocFailed ){
86528 goto exit_drop_table;
86530 assert( pParse->nErr==0 );
86531 assert( pName->nSrc==1 );
86532 if( noErr ) db->suppressErr++;
86533 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
86534 if( noErr ) db->suppressErr--;
86536 if( pTab==0 ){
86537 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
86538 goto exit_drop_table;
86540 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86541 assert( iDb>=0 && iDb<db->nDb );
86543 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
86544 ** it is initialized.
86546 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
86547 goto exit_drop_table;
86549 #ifndef SQLITE_OMIT_AUTHORIZATION
86551 int code;
86552 const char *zTab = SCHEMA_TABLE(iDb);
86553 const char *zDb = db->aDb[iDb].zName;
86554 const char *zArg2 = 0;
86555 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
86556 goto exit_drop_table;
86558 if( isView ){
86559 if( !OMIT_TEMPDB && iDb==1 ){
86560 code = SQLITE_DROP_TEMP_VIEW;
86561 }else{
86562 code = SQLITE_DROP_VIEW;
86564 #ifndef SQLITE_OMIT_VIRTUALTABLE
86565 }else if( IsVirtual(pTab) ){
86566 code = SQLITE_DROP_VTABLE;
86567 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
86568 #endif
86569 }else{
86570 if( !OMIT_TEMPDB && iDb==1 ){
86571 code = SQLITE_DROP_TEMP_TABLE;
86572 }else{
86573 code = SQLITE_DROP_TABLE;
86576 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
86577 goto exit_drop_table;
86579 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
86580 goto exit_drop_table;
86583 #endif
86584 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
86585 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
86586 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
86587 goto exit_drop_table;
86590 #ifndef SQLITE_OMIT_VIEW
86591 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
86592 ** on a table.
86594 if( isView && pTab->pSelect==0 ){
86595 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
86596 goto exit_drop_table;
86598 if( !isView && pTab->pSelect ){
86599 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
86600 goto exit_drop_table;
86602 #endif
86604 /* Generate code to remove the table from the master table
86605 ** on disk.
86607 v = sqlite3GetVdbe(pParse);
86608 if( v ){
86609 sqlite3BeginWriteOperation(pParse, 1, iDb);
86610 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
86611 sqlite3FkDropTable(pParse, pName, pTab);
86612 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
86615 exit_drop_table:
86616 sqlite3SrcListDelete(db, pName);
86620 ** This routine is called to create a new foreign key on the table
86621 ** currently under construction. pFromCol determines which columns
86622 ** in the current table point to the foreign key. If pFromCol==0 then
86623 ** connect the key to the last column inserted. pTo is the name of
86624 ** the table referred to (a.k.a the "parent" table). pToCol is a list
86625 ** of tables in the parent pTo table. flags contains all
86626 ** information about the conflict resolution algorithms specified
86627 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
86629 ** An FKey structure is created and added to the table currently
86630 ** under construction in the pParse->pNewTable field.
86632 ** The foreign key is set for IMMEDIATE processing. A subsequent call
86633 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
86635 SQLITE_PRIVATE void sqlite3CreateForeignKey(
86636 Parse *pParse, /* Parsing context */
86637 ExprList *pFromCol, /* Columns in this table that point to other table */
86638 Token *pTo, /* Name of the other table */
86639 ExprList *pToCol, /* Columns in the other table */
86640 int flags /* Conflict resolution algorithms. */
86642 sqlite3 *db = pParse->db;
86643 #ifndef SQLITE_OMIT_FOREIGN_KEY
86644 FKey *pFKey = 0;
86645 FKey *pNextTo;
86646 Table *p = pParse->pNewTable;
86647 int nByte;
86648 int i;
86649 int nCol;
86650 char *z;
86652 assert( pTo!=0 );
86653 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
86654 if( pFromCol==0 ){
86655 int iCol = p->nCol-1;
86656 if( NEVER(iCol<0) ) goto fk_end;
86657 if( pToCol && pToCol->nExpr!=1 ){
86658 sqlite3ErrorMsg(pParse, "foreign key on %s"
86659 " should reference only one column of table %T",
86660 p->aCol[iCol].zName, pTo);
86661 goto fk_end;
86663 nCol = 1;
86664 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
86665 sqlite3ErrorMsg(pParse,
86666 "number of columns in foreign key does not match the number of "
86667 "columns in the referenced table");
86668 goto fk_end;
86669 }else{
86670 nCol = pFromCol->nExpr;
86672 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
86673 if( pToCol ){
86674 for(i=0; i<pToCol->nExpr; i++){
86675 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
86678 pFKey = sqlite3DbMallocZero(db, nByte );
86679 if( pFKey==0 ){
86680 goto fk_end;
86682 pFKey->pFrom = p;
86683 pFKey->pNextFrom = p->pFKey;
86684 z = (char*)&pFKey->aCol[nCol];
86685 pFKey->zTo = z;
86686 memcpy(z, pTo->z, pTo->n);
86687 z[pTo->n] = 0;
86688 sqlite3Dequote(z);
86689 z += pTo->n+1;
86690 pFKey->nCol = nCol;
86691 if( pFromCol==0 ){
86692 pFKey->aCol[0].iFrom = p->nCol-1;
86693 }else{
86694 for(i=0; i<nCol; i++){
86695 int j;
86696 for(j=0; j<p->nCol; j++){
86697 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
86698 pFKey->aCol[i].iFrom = j;
86699 break;
86702 if( j>=p->nCol ){
86703 sqlite3ErrorMsg(pParse,
86704 "unknown column \"%s\" in foreign key definition",
86705 pFromCol->a[i].zName);
86706 goto fk_end;
86710 if( pToCol ){
86711 for(i=0; i<nCol; i++){
86712 int n = sqlite3Strlen30(pToCol->a[i].zName);
86713 pFKey->aCol[i].zCol = z;
86714 memcpy(z, pToCol->a[i].zName, n);
86715 z[n] = 0;
86716 z += n+1;
86719 pFKey->isDeferred = 0;
86720 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
86721 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
86723 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
86724 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
86725 pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
86727 if( pNextTo==pFKey ){
86728 db->mallocFailed = 1;
86729 goto fk_end;
86731 if( pNextTo ){
86732 assert( pNextTo->pPrevTo==0 );
86733 pFKey->pNextTo = pNextTo;
86734 pNextTo->pPrevTo = pFKey;
86737 /* Link the foreign key to the table as the last step.
86739 p->pFKey = pFKey;
86740 pFKey = 0;
86742 fk_end:
86743 sqlite3DbFree(db, pFKey);
86744 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
86745 sqlite3ExprListDelete(db, pFromCol);
86746 sqlite3ExprListDelete(db, pToCol);
86750 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
86751 ** clause is seen as part of a foreign key definition. The isDeferred
86752 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
86753 ** The behavior of the most recently created foreign key is adjusted
86754 ** accordingly.
86756 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
86757 #ifndef SQLITE_OMIT_FOREIGN_KEY
86758 Table *pTab;
86759 FKey *pFKey;
86760 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
86761 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
86762 pFKey->isDeferred = (u8)isDeferred;
86763 #endif
86767 ** Generate code that will erase and refill index *pIdx. This is
86768 ** used to initialize a newly created index or to recompute the
86769 ** content of an index in response to a REINDEX command.
86771 ** if memRootPage is not negative, it means that the index is newly
86772 ** created. The register specified by memRootPage contains the
86773 ** root page number of the index. If memRootPage is negative, then
86774 ** the index already exists and must be cleared before being refilled and
86775 ** the root page number of the index is taken from pIndex->tnum.
86777 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
86778 Table *pTab = pIndex->pTable; /* The table that is indexed */
86779 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
86780 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
86781 int iSorter; /* Cursor opened by OpenSorter (if in use) */
86782 int addr1; /* Address of top of loop */
86783 int addr2; /* Address to jump to for next iteration */
86784 int tnum; /* Root page of index */
86785 int iPartIdxLabel; /* Jump to this label to skip a row */
86786 Vdbe *v; /* Generate code into this virtual machine */
86787 KeyInfo *pKey; /* KeyInfo for index */
86788 int regRecord; /* Register holding assemblied index record */
86789 sqlite3 *db = pParse->db; /* The database connection */
86790 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
86792 #ifndef SQLITE_OMIT_AUTHORIZATION
86793 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
86794 db->aDb[iDb].zName ) ){
86795 return;
86797 #endif
86799 /* Require a write-lock on the table to perform this operation */
86800 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
86802 v = sqlite3GetVdbe(pParse);
86803 if( v==0 ) return;
86804 if( memRootPage>=0 ){
86805 tnum = memRootPage;
86806 }else{
86807 tnum = pIndex->tnum;
86809 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
86811 /* Open the sorter cursor if we are to use one. */
86812 iSorter = pParse->nTab++;
86813 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
86814 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
86816 /* Open the table. Loop through all rows of the table, inserting index
86817 ** records into the sorter. */
86818 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
86819 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
86820 regRecord = sqlite3GetTempReg(pParse);
86822 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
86823 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
86824 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
86825 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
86826 sqlite3VdbeJumpHere(v, addr1);
86827 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
86828 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
86829 (char *)pKey, P4_KEYINFO);
86830 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
86832 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
86833 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
86834 if( pIndex->onError!=OE_None && pKey!=0 ){
86835 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
86836 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
86837 addr2 = sqlite3VdbeCurrentAddr(v);
86838 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
86839 pKey->nField - pIndex->nKeyCol);
86840 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
86841 }else{
86842 addr2 = sqlite3VdbeCurrentAddr(v);
86844 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
86845 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
86846 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
86847 sqlite3ReleaseTempReg(pParse, regRecord);
86848 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
86849 sqlite3VdbeJumpHere(v, addr1);
86851 sqlite3VdbeAddOp1(v, OP_Close, iTab);
86852 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
86853 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
86857 ** Allocate heap space to hold an Index object with nCol columns.
86859 ** Increase the allocation size to provide an extra nExtra bytes
86860 ** of 8-byte aligned space after the Index object and return a
86861 ** pointer to this extra space in *ppExtra.
86863 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
86864 sqlite3 *db, /* Database connection */
86865 i16 nCol, /* Total number of columns in the index */
86866 int nExtra, /* Number of bytes of extra space to alloc */
86867 char **ppExtra /* Pointer to the "extra" space */
86869 Index *p; /* Allocated index object */
86870 int nByte; /* Bytes of space for Index object + arrays */
86872 nByte = ROUND8(sizeof(Index)) + /* Index structure */
86873 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
86874 ROUND8(sizeof(tRowcnt)*(nCol+1) + /* Index.aiRowEst */
86875 sizeof(i16)*nCol + /* Index.aiColumn */
86876 sizeof(u8)*nCol); /* Index.aSortOrder */
86877 p = sqlite3DbMallocZero(db, nByte + nExtra);
86878 if( p ){
86879 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
86880 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
86881 p->aiRowEst = (tRowcnt*)pExtra; pExtra += sizeof(tRowcnt)*(nCol+1);
86882 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
86883 p->aSortOrder = (u8*)pExtra;
86884 p->nColumn = nCol;
86885 p->nKeyCol = nCol - 1;
86886 *ppExtra = ((char*)p) + nByte;
86888 return p;
86892 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
86893 ** and pTblList is the name of the table that is to be indexed. Both will
86894 ** be NULL for a primary key or an index that is created to satisfy a
86895 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
86896 ** as the table to be indexed. pParse->pNewTable is a table that is
86897 ** currently being constructed by a CREATE TABLE statement.
86899 ** pList is a list of columns to be indexed. pList will be NULL if this
86900 ** is a primary key or unique-constraint on the most recent column added
86901 ** to the table currently under construction.
86903 ** If the index is created successfully, return a pointer to the new Index
86904 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
86905 ** as the tables primary key (Index.autoIndex==2).
86907 SQLITE_PRIVATE Index *sqlite3CreateIndex(
86908 Parse *pParse, /* All information about this parse */
86909 Token *pName1, /* First part of index name. May be NULL */
86910 Token *pName2, /* Second part of index name. May be NULL */
86911 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
86912 ExprList *pList, /* A list of columns to be indexed */
86913 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
86914 Token *pStart, /* The CREATE token that begins this statement */
86915 Expr *pPIWhere, /* WHERE clause for partial indices */
86916 int sortOrder, /* Sort order of primary key when pList==NULL */
86917 int ifNotExist /* Omit error if index already exists */
86919 Index *pRet = 0; /* Pointer to return */
86920 Table *pTab = 0; /* Table to be indexed */
86921 Index *pIndex = 0; /* The index to be created */
86922 char *zName = 0; /* Name of the index */
86923 int nName; /* Number of characters in zName */
86924 int i, j;
86925 DbFixer sFix; /* For assigning database names to pTable */
86926 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
86927 sqlite3 *db = pParse->db;
86928 Db *pDb; /* The specific table containing the indexed database */
86929 int iDb; /* Index of the database that is being written */
86930 Token *pName = 0; /* Unqualified name of the index to create */
86931 struct ExprList_item *pListItem; /* For looping over pList */
86932 const Column *pTabCol; /* A column in the table */
86933 int nExtra = 0; /* Space allocated for zExtra[] */
86934 int nExtraCol; /* Number of extra columns needed */
86935 char *zExtra = 0; /* Extra space after the Index object */
86936 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
86938 assert( pParse->nErr==0 ); /* Never called with prior errors */
86939 if( db->mallocFailed || IN_DECLARE_VTAB ){
86940 goto exit_create_index;
86942 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
86943 goto exit_create_index;
86947 ** Find the table that is to be indexed. Return early if not found.
86949 if( pTblName!=0 ){
86951 /* Use the two-part index name to determine the database
86952 ** to search for the table. 'Fix' the table name to this db
86953 ** before looking up the table.
86955 assert( pName1 && pName2 );
86956 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
86957 if( iDb<0 ) goto exit_create_index;
86958 assert( pName && pName->z );
86960 #ifndef SQLITE_OMIT_TEMPDB
86961 /* If the index name was unqualified, check if the table
86962 ** is a temp table. If so, set the database to 1. Do not do this
86963 ** if initialising a database schema.
86965 if( !db->init.busy ){
86966 pTab = sqlite3SrcListLookup(pParse, pTblName);
86967 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
86968 iDb = 1;
86971 #endif
86973 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
86974 if( sqlite3FixSrcList(&sFix, pTblName) ){
86975 /* Because the parser constructs pTblName from a single identifier,
86976 ** sqlite3FixSrcList can never fail. */
86977 assert(0);
86979 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
86980 assert( db->mallocFailed==0 || pTab==0 );
86981 if( pTab==0 ) goto exit_create_index;
86982 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
86983 sqlite3ErrorMsg(pParse,
86984 "cannot create a TEMP index on non-TEMP table \"%s\"",
86985 pTab->zName);
86986 goto exit_create_index;
86988 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
86989 }else{
86990 assert( pName==0 );
86991 assert( pStart==0 );
86992 pTab = pParse->pNewTable;
86993 if( !pTab ) goto exit_create_index;
86994 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86996 pDb = &db->aDb[iDb];
86998 assert( pTab!=0 );
86999 assert( pParse->nErr==0 );
87000 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
87001 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
87002 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
87003 goto exit_create_index;
87005 #ifndef SQLITE_OMIT_VIEW
87006 if( pTab->pSelect ){
87007 sqlite3ErrorMsg(pParse, "views may not be indexed");
87008 goto exit_create_index;
87010 #endif
87011 #ifndef SQLITE_OMIT_VIRTUALTABLE
87012 if( IsVirtual(pTab) ){
87013 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
87014 goto exit_create_index;
87016 #endif
87019 ** Find the name of the index. Make sure there is not already another
87020 ** index or table with the same name.
87022 ** Exception: If we are reading the names of permanent indices from the
87023 ** sqlite_master table (because some other process changed the schema) and
87024 ** one of the index names collides with the name of a temporary table or
87025 ** index, then we will continue to process this index.
87027 ** If pName==0 it means that we are
87028 ** dealing with a primary key or UNIQUE constraint. We have to invent our
87029 ** own name.
87031 if( pName ){
87032 zName = sqlite3NameFromToken(db, pName);
87033 if( zName==0 ) goto exit_create_index;
87034 assert( pName->z!=0 );
87035 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
87036 goto exit_create_index;
87038 if( !db->init.busy ){
87039 if( sqlite3FindTable(db, zName, 0)!=0 ){
87040 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
87041 goto exit_create_index;
87044 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
87045 if( !ifNotExist ){
87046 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
87047 }else{
87048 assert( !db->init.busy );
87049 sqlite3CodeVerifySchema(pParse, iDb);
87051 goto exit_create_index;
87053 }else{
87054 int n;
87055 Index *pLoop;
87056 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
87057 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
87058 if( zName==0 ){
87059 goto exit_create_index;
87063 /* Check for authorization to create an index.
87065 #ifndef SQLITE_OMIT_AUTHORIZATION
87067 const char *zDb = pDb->zName;
87068 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
87069 goto exit_create_index;
87071 i = SQLITE_CREATE_INDEX;
87072 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
87073 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
87074 goto exit_create_index;
87077 #endif
87079 /* If pList==0, it means this routine was called to make a primary
87080 ** key out of the last column added to the table under construction.
87081 ** So create a fake list to simulate this.
87083 if( pList==0 ){
87084 pList = sqlite3ExprListAppend(pParse, 0, 0);
87085 if( pList==0 ) goto exit_create_index;
87086 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
87087 pTab->aCol[pTab->nCol-1].zName);
87088 pList->a[0].sortOrder = (u8)sortOrder;
87091 /* Figure out how many bytes of space are required to store explicitly
87092 ** specified collation sequence names.
87094 for(i=0; i<pList->nExpr; i++){
87095 Expr *pExpr = pList->a[i].pExpr;
87096 if( pExpr ){
87097 assert( pExpr->op==TK_COLLATE );
87098 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
87103 ** Allocate the index structure.
87105 nName = sqlite3Strlen30(zName);
87106 nExtraCol = pPk ? pPk->nKeyCol : 1;
87107 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
87108 nName + nExtra + 1, &zExtra);
87109 if( db->mallocFailed ){
87110 goto exit_create_index;
87112 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
87113 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
87114 pIndex->zName = zExtra;
87115 zExtra += nName + 1;
87116 memcpy(pIndex->zName, zName, nName+1);
87117 pIndex->pTable = pTab;
87118 pIndex->onError = (u8)onError;
87119 pIndex->uniqNotNull = onError!=OE_None;
87120 pIndex->autoIndex = (u8)(pName==0);
87121 pIndex->pSchema = db->aDb[iDb].pSchema;
87122 pIndex->nKeyCol = pList->nExpr;
87123 if( pPIWhere ){
87124 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
87125 pIndex->pPartIdxWhere = pPIWhere;
87126 pPIWhere = 0;
87128 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
87130 /* Check to see if we should honor DESC requests on index columns
87132 if( pDb->pSchema->file_format>=4 ){
87133 sortOrderMask = -1; /* Honor DESC */
87134 }else{
87135 sortOrderMask = 0; /* Ignore DESC */
87138 /* Scan the names of the columns of the table to be indexed and
87139 ** load the column indices into the Index structure. Report an error
87140 ** if any column is not found.
87142 ** TODO: Add a test to make sure that the same column is not named
87143 ** more than once within the same index. Only the first instance of
87144 ** the column will ever be used by the optimizer. Note that using the
87145 ** same column more than once cannot be an error because that would
87146 ** break backwards compatibility - it needs to be a warning.
87148 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
87149 const char *zColName = pListItem->zName;
87150 int requestedSortOrder;
87151 char *zColl; /* Collation sequence name */
87153 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
87154 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
87156 if( j>=pTab->nCol ){
87157 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
87158 pTab->zName, zColName);
87159 pParse->checkSchema = 1;
87160 goto exit_create_index;
87162 assert( pTab->nCol<=0x7fff && j<=0x7fff );
87163 pIndex->aiColumn[i] = (i16)j;
87164 if( pListItem->pExpr ){
87165 int nColl;
87166 assert( pListItem->pExpr->op==TK_COLLATE );
87167 zColl = pListItem->pExpr->u.zToken;
87168 nColl = sqlite3Strlen30(zColl) + 1;
87169 assert( nExtra>=nColl );
87170 memcpy(zExtra, zColl, nColl);
87171 zColl = zExtra;
87172 zExtra += nColl;
87173 nExtra -= nColl;
87174 }else{
87175 zColl = pTab->aCol[j].zColl;
87176 if( !zColl ) zColl = "BINARY";
87178 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
87179 goto exit_create_index;
87181 pIndex->azColl[i] = zColl;
87182 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
87183 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
87184 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
87186 if( pPk ){
87187 for(j=0; j<pPk->nKeyCol; j++){
87188 int x = pPk->aiColumn[j];
87189 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
87190 pIndex->nColumn--;
87191 }else{
87192 pIndex->aiColumn[i] = x;
87193 pIndex->azColl[i] = pPk->azColl[j];
87194 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
87195 i++;
87198 assert( i==pIndex->nColumn );
87199 }else{
87200 pIndex->aiColumn[i] = -1;
87201 pIndex->azColl[i] = "BINARY";
87203 sqlite3DefaultRowEst(pIndex);
87204 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
87206 if( pTab==pParse->pNewTable ){
87207 /* This routine has been called to create an automatic index as a
87208 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
87209 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
87210 ** i.e. one of:
87212 ** CREATE TABLE t(x PRIMARY KEY, y);
87213 ** CREATE TABLE t(x, y, UNIQUE(x, y));
87215 ** Either way, check to see if the table already has such an index. If
87216 ** so, don't bother creating this one. This only applies to
87217 ** automatically created indices. Users can do as they wish with
87218 ** explicit indices.
87220 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
87221 ** (and thus suppressing the second one) even if they have different
87222 ** sort orders.
87224 ** If there are different collating sequences or if the columns of
87225 ** the constraint occur in different orders, then the constraints are
87226 ** considered distinct and both result in separate indices.
87228 Index *pIdx;
87229 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
87230 int k;
87231 assert( pIdx->onError!=OE_None );
87232 assert( pIdx->autoIndex );
87233 assert( pIndex->onError!=OE_None );
87235 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
87236 for(k=0; k<pIdx->nKeyCol; k++){
87237 const char *z1;
87238 const char *z2;
87239 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
87240 z1 = pIdx->azColl[k];
87241 z2 = pIndex->azColl[k];
87242 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
87244 if( k==pIdx->nKeyCol ){
87245 if( pIdx->onError!=pIndex->onError ){
87246 /* This constraint creates the same index as a previous
87247 ** constraint specified somewhere in the CREATE TABLE statement.
87248 ** However the ON CONFLICT clauses are different. If both this
87249 ** constraint and the previous equivalent constraint have explicit
87250 ** ON CONFLICT clauses this is an error. Otherwise, use the
87251 ** explicitly specified behavior for the index.
87253 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
87254 sqlite3ErrorMsg(pParse,
87255 "conflicting ON CONFLICT clauses specified", 0);
87257 if( pIdx->onError==OE_Default ){
87258 pIdx->onError = pIndex->onError;
87261 goto exit_create_index;
87266 /* Link the new Index structure to its table and to the other
87267 ** in-memory database structures.
87269 if( db->init.busy ){
87270 Index *p;
87271 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
87272 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
87273 pIndex->zName, sqlite3Strlen30(pIndex->zName),
87274 pIndex);
87275 if( p ){
87276 assert( p==pIndex ); /* Malloc must have failed */
87277 db->mallocFailed = 1;
87278 goto exit_create_index;
87280 db->flags |= SQLITE_InternChanges;
87281 if( pTblName!=0 ){
87282 pIndex->tnum = db->init.newTnum;
87286 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
87287 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
87288 ** emit code to allocate the index rootpage on disk and make an entry for
87289 ** the index in the sqlite_master table and populate the index with
87290 ** content. But, do not do this if we are simply reading the sqlite_master
87291 ** table to parse the schema, or if this index is the PRIMARY KEY index
87292 ** of a WITHOUT ROWID table.
87294 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
87295 ** or UNIQUE index in a CREATE TABLE statement. Since the table
87296 ** has just been created, it contains no data and the index initialization
87297 ** step can be skipped.
87299 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
87300 Vdbe *v;
87301 char *zStmt;
87302 int iMem = ++pParse->nMem;
87304 v = sqlite3GetVdbe(pParse);
87305 if( v==0 ) goto exit_create_index;
87308 /* Create the rootpage for the index
87310 sqlite3BeginWriteOperation(pParse, 1, iDb);
87311 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
87313 /* Gather the complete text of the CREATE INDEX statement into
87314 ** the zStmt variable
87316 if( pStart ){
87317 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
87318 if( pName->z[n-1]==';' ) n--;
87319 /* A named index with an explicit CREATE INDEX statement */
87320 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
87321 onError==OE_None ? "" : " UNIQUE", n, pName->z);
87322 }else{
87323 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
87324 /* zStmt = sqlite3MPrintf(""); */
87325 zStmt = 0;
87328 /* Add an entry in sqlite_master for this index
87330 sqlite3NestedParse(pParse,
87331 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
87332 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
87333 pIndex->zName,
87334 pTab->zName,
87335 iMem,
87336 zStmt
87338 sqlite3DbFree(db, zStmt);
87340 /* Fill the index with data and reparse the schema. Code an OP_Expire
87341 ** to invalidate all pre-compiled statements.
87343 if( pTblName ){
87344 sqlite3RefillIndex(pParse, pIndex, iMem);
87345 sqlite3ChangeCookie(pParse, iDb);
87346 sqlite3VdbeAddParseSchemaOp(v, iDb,
87347 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
87348 sqlite3VdbeAddOp1(v, OP_Expire, 0);
87352 /* When adding an index to the list of indices for a table, make
87353 ** sure all indices labeled OE_Replace come after all those labeled
87354 ** OE_Ignore. This is necessary for the correct constraint check
87355 ** processing (in sqlite3GenerateConstraintChecks()) as part of
87356 ** UPDATE and INSERT statements.
87358 if( db->init.busy || pTblName==0 ){
87359 if( onError!=OE_Replace || pTab->pIndex==0
87360 || pTab->pIndex->onError==OE_Replace){
87361 pIndex->pNext = pTab->pIndex;
87362 pTab->pIndex = pIndex;
87363 }else{
87364 Index *pOther = pTab->pIndex;
87365 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
87366 pOther = pOther->pNext;
87368 pIndex->pNext = pOther->pNext;
87369 pOther->pNext = pIndex;
87371 pRet = pIndex;
87372 pIndex = 0;
87375 /* Clean up before exiting */
87376 exit_create_index:
87377 if( pIndex ) freeIndex(db, pIndex);
87378 sqlite3ExprDelete(db, pPIWhere);
87379 sqlite3ExprListDelete(db, pList);
87380 sqlite3SrcListDelete(db, pTblName);
87381 sqlite3DbFree(db, zName);
87382 return pRet;
87386 ** Fill the Index.aiRowEst[] array with default information - information
87387 ** to be used when we have not run the ANALYZE command.
87389 ** aiRowEst[0] is suppose to contain the number of elements in the index.
87390 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
87391 ** number of rows in the table that match any particular value of the
87392 ** first column of the index. aiRowEst[2] is an estimate of the number
87393 ** of rows that match any particular combiniation of the first 2 columns
87394 ** of the index. And so forth. It must always be the case that
87396 ** aiRowEst[N]<=aiRowEst[N-1]
87397 ** aiRowEst[N]>=1
87399 ** Apart from that, we have little to go on besides intuition as to
87400 ** how aiRowEst[] should be initialized. The numbers generated here
87401 ** are based on typical values found in actual indices.
87403 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
87404 tRowcnt *a = pIdx->aiRowEst;
87405 int i;
87406 tRowcnt n;
87407 assert( a!=0 );
87408 a[0] = pIdx->pTable->nRowEst;
87409 if( a[0]<10 ) a[0] = 10;
87410 n = 10;
87411 for(i=1; i<=pIdx->nKeyCol; i++){
87412 a[i] = n;
87413 if( n>5 ) n--;
87415 if( pIdx->onError!=OE_None ){
87416 a[pIdx->nKeyCol] = 1;
87421 ** This routine will drop an existing named index. This routine
87422 ** implements the DROP INDEX statement.
87424 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
87425 Index *pIndex;
87426 Vdbe *v;
87427 sqlite3 *db = pParse->db;
87428 int iDb;
87430 assert( pParse->nErr==0 ); /* Never called with prior errors */
87431 if( db->mallocFailed ){
87432 goto exit_drop_index;
87434 assert( pName->nSrc==1 );
87435 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
87436 goto exit_drop_index;
87438 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
87439 if( pIndex==0 ){
87440 if( !ifExists ){
87441 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
87442 }else{
87443 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
87445 pParse->checkSchema = 1;
87446 goto exit_drop_index;
87448 if( pIndex->autoIndex ){
87449 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
87450 "or PRIMARY KEY constraint cannot be dropped", 0);
87451 goto exit_drop_index;
87453 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
87454 #ifndef SQLITE_OMIT_AUTHORIZATION
87456 int code = SQLITE_DROP_INDEX;
87457 Table *pTab = pIndex->pTable;
87458 const char *zDb = db->aDb[iDb].zName;
87459 const char *zTab = SCHEMA_TABLE(iDb);
87460 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
87461 goto exit_drop_index;
87463 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
87464 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
87465 goto exit_drop_index;
87468 #endif
87470 /* Generate code to remove the index and from the master table */
87471 v = sqlite3GetVdbe(pParse);
87472 if( v ){
87473 sqlite3BeginWriteOperation(pParse, 1, iDb);
87474 sqlite3NestedParse(pParse,
87475 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
87476 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
87478 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
87479 sqlite3ChangeCookie(pParse, iDb);
87480 destroyRootPage(pParse, pIndex->tnum, iDb);
87481 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
87484 exit_drop_index:
87485 sqlite3SrcListDelete(db, pName);
87489 ** pArray is a pointer to an array of objects. Each object in the
87490 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
87491 ** to extend the array so that there is space for a new object at the end.
87493 ** When this function is called, *pnEntry contains the current size of
87494 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
87495 ** in total).
87497 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
87498 ** space allocated for the new object is zeroed, *pnEntry updated to
87499 ** reflect the new size of the array and a pointer to the new allocation
87500 ** returned. *pIdx is set to the index of the new array entry in this case.
87502 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
87503 ** unchanged and a copy of pArray returned.
87505 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
87506 sqlite3 *db, /* Connection to notify of malloc failures */
87507 void *pArray, /* Array of objects. Might be reallocated */
87508 int szEntry, /* Size of each object in the array */
87509 int *pnEntry, /* Number of objects currently in use */
87510 int *pIdx /* Write the index of a new slot here */
87512 char *z;
87513 int n = *pnEntry;
87514 if( (n & (n-1))==0 ){
87515 int sz = (n==0) ? 1 : 2*n;
87516 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
87517 if( pNew==0 ){
87518 *pIdx = -1;
87519 return pArray;
87521 pArray = pNew;
87523 z = (char*)pArray;
87524 memset(&z[n * szEntry], 0, szEntry);
87525 *pIdx = n;
87526 ++*pnEntry;
87527 return pArray;
87531 ** Append a new element to the given IdList. Create a new IdList if
87532 ** need be.
87534 ** A new IdList is returned, or NULL if malloc() fails.
87536 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
87537 int i;
87538 if( pList==0 ){
87539 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
87540 if( pList==0 ) return 0;
87542 pList->a = sqlite3ArrayAllocate(
87544 pList->a,
87545 sizeof(pList->a[0]),
87546 &pList->nId,
87549 if( i<0 ){
87550 sqlite3IdListDelete(db, pList);
87551 return 0;
87553 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
87554 return pList;
87558 ** Delete an IdList.
87560 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
87561 int i;
87562 if( pList==0 ) return;
87563 for(i=0; i<pList->nId; i++){
87564 sqlite3DbFree(db, pList->a[i].zName);
87566 sqlite3DbFree(db, pList->a);
87567 sqlite3DbFree(db, pList);
87571 ** Return the index in pList of the identifier named zId. Return -1
87572 ** if not found.
87574 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
87575 int i;
87576 if( pList==0 ) return -1;
87577 for(i=0; i<pList->nId; i++){
87578 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
87580 return -1;
87584 ** Expand the space allocated for the given SrcList object by
87585 ** creating nExtra new slots beginning at iStart. iStart is zero based.
87586 ** New slots are zeroed.
87588 ** For example, suppose a SrcList initially contains two entries: A,B.
87589 ** To append 3 new entries onto the end, do this:
87591 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
87593 ** After the call above it would contain: A, B, nil, nil, nil.
87594 ** If the iStart argument had been 1 instead of 2, then the result
87595 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
87596 ** the iStart value would be 0. The result then would
87597 ** be: nil, nil, nil, A, B.
87599 ** If a memory allocation fails the SrcList is unchanged. The
87600 ** db->mallocFailed flag will be set to true.
87602 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
87603 sqlite3 *db, /* Database connection to notify of OOM errors */
87604 SrcList *pSrc, /* The SrcList to be enlarged */
87605 int nExtra, /* Number of new slots to add to pSrc->a[] */
87606 int iStart /* Index in pSrc->a[] of first new slot */
87608 int i;
87610 /* Sanity checking on calling parameters */
87611 assert( iStart>=0 );
87612 assert( nExtra>=1 );
87613 assert( pSrc!=0 );
87614 assert( iStart<=pSrc->nSrc );
87616 /* Allocate additional space if needed */
87617 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
87618 SrcList *pNew;
87619 int nAlloc = pSrc->nSrc+nExtra;
87620 int nGot;
87621 pNew = sqlite3DbRealloc(db, pSrc,
87622 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
87623 if( pNew==0 ){
87624 assert( db->mallocFailed );
87625 return pSrc;
87627 pSrc = pNew;
87628 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
87629 pSrc->nAlloc = (u8)nGot;
87632 /* Move existing slots that come after the newly inserted slots
87633 ** out of the way */
87634 for(i=pSrc->nSrc-1; i>=iStart; i--){
87635 pSrc->a[i+nExtra] = pSrc->a[i];
87637 pSrc->nSrc += (i8)nExtra;
87639 /* Zero the newly allocated slots */
87640 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
87641 for(i=iStart; i<iStart+nExtra; i++){
87642 pSrc->a[i].iCursor = -1;
87645 /* Return a pointer to the enlarged SrcList */
87646 return pSrc;
87651 ** Append a new table name to the given SrcList. Create a new SrcList if
87652 ** need be. A new entry is created in the SrcList even if pTable is NULL.
87654 ** A SrcList is returned, or NULL if there is an OOM error. The returned
87655 ** SrcList might be the same as the SrcList that was input or it might be
87656 ** a new one. If an OOM error does occurs, then the prior value of pList
87657 ** that is input to this routine is automatically freed.
87659 ** If pDatabase is not null, it means that the table has an optional
87660 ** database name prefix. Like this: "database.table". The pDatabase
87661 ** points to the table name and the pTable points to the database name.
87662 ** The SrcList.a[].zName field is filled with the table name which might
87663 ** come from pTable (if pDatabase is NULL) or from pDatabase.
87664 ** SrcList.a[].zDatabase is filled with the database name from pTable,
87665 ** or with NULL if no database is specified.
87667 ** In other words, if call like this:
87669 ** sqlite3SrcListAppend(D,A,B,0);
87671 ** Then B is a table name and the database name is unspecified. If called
87672 ** like this:
87674 ** sqlite3SrcListAppend(D,A,B,C);
87676 ** Then C is the table name and B is the database name. If C is defined
87677 ** then so is B. In other words, we never have a case where:
87679 ** sqlite3SrcListAppend(D,A,0,C);
87681 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
87682 ** before being added to the SrcList.
87684 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
87685 sqlite3 *db, /* Connection to notify of malloc failures */
87686 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
87687 Token *pTable, /* Table to append */
87688 Token *pDatabase /* Database of the table */
87690 struct SrcList_item *pItem;
87691 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
87692 if( pList==0 ){
87693 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
87694 if( pList==0 ) return 0;
87695 pList->nAlloc = 1;
87697 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
87698 if( db->mallocFailed ){
87699 sqlite3SrcListDelete(db, pList);
87700 return 0;
87702 pItem = &pList->a[pList->nSrc-1];
87703 if( pDatabase && pDatabase->z==0 ){
87704 pDatabase = 0;
87706 if( pDatabase ){
87707 Token *pTemp = pDatabase;
87708 pDatabase = pTable;
87709 pTable = pTemp;
87711 pItem->zName = sqlite3NameFromToken(db, pTable);
87712 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
87713 return pList;
87717 ** Assign VdbeCursor index numbers to all tables in a SrcList
87719 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
87720 int i;
87721 struct SrcList_item *pItem;
87722 assert(pList || pParse->db->mallocFailed );
87723 if( pList ){
87724 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
87725 if( pItem->iCursor>=0 ) break;
87726 pItem->iCursor = pParse->nTab++;
87727 if( pItem->pSelect ){
87728 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
87735 ** Delete an entire SrcList including all its substructure.
87737 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
87738 int i;
87739 struct SrcList_item *pItem;
87740 if( pList==0 ) return;
87741 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
87742 sqlite3DbFree(db, pItem->zDatabase);
87743 sqlite3DbFree(db, pItem->zName);
87744 sqlite3DbFree(db, pItem->zAlias);
87745 sqlite3DbFree(db, pItem->zIndex);
87746 sqlite3DeleteTable(db, pItem->pTab);
87747 sqlite3SelectDelete(db, pItem->pSelect);
87748 sqlite3ExprDelete(db, pItem->pOn);
87749 sqlite3IdListDelete(db, pItem->pUsing);
87751 sqlite3DbFree(db, pList);
87755 ** This routine is called by the parser to add a new term to the
87756 ** end of a growing FROM clause. The "p" parameter is the part of
87757 ** the FROM clause that has already been constructed. "p" is NULL
87758 ** if this is the first term of the FROM clause. pTable and pDatabase
87759 ** are the name of the table and database named in the FROM clause term.
87760 ** pDatabase is NULL if the database name qualifier is missing - the
87761 ** usual case. If the term has a alias, then pAlias points to the
87762 ** alias token. If the term is a subquery, then pSubquery is the
87763 ** SELECT statement that the subquery encodes. The pTable and
87764 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
87765 ** parameters are the content of the ON and USING clauses.
87767 ** Return a new SrcList which encodes is the FROM with the new
87768 ** term added.
87770 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
87771 Parse *pParse, /* Parsing context */
87772 SrcList *p, /* The left part of the FROM clause already seen */
87773 Token *pTable, /* Name of the table to add to the FROM clause */
87774 Token *pDatabase, /* Name of the database containing pTable */
87775 Token *pAlias, /* The right-hand side of the AS subexpression */
87776 Select *pSubquery, /* A subquery used in place of a table name */
87777 Expr *pOn, /* The ON clause of a join */
87778 IdList *pUsing /* The USING clause of a join */
87780 struct SrcList_item *pItem;
87781 sqlite3 *db = pParse->db;
87782 if( !p && (pOn || pUsing) ){
87783 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
87784 (pOn ? "ON" : "USING")
87786 goto append_from_error;
87788 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
87789 if( p==0 || NEVER(p->nSrc==0) ){
87790 goto append_from_error;
87792 pItem = &p->a[p->nSrc-1];
87793 assert( pAlias!=0 );
87794 if( pAlias->n ){
87795 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
87797 pItem->pSelect = pSubquery;
87798 pItem->pOn = pOn;
87799 pItem->pUsing = pUsing;
87800 return p;
87802 append_from_error:
87803 assert( p==0 );
87804 sqlite3ExprDelete(db, pOn);
87805 sqlite3IdListDelete(db, pUsing);
87806 sqlite3SelectDelete(db, pSubquery);
87807 return 0;
87811 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
87812 ** element of the source-list passed as the second argument.
87814 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
87815 assert( pIndexedBy!=0 );
87816 if( p && ALWAYS(p->nSrc>0) ){
87817 struct SrcList_item *pItem = &p->a[p->nSrc-1];
87818 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
87819 if( pIndexedBy->n==1 && !pIndexedBy->z ){
87820 /* A "NOT INDEXED" clause was supplied. See parse.y
87821 ** construct "indexed_opt" for details. */
87822 pItem->notIndexed = 1;
87823 }else{
87824 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
87830 ** When building up a FROM clause in the parser, the join operator
87831 ** is initially attached to the left operand. But the code generator
87832 ** expects the join operator to be on the right operand. This routine
87833 ** Shifts all join operators from left to right for an entire FROM
87834 ** clause.
87836 ** Example: Suppose the join is like this:
87838 ** A natural cross join B
87840 ** The operator is "natural cross join". The A and B operands are stored
87841 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
87842 ** operator with A. This routine shifts that operator over to B.
87844 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
87845 if( p ){
87846 int i;
87847 assert( p->a || p->nSrc==0 );
87848 for(i=p->nSrc-1; i>0; i--){
87849 p->a[i].jointype = p->a[i-1].jointype;
87851 p->a[0].jointype = 0;
87856 ** Begin a transaction
87858 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
87859 sqlite3 *db;
87860 Vdbe *v;
87861 int i;
87863 assert( pParse!=0 );
87864 db = pParse->db;
87865 assert( db!=0 );
87866 /* if( db->aDb[0].pBt==0 ) return; */
87867 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
87868 return;
87870 v = sqlite3GetVdbe(pParse);
87871 if( !v ) return;
87872 if( type!=TK_DEFERRED ){
87873 for(i=0; i<db->nDb; i++){
87874 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
87875 sqlite3VdbeUsesBtree(v, i);
87878 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
87882 ** Commit a transaction
87884 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
87885 Vdbe *v;
87887 assert( pParse!=0 );
87888 assert( pParse->db!=0 );
87889 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
87890 return;
87892 v = sqlite3GetVdbe(pParse);
87893 if( v ){
87894 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
87899 ** Rollback a transaction
87901 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
87902 Vdbe *v;
87904 assert( pParse!=0 );
87905 assert( pParse->db!=0 );
87906 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
87907 return;
87909 v = sqlite3GetVdbe(pParse);
87910 if( v ){
87911 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
87916 ** This function is called by the parser when it parses a command to create,
87917 ** release or rollback an SQL savepoint.
87919 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
87920 char *zName = sqlite3NameFromToken(pParse->db, pName);
87921 if( zName ){
87922 Vdbe *v = sqlite3GetVdbe(pParse);
87923 #ifndef SQLITE_OMIT_AUTHORIZATION
87924 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
87925 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
87926 #endif
87927 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
87928 sqlite3DbFree(pParse->db, zName);
87929 return;
87931 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
87936 ** Make sure the TEMP database is open and available for use. Return
87937 ** the number of errors. Leave any error messages in the pParse structure.
87939 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
87940 sqlite3 *db = pParse->db;
87941 if( db->aDb[1].pBt==0 && !pParse->explain ){
87942 int rc;
87943 Btree *pBt;
87944 static const int flags =
87945 SQLITE_OPEN_READWRITE |
87946 SQLITE_OPEN_CREATE |
87947 SQLITE_OPEN_EXCLUSIVE |
87948 SQLITE_OPEN_DELETEONCLOSE |
87949 SQLITE_OPEN_TEMP_DB;
87951 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
87952 if( rc!=SQLITE_OK ){
87953 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
87954 "file for storing temporary tables");
87955 pParse->rc = rc;
87956 return 1;
87958 db->aDb[1].pBt = pBt;
87959 assert( db->aDb[1].pSchema );
87960 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
87961 db->mallocFailed = 1;
87962 return 1;
87965 return 0;
87969 ** Generate VDBE code that will verify the schema cookie and start
87970 ** a read-transaction for all named database files.
87972 ** It is important that all schema cookies be verified and all
87973 ** read transactions be started before anything else happens in
87974 ** the VDBE program. But this routine can be called after much other
87975 ** code has been generated. So here is what we do:
87977 ** The first time this routine is called, we code an OP_Goto that
87978 ** will jump to a subroutine at the end of the program. Then we
87979 ** record every database that needs its schema verified in the
87980 ** pParse->cookieMask field. Later, after all other code has been
87981 ** generated, the subroutine that does the cookie verifications and
87982 ** starts the transactions will be coded and the OP_Goto P2 value
87983 ** will be made to point to that subroutine. The generation of the
87984 ** cookie verification subroutine code happens in sqlite3FinishCoding().
87986 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
87987 ** schema on any databases. This can be used to position the OP_Goto
87988 ** early in the code, before we know if any database tables will be used.
87990 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
87991 Parse *pToplevel = sqlite3ParseToplevel(pParse);
87993 #ifndef SQLITE_OMIT_TRIGGER
87994 if( pToplevel!=pParse ){
87995 /* This branch is taken if a trigger is currently being coded. In this
87996 ** case, set cookieGoto to a non-zero value to show that this function
87997 ** has been called. This is used by the sqlite3ExprCodeConstants()
87998 ** function. */
87999 pParse->cookieGoto = -1;
88001 #endif
88002 if( pToplevel->cookieGoto==0 ){
88003 Vdbe *v = sqlite3GetVdbe(pToplevel);
88004 if( v==0 ) return; /* This only happens if there was a prior error */
88005 pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
88007 if( iDb>=0 ){
88008 sqlite3 *db = pToplevel->db;
88009 yDbMask mask;
88011 assert( iDb<db->nDb );
88012 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
88013 assert( iDb<SQLITE_MAX_ATTACHED+2 );
88014 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88015 mask = ((yDbMask)1)<<iDb;
88016 if( (pToplevel->cookieMask & mask)==0 ){
88017 pToplevel->cookieMask |= mask;
88018 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
88019 if( !OMIT_TEMPDB && iDb==1 ){
88020 sqlite3OpenTempDatabase(pToplevel);
88027 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
88028 ** attached database. Otherwise, invoke it for the database named zDb only.
88030 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
88031 sqlite3 *db = pParse->db;
88032 int i;
88033 for(i=0; i<db->nDb; i++){
88034 Db *pDb = &db->aDb[i];
88035 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
88036 sqlite3CodeVerifySchema(pParse, i);
88042 ** Generate VDBE code that prepares for doing an operation that
88043 ** might change the database.
88045 ** This routine starts a new transaction if we are not already within
88046 ** a transaction. If we are already within a transaction, then a checkpoint
88047 ** is set if the setStatement parameter is true. A checkpoint should
88048 ** be set for operations that might fail (due to a constraint) part of
88049 ** the way through and which will need to undo some writes without having to
88050 ** rollback the whole transaction. For operations where all constraints
88051 ** can be checked before any changes are made to the database, it is never
88052 ** necessary to undo a write and the checkpoint should not be set.
88054 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
88055 Parse *pToplevel = sqlite3ParseToplevel(pParse);
88056 sqlite3CodeVerifySchema(pParse, iDb);
88057 pToplevel->writeMask |= ((yDbMask)1)<<iDb;
88058 pToplevel->isMultiWrite |= setStatement;
88062 ** Indicate that the statement currently under construction might write
88063 ** more than one entry (example: deleting one row then inserting another,
88064 ** inserting multiple rows in a table, or inserting a row and index entries.)
88065 ** If an abort occurs after some of these writes have completed, then it will
88066 ** be necessary to undo the completed writes.
88068 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
88069 Parse *pToplevel = sqlite3ParseToplevel(pParse);
88070 pToplevel->isMultiWrite = 1;
88074 ** The code generator calls this routine if is discovers that it is
88075 ** possible to abort a statement prior to completion. In order to
88076 ** perform this abort without corrupting the database, we need to make
88077 ** sure that the statement is protected by a statement transaction.
88079 ** Technically, we only need to set the mayAbort flag if the
88080 ** isMultiWrite flag was previously set. There is a time dependency
88081 ** such that the abort must occur after the multiwrite. This makes
88082 ** some statements involving the REPLACE conflict resolution algorithm
88083 ** go a little faster. But taking advantage of this time dependency
88084 ** makes it more difficult to prove that the code is correct (in
88085 ** particular, it prevents us from writing an effective
88086 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
88087 ** to take the safe route and skip the optimization.
88089 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
88090 Parse *pToplevel = sqlite3ParseToplevel(pParse);
88091 pToplevel->mayAbort = 1;
88095 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
88096 ** error. The onError parameter determines which (if any) of the statement
88097 ** and/or current transaction is rolled back.
88099 SQLITE_PRIVATE void sqlite3HaltConstraint(
88100 Parse *pParse, /* Parsing context */
88101 int errCode, /* extended error code */
88102 int onError, /* Constraint type */
88103 char *p4, /* Error message */
88104 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
88105 u8 p5Errmsg /* P5_ErrMsg type */
88107 Vdbe *v = sqlite3GetVdbe(pParse);
88108 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
88109 if( onError==OE_Abort ){
88110 sqlite3MayAbort(pParse);
88112 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
88113 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
88117 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
88119 SQLITE_PRIVATE void sqlite3UniqueConstraint(
88120 Parse *pParse, /* Parsing context */
88121 int onError, /* Constraint type */
88122 Index *pIdx /* The index that triggers the constraint */
88124 char *zErr;
88125 int j;
88126 StrAccum errMsg;
88127 Table *pTab = pIdx->pTable;
88129 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
88130 errMsg.db = pParse->db;
88131 for(j=0; j<pIdx->nKeyCol; j++){
88132 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
88133 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
88134 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
88135 sqlite3StrAccumAppend(&errMsg, ".", 1);
88136 sqlite3StrAccumAppendAll(&errMsg, zCol);
88138 zErr = sqlite3StrAccumFinish(&errMsg);
88139 sqlite3HaltConstraint(pParse,
88140 (pIdx->autoIndex==2)?SQLITE_CONSTRAINT_PRIMARYKEY:SQLITE_CONSTRAINT_UNIQUE,
88141 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
88146 ** Code an OP_Halt due to non-unique rowid.
88148 SQLITE_PRIVATE void sqlite3RowidConstraint(
88149 Parse *pParse, /* Parsing context */
88150 int onError, /* Conflict resolution algorithm */
88151 Table *pTab /* The table with the non-unique rowid */
88153 char *zMsg;
88154 int rc;
88155 if( pTab->iPKey>=0 ){
88156 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
88157 pTab->aCol[pTab->iPKey].zName);
88158 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
88159 }else{
88160 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
88161 rc = SQLITE_CONSTRAINT_ROWID;
88163 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
88164 P5_ConstraintUnique);
88168 ** Check to see if pIndex uses the collating sequence pColl. Return
88169 ** true if it does and false if it does not.
88171 #ifndef SQLITE_OMIT_REINDEX
88172 static int collationMatch(const char *zColl, Index *pIndex){
88173 int i;
88174 assert( zColl!=0 );
88175 for(i=0; i<pIndex->nColumn; i++){
88176 const char *z = pIndex->azColl[i];
88177 assert( z!=0 || pIndex->aiColumn[i]<0 );
88178 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
88179 return 1;
88182 return 0;
88184 #endif
88187 ** Recompute all indices of pTab that use the collating sequence pColl.
88188 ** If pColl==0 then recompute all indices of pTab.
88190 #ifndef SQLITE_OMIT_REINDEX
88191 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
88192 Index *pIndex; /* An index associated with pTab */
88194 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
88195 if( zColl==0 || collationMatch(zColl, pIndex) ){
88196 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
88197 sqlite3BeginWriteOperation(pParse, 0, iDb);
88198 sqlite3RefillIndex(pParse, pIndex, -1);
88202 #endif
88205 ** Recompute all indices of all tables in all databases where the
88206 ** indices use the collating sequence pColl. If pColl==0 then recompute
88207 ** all indices everywhere.
88209 #ifndef SQLITE_OMIT_REINDEX
88210 static void reindexDatabases(Parse *pParse, char const *zColl){
88211 Db *pDb; /* A single database */
88212 int iDb; /* The database index number */
88213 sqlite3 *db = pParse->db; /* The database connection */
88214 HashElem *k; /* For looping over tables in pDb */
88215 Table *pTab; /* A table in the database */
88217 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
88218 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
88219 assert( pDb!=0 );
88220 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
88221 pTab = (Table*)sqliteHashData(k);
88222 reindexTable(pParse, pTab, zColl);
88226 #endif
88229 ** Generate code for the REINDEX command.
88231 ** REINDEX -- 1
88232 ** REINDEX <collation> -- 2
88233 ** REINDEX ?<database>.?<tablename> -- 3
88234 ** REINDEX ?<database>.?<indexname> -- 4
88236 ** Form 1 causes all indices in all attached databases to be rebuilt.
88237 ** Form 2 rebuilds all indices in all databases that use the named
88238 ** collating function. Forms 3 and 4 rebuild the named index or all
88239 ** indices associated with the named table.
88241 #ifndef SQLITE_OMIT_REINDEX
88242 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
88243 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
88244 char *z; /* Name of a table or index */
88245 const char *zDb; /* Name of the database */
88246 Table *pTab; /* A table in the database */
88247 Index *pIndex; /* An index associated with pTab */
88248 int iDb; /* The database index number */
88249 sqlite3 *db = pParse->db; /* The database connection */
88250 Token *pObjName; /* Name of the table or index to be reindexed */
88252 /* Read the database schema. If an error occurs, leave an error message
88253 ** and code in pParse and return NULL. */
88254 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
88255 return;
88258 if( pName1==0 ){
88259 reindexDatabases(pParse, 0);
88260 return;
88261 }else if( NEVER(pName2==0) || pName2->z==0 ){
88262 char *zColl;
88263 assert( pName1->z );
88264 zColl = sqlite3NameFromToken(pParse->db, pName1);
88265 if( !zColl ) return;
88266 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
88267 if( pColl ){
88268 reindexDatabases(pParse, zColl);
88269 sqlite3DbFree(db, zColl);
88270 return;
88272 sqlite3DbFree(db, zColl);
88274 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
88275 if( iDb<0 ) return;
88276 z = sqlite3NameFromToken(db, pObjName);
88277 if( z==0 ) return;
88278 zDb = db->aDb[iDb].zName;
88279 pTab = sqlite3FindTable(db, z, zDb);
88280 if( pTab ){
88281 reindexTable(pParse, pTab, 0);
88282 sqlite3DbFree(db, z);
88283 return;
88285 pIndex = sqlite3FindIndex(db, z, zDb);
88286 sqlite3DbFree(db, z);
88287 if( pIndex ){
88288 sqlite3BeginWriteOperation(pParse, 0, iDb);
88289 sqlite3RefillIndex(pParse, pIndex, -1);
88290 return;
88292 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
88294 #endif
88297 ** Return a KeyInfo structure that is appropriate for the given Index.
88299 ** The KeyInfo structure for an index is cached in the Index object.
88300 ** So there might be multiple references to the returned pointer. The
88301 ** caller should not try to modify the KeyInfo object.
88303 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
88304 ** when it has finished using it.
88306 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
88307 if( pParse->nErr ) return 0;
88308 #ifndef SQLITE_OMIT_SHARED_CACHE
88309 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
88310 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
88311 pIdx->pKeyInfo = 0;
88313 #endif
88314 if( pIdx->pKeyInfo==0 ){
88315 int i;
88316 int nCol = pIdx->nColumn;
88317 int nKey = pIdx->nKeyCol;
88318 KeyInfo *pKey;
88319 if( pIdx->uniqNotNull ){
88320 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
88321 }else{
88322 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
88324 if( pKey ){
88325 assert( sqlite3KeyInfoIsWriteable(pKey) );
88326 for(i=0; i<nCol; i++){
88327 char *zColl = pIdx->azColl[i];
88328 assert( zColl!=0 );
88329 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
88330 sqlite3LocateCollSeq(pParse, zColl);
88331 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
88333 if( pParse->nErr ){
88334 sqlite3KeyInfoUnref(pKey);
88335 }else{
88336 pIdx->pKeyInfo = pKey;
88340 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
88343 #ifndef SQLITE_OMIT_CTE
88345 ** This routine is invoked once per CTE by the parser while parsing a
88346 ** WITH clause.
88348 SQLITE_PRIVATE With *sqlite3WithAdd(
88349 Parse *pParse, /* Parsing context */
88350 With *pWith, /* Existing WITH clause, or NULL */
88351 Token *pName, /* Name of the common-table */
88352 ExprList *pArglist, /* Optional column name list for the table */
88353 Select *pQuery /* Query used to initialize the table */
88355 sqlite3 *db = pParse->db;
88356 With *pNew;
88357 char *zName;
88359 /* Check that the CTE name is unique within this WITH clause. If
88360 ** not, store an error in the Parse structure. */
88361 zName = sqlite3NameFromToken(pParse->db, pName);
88362 if( zName && pWith ){
88363 int i;
88364 for(i=0; i<pWith->nCte; i++){
88365 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
88366 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
88371 if( pWith ){
88372 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
88373 pNew = sqlite3DbRealloc(db, pWith, nByte);
88374 }else{
88375 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
88377 assert( zName!=0 || pNew==0 );
88378 assert( db->mallocFailed==0 || pNew==0 );
88380 if( pNew==0 ){
88381 sqlite3ExprListDelete(db, pArglist);
88382 sqlite3SelectDelete(db, pQuery);
88383 sqlite3DbFree(db, zName);
88384 pNew = pWith;
88385 }else{
88386 pNew->a[pNew->nCte].pSelect = pQuery;
88387 pNew->a[pNew->nCte].pCols = pArglist;
88388 pNew->a[pNew->nCte].zName = zName;
88389 pNew->a[pNew->nCte].zErr = 0;
88390 pNew->nCte++;
88393 return pNew;
88397 ** Free the contents of the With object passed as the second argument.
88399 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
88400 if( pWith ){
88401 int i;
88402 for(i=0; i<pWith->nCte; i++){
88403 struct Cte *pCte = &pWith->a[i];
88404 sqlite3ExprListDelete(db, pCte->pCols);
88405 sqlite3SelectDelete(db, pCte->pSelect);
88406 sqlite3DbFree(db, pCte->zName);
88408 sqlite3DbFree(db, pWith);
88411 #endif /* !defined(SQLITE_OMIT_CTE) */
88413 /************** End of build.c ***********************************************/
88414 /************** Begin file callback.c ****************************************/
88416 ** 2005 May 23
88418 ** The author disclaims copyright to this source code. In place of
88419 ** a legal notice, here is a blessing:
88421 ** May you do good and not evil.
88422 ** May you find forgiveness for yourself and forgive others.
88423 ** May you share freely, never taking more than you give.
88425 *************************************************************************
88427 ** This file contains functions used to access the internal hash tables
88428 ** of user defined functions and collation sequences.
88433 ** Invoke the 'collation needed' callback to request a collation sequence
88434 ** in the encoding enc of name zName, length nName.
88436 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
88437 assert( !db->xCollNeeded || !db->xCollNeeded16 );
88438 if( db->xCollNeeded ){
88439 char *zExternal = sqlite3DbStrDup(db, zName);
88440 if( !zExternal ) return;
88441 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
88442 sqlite3DbFree(db, zExternal);
88444 #ifndef SQLITE_OMIT_UTF16
88445 if( db->xCollNeeded16 ){
88446 char const *zExternal;
88447 sqlite3_value *pTmp = sqlite3ValueNew(db);
88448 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
88449 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
88450 if( zExternal ){
88451 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
88453 sqlite3ValueFree(pTmp);
88455 #endif
88459 ** This routine is called if the collation factory fails to deliver a
88460 ** collation function in the best encoding but there may be other versions
88461 ** of this collation function (for other text encodings) available. Use one
88462 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
88463 ** possible.
88465 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
88466 CollSeq *pColl2;
88467 char *z = pColl->zName;
88468 int i;
88469 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
88470 for(i=0; i<3; i++){
88471 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
88472 if( pColl2->xCmp!=0 ){
88473 memcpy(pColl, pColl2, sizeof(CollSeq));
88474 pColl->xDel = 0; /* Do not copy the destructor */
88475 return SQLITE_OK;
88478 return SQLITE_ERROR;
88482 ** This function is responsible for invoking the collation factory callback
88483 ** or substituting a collation sequence of a different encoding when the
88484 ** requested collation sequence is not available in the desired encoding.
88486 ** If it is not NULL, then pColl must point to the database native encoding
88487 ** collation sequence with name zName, length nName.
88489 ** The return value is either the collation sequence to be used in database
88490 ** db for collation type name zName, length nName, or NULL, if no collation
88491 ** sequence can be found. If no collation is found, leave an error message.
88493 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
88495 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
88496 Parse *pParse, /* Parsing context */
88497 u8 enc, /* The desired encoding for the collating sequence */
88498 CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
88499 const char *zName /* Collating sequence name */
88501 CollSeq *p;
88502 sqlite3 *db = pParse->db;
88504 p = pColl;
88505 if( !p ){
88506 p = sqlite3FindCollSeq(db, enc, zName, 0);
88508 if( !p || !p->xCmp ){
88509 /* No collation sequence of this type for this encoding is registered.
88510 ** Call the collation factory to see if it can supply us with one.
88512 callCollNeeded(db, enc, zName);
88513 p = sqlite3FindCollSeq(db, enc, zName, 0);
88515 if( p && !p->xCmp && synthCollSeq(db, p) ){
88516 p = 0;
88518 assert( !p || p->xCmp );
88519 if( p==0 ){
88520 sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
88522 return p;
88526 ** This routine is called on a collation sequence before it is used to
88527 ** check that it is defined. An undefined collation sequence exists when
88528 ** a database is loaded that contains references to collation sequences
88529 ** that have not been defined by sqlite3_create_collation() etc.
88531 ** If required, this routine calls the 'collation needed' callback to
88532 ** request a definition of the collating sequence. If this doesn't work,
88533 ** an equivalent collating sequence that uses a text encoding different
88534 ** from the main database is substituted, if one is available.
88536 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
88537 if( pColl ){
88538 const char *zName = pColl->zName;
88539 sqlite3 *db = pParse->db;
88540 CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
88541 if( !p ){
88542 return SQLITE_ERROR;
88544 assert( p==pColl );
88546 return SQLITE_OK;
88552 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
88553 ** specified by zName and nName is not found and parameter 'create' is
88554 ** true, then create a new entry. Otherwise return NULL.
88556 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
88557 ** array of three CollSeq structures. The first is the collation sequence
88558 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
88560 ** Stored immediately after the three collation sequences is a copy of
88561 ** the collation sequence name. A pointer to this string is stored in
88562 ** each collation sequence structure.
88564 static CollSeq *findCollSeqEntry(
88565 sqlite3 *db, /* Database connection */
88566 const char *zName, /* Name of the collating sequence */
88567 int create /* Create a new entry if true */
88569 CollSeq *pColl;
88570 int nName = sqlite3Strlen30(zName);
88571 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
88573 if( 0==pColl && create ){
88574 pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
88575 if( pColl ){
88576 CollSeq *pDel = 0;
88577 pColl[0].zName = (char*)&pColl[3];
88578 pColl[0].enc = SQLITE_UTF8;
88579 pColl[1].zName = (char*)&pColl[3];
88580 pColl[1].enc = SQLITE_UTF16LE;
88581 pColl[2].zName = (char*)&pColl[3];
88582 pColl[2].enc = SQLITE_UTF16BE;
88583 memcpy(pColl[0].zName, zName, nName);
88584 pColl[0].zName[nName] = 0;
88585 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
88587 /* If a malloc() failure occurred in sqlite3HashInsert(), it will
88588 ** return the pColl pointer to be deleted (because it wasn't added
88589 ** to the hash table).
88591 assert( pDel==0 || pDel==pColl );
88592 if( pDel!=0 ){
88593 db->mallocFailed = 1;
88594 sqlite3DbFree(db, pDel);
88595 pColl = 0;
88599 return pColl;
88603 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
88604 ** Return the CollSeq* pointer for the collation sequence named zName
88605 ** for the encoding 'enc' from the database 'db'.
88607 ** If the entry specified is not found and 'create' is true, then create a
88608 ** new entry. Otherwise return NULL.
88610 ** A separate function sqlite3LocateCollSeq() is a wrapper around
88611 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
88612 ** if necessary and generates an error message if the collating sequence
88613 ** cannot be found.
88615 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
88617 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
88618 sqlite3 *db,
88619 u8 enc,
88620 const char *zName,
88621 int create
88623 CollSeq *pColl;
88624 if( zName ){
88625 pColl = findCollSeqEntry(db, zName, create);
88626 }else{
88627 pColl = db->pDfltColl;
88629 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
88630 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
88631 if( pColl ) pColl += enc-1;
88632 return pColl;
88635 /* During the search for the best function definition, this procedure
88636 ** is called to test how well the function passed as the first argument
88637 ** matches the request for a function with nArg arguments in a system
88638 ** that uses encoding enc. The value returned indicates how well the
88639 ** request is matched. A higher value indicates a better match.
88641 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
88642 ** is also -1. In other words, we are searching for a function that
88643 ** takes a variable number of arguments.
88645 ** If nArg is -2 that means that we are searching for any function
88646 ** regardless of the number of arguments it uses, so return a positive
88647 ** match score for any
88649 ** The returned value is always between 0 and 6, as follows:
88651 ** 0: Not a match.
88652 ** 1: UTF8/16 conversion required and function takes any number of arguments.
88653 ** 2: UTF16 byte order change required and function takes any number of args.
88654 ** 3: encoding matches and function takes any number of arguments
88655 ** 4: UTF8/16 conversion required - argument count matches exactly
88656 ** 5: UTF16 byte order conversion required - argument count matches exactly
88657 ** 6: Perfect match: encoding and argument count match exactly.
88659 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
88660 ** a perfect match and any function with both xStep and xFunc NULL is
88661 ** a non-match.
88663 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
88664 static int matchQuality(
88665 FuncDef *p, /* The function we are evaluating for match quality */
88666 int nArg, /* Desired number of arguments. (-1)==any */
88667 u8 enc /* Desired text encoding */
88669 int match;
88671 /* nArg of -2 is a special case */
88672 if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
88674 /* Wrong number of arguments means "no match" */
88675 if( p->nArg!=nArg && p->nArg>=0 ) return 0;
88677 /* Give a better score to a function with a specific number of arguments
88678 ** than to function that accepts any number of arguments. */
88679 if( p->nArg==nArg ){
88680 match = 4;
88681 }else{
88682 match = 1;
88685 /* Bonus points if the text encoding matches */
88686 if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
88687 match += 2; /* Exact encoding match */
88688 }else if( (enc & p->funcFlags & 2)!=0 ){
88689 match += 1; /* Both are UTF16, but with different byte orders */
88692 return match;
88696 ** Search a FuncDefHash for a function with the given name. Return
88697 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
88699 static FuncDef *functionSearch(
88700 FuncDefHash *pHash, /* Hash table to search */
88701 int h, /* Hash of the name */
88702 const char *zFunc, /* Name of function */
88703 int nFunc /* Number of bytes in zFunc */
88705 FuncDef *p;
88706 for(p=pHash->a[h]; p; p=p->pHash){
88707 if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
88708 return p;
88711 return 0;
88715 ** Insert a new FuncDef into a FuncDefHash hash table.
88717 SQLITE_PRIVATE void sqlite3FuncDefInsert(
88718 FuncDefHash *pHash, /* The hash table into which to insert */
88719 FuncDef *pDef /* The function definition to insert */
88721 FuncDef *pOther;
88722 int nName = sqlite3Strlen30(pDef->zName);
88723 u8 c1 = (u8)pDef->zName[0];
88724 int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
88725 pOther = functionSearch(pHash, h, pDef->zName, nName);
88726 if( pOther ){
88727 assert( pOther!=pDef && pOther->pNext!=pDef );
88728 pDef->pNext = pOther->pNext;
88729 pOther->pNext = pDef;
88730 }else{
88731 pDef->pNext = 0;
88732 pDef->pHash = pHash->a[h];
88733 pHash->a[h] = pDef;
88740 ** Locate a user function given a name, a number of arguments and a flag
88741 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
88742 ** pointer to the FuncDef structure that defines that function, or return
88743 ** NULL if the function does not exist.
88745 ** If the createFlag argument is true, then a new (blank) FuncDef
88746 ** structure is created and liked into the "db" structure if a
88747 ** no matching function previously existed.
88749 ** If nArg is -2, then the first valid function found is returned. A
88750 ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
88751 ** case is used to see if zName is a valid function name for some number
88752 ** of arguments. If nArg is -2, then createFlag must be 0.
88754 ** If createFlag is false, then a function with the required name and
88755 ** number of arguments may be returned even if the eTextRep flag does not
88756 ** match that requested.
88758 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
88759 sqlite3 *db, /* An open database */
88760 const char *zName, /* Name of the function. Not null-terminated */
88761 int nName, /* Number of characters in the name */
88762 int nArg, /* Number of arguments. -1 means any number */
88763 u8 enc, /* Preferred text encoding */
88764 u8 createFlag /* Create new entry if true and does not otherwise exist */
88766 FuncDef *p; /* Iterator variable */
88767 FuncDef *pBest = 0; /* Best match found so far */
88768 int bestScore = 0; /* Score of best match */
88769 int h; /* Hash value */
88771 assert( nArg>=(-2) );
88772 assert( nArg>=(-1) || createFlag==0 );
88773 h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
88775 /* First search for a match amongst the application-defined functions.
88777 p = functionSearch(&db->aFunc, h, zName, nName);
88778 while( p ){
88779 int score = matchQuality(p, nArg, enc);
88780 if( score>bestScore ){
88781 pBest = p;
88782 bestScore = score;
88784 p = p->pNext;
88787 /* If no match is found, search the built-in functions.
88789 ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
88790 ** functions even if a prior app-defined function was found. And give
88791 ** priority to built-in functions.
88793 ** Except, if createFlag is true, that means that we are trying to
88794 ** install a new function. Whatever FuncDef structure is returned it will
88795 ** have fields overwritten with new information appropriate for the
88796 ** new function. But the FuncDefs for built-in functions are read-only.
88797 ** So we must not search for built-ins when creating a new function.
88799 if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
88800 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
88801 bestScore = 0;
88802 p = functionSearch(pHash, h, zName, nName);
88803 while( p ){
88804 int score = matchQuality(p, nArg, enc);
88805 if( score>bestScore ){
88806 pBest = p;
88807 bestScore = score;
88809 p = p->pNext;
88813 /* If the createFlag parameter is true and the search did not reveal an
88814 ** exact match for the name, number of arguments and encoding, then add a
88815 ** new entry to the hash table and return it.
88817 if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
88818 (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
88819 pBest->zName = (char *)&pBest[1];
88820 pBest->nArg = (u16)nArg;
88821 pBest->funcFlags = enc;
88822 memcpy(pBest->zName, zName, nName);
88823 pBest->zName[nName] = 0;
88824 sqlite3FuncDefInsert(&db->aFunc, pBest);
88827 if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
88828 return pBest;
88830 return 0;
88834 ** Free all resources held by the schema structure. The void* argument points
88835 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
88836 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
88837 ** of the schema hash tables).
88839 ** The Schema.cache_size variable is not cleared.
88841 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
88842 Hash temp1;
88843 Hash temp2;
88844 HashElem *pElem;
88845 Schema *pSchema = (Schema *)p;
88847 temp1 = pSchema->tblHash;
88848 temp2 = pSchema->trigHash;
88849 sqlite3HashInit(&pSchema->trigHash);
88850 sqlite3HashClear(&pSchema->idxHash);
88851 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
88852 sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
88854 sqlite3HashClear(&temp2);
88855 sqlite3HashInit(&pSchema->tblHash);
88856 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
88857 Table *pTab = sqliteHashData(pElem);
88858 sqlite3DeleteTable(0, pTab);
88860 sqlite3HashClear(&temp1);
88861 sqlite3HashClear(&pSchema->fkeyHash);
88862 pSchema->pSeqTab = 0;
88863 if( pSchema->flags & DB_SchemaLoaded ){
88864 pSchema->iGeneration++;
88865 pSchema->flags &= ~DB_SchemaLoaded;
88870 ** Find and return the schema associated with a BTree. Create
88871 ** a new one if necessary.
88873 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
88874 Schema * p;
88875 if( pBt ){
88876 p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
88877 }else{
88878 p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
88880 if( !p ){
88881 db->mallocFailed = 1;
88882 }else if ( 0==p->file_format ){
88883 sqlite3HashInit(&p->tblHash);
88884 sqlite3HashInit(&p->idxHash);
88885 sqlite3HashInit(&p->trigHash);
88886 sqlite3HashInit(&p->fkeyHash);
88887 p->enc = SQLITE_UTF8;
88889 return p;
88892 /************** End of callback.c ********************************************/
88893 /************** Begin file delete.c ******************************************/
88895 ** 2001 September 15
88897 ** The author disclaims copyright to this source code. In place of
88898 ** a legal notice, here is a blessing:
88900 ** May you do good and not evil.
88901 ** May you find forgiveness for yourself and forgive others.
88902 ** May you share freely, never taking more than you give.
88904 *************************************************************************
88905 ** This file contains C code routines that are called by the parser
88906 ** in order to generate code for DELETE FROM statements.
88910 ** While a SrcList can in general represent multiple tables and subqueries
88911 ** (as in the FROM clause of a SELECT statement) in this case it contains
88912 ** the name of a single table, as one might find in an INSERT, DELETE,
88913 ** or UPDATE statement. Look up that table in the symbol table and
88914 ** return a pointer. Set an error message and return NULL if the table
88915 ** name is not found or if any other error occurs.
88917 ** The following fields are initialized appropriate in pSrc:
88919 ** pSrc->a[0].pTab Pointer to the Table object
88920 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
88923 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
88924 struct SrcList_item *pItem = pSrc->a;
88925 Table *pTab;
88926 assert( pItem && pSrc->nSrc==1 );
88927 pTab = sqlite3LocateTableItem(pParse, 0, pItem);
88928 sqlite3DeleteTable(pParse->db, pItem->pTab);
88929 pItem->pTab = pTab;
88930 if( pTab ){
88931 pTab->nRef++;
88933 if( sqlite3IndexedByLookup(pParse, pItem) ){
88934 pTab = 0;
88936 return pTab;
88940 ** Check to make sure the given table is writable. If it is not
88941 ** writable, generate an error message and return 1. If it is
88942 ** writable return 0;
88944 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
88945 /* A table is not writable under the following circumstances:
88947 ** 1) It is a virtual table and no implementation of the xUpdate method
88948 ** has been provided, or
88949 ** 2) It is a system table (i.e. sqlite_master), this call is not
88950 ** part of a nested parse and writable_schema pragma has not
88951 ** been specified.
88953 ** In either case leave an error message in pParse and return non-zero.
88955 if( ( IsVirtual(pTab)
88956 && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
88957 || ( (pTab->tabFlags & TF_Readonly)!=0
88958 && (pParse->db->flags & SQLITE_WriteSchema)==0
88959 && pParse->nested==0 )
88961 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
88962 return 1;
88965 #ifndef SQLITE_OMIT_VIEW
88966 if( !viewOk && pTab->pSelect ){
88967 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
88968 return 1;
88970 #endif
88971 return 0;
88975 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
88977 ** Evaluate a view and store its result in an ephemeral table. The
88978 ** pWhere argument is an optional WHERE clause that restricts the
88979 ** set of rows in the view that are to be added to the ephemeral table.
88981 SQLITE_PRIVATE void sqlite3MaterializeView(
88982 Parse *pParse, /* Parsing context */
88983 Table *pView, /* View definition */
88984 Expr *pWhere, /* Optional WHERE clause to be added */
88985 int iCur /* Cursor number for ephemerial table */
88987 SelectDest dest;
88988 Select *pSel;
88989 SrcList *pFrom;
88990 sqlite3 *db = pParse->db;
88991 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
88993 pWhere = sqlite3ExprDup(db, pWhere, 0);
88994 pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
88996 if( pFrom ){
88997 assert( pFrom->nSrc==1 );
88998 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
88999 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
89000 assert( pFrom->a[0].pOn==0 );
89001 assert( pFrom->a[0].pUsing==0 );
89004 pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
89005 if( pSel ) pSel->selFlags |= SF_Materialize;
89007 sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
89008 sqlite3Select(pParse, pSel, &dest);
89009 sqlite3SelectDelete(db, pSel);
89011 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
89013 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
89015 ** Generate an expression tree to implement the WHERE, ORDER BY,
89016 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
89018 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
89019 ** \__________________________/
89020 ** pLimitWhere (pInClause)
89022 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
89023 Parse *pParse, /* The parser context */
89024 SrcList *pSrc, /* the FROM clause -- which tables to scan */
89025 Expr *pWhere, /* The WHERE clause. May be null */
89026 ExprList *pOrderBy, /* The ORDER BY clause. May be null */
89027 Expr *pLimit, /* The LIMIT clause. May be null */
89028 Expr *pOffset, /* The OFFSET clause. May be null */
89029 char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
89031 Expr *pWhereRowid = NULL; /* WHERE rowid .. */
89032 Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
89033 Expr *pSelectRowid = NULL; /* SELECT rowid ... */
89034 ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
89035 SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
89036 Select *pSelect = NULL; /* Complete SELECT tree */
89038 /* Check that there isn't an ORDER BY without a LIMIT clause.
89040 if( pOrderBy && (pLimit == 0) ) {
89041 sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
89042 goto limit_where_cleanup_2;
89045 /* We only need to generate a select expression if there
89046 ** is a limit/offset term to enforce.
89048 if( pLimit == 0 ) {
89049 /* if pLimit is null, pOffset will always be null as well. */
89050 assert( pOffset == 0 );
89051 return pWhere;
89054 /* Generate a select expression tree to enforce the limit/offset
89055 ** term for the DELETE or UPDATE statement. For example:
89056 ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
89057 ** becomes:
89058 ** DELETE FROM table_a WHERE rowid IN (
89059 ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
89060 ** );
89063 pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
89064 if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
89065 pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
89066 if( pEList == 0 ) goto limit_where_cleanup_2;
89068 /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
89069 ** and the SELECT subtree. */
89070 pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
89071 if( pSelectSrc == 0 ) {
89072 sqlite3ExprListDelete(pParse->db, pEList);
89073 goto limit_where_cleanup_2;
89076 /* generate the SELECT expression tree. */
89077 pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
89078 pOrderBy,0,pLimit,pOffset);
89079 if( pSelect == 0 ) return 0;
89081 /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
89082 pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
89083 if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
89084 pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
89085 if( pInClause == 0 ) goto limit_where_cleanup_1;
89087 pInClause->x.pSelect = pSelect;
89088 pInClause->flags |= EP_xIsSelect;
89089 sqlite3ExprSetHeight(pParse, pInClause);
89090 return pInClause;
89092 /* something went wrong. clean up anything allocated. */
89093 limit_where_cleanup_1:
89094 sqlite3SelectDelete(pParse->db, pSelect);
89095 return 0;
89097 limit_where_cleanup_2:
89098 sqlite3ExprDelete(pParse->db, pWhere);
89099 sqlite3ExprListDelete(pParse->db, pOrderBy);
89100 sqlite3ExprDelete(pParse->db, pLimit);
89101 sqlite3ExprDelete(pParse->db, pOffset);
89102 return 0;
89104 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
89105 /* && !defined(SQLITE_OMIT_SUBQUERY) */
89108 ** Generate code for a DELETE FROM statement.
89110 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
89111 ** \________/ \________________/
89112 ** pTabList pWhere
89114 SQLITE_PRIVATE void sqlite3DeleteFrom(
89115 Parse *pParse, /* The parser context */
89116 SrcList *pTabList, /* The table from which we should delete things */
89117 Expr *pWhere /* The WHERE clause. May be null */
89119 Vdbe *v; /* The virtual database engine */
89120 Table *pTab; /* The table from which records will be deleted */
89121 const char *zDb; /* Name of database holding pTab */
89122 int i; /* Loop counter */
89123 WhereInfo *pWInfo; /* Information about the WHERE clause */
89124 Index *pIdx; /* For looping over indices of the table */
89125 int iTabCur; /* Cursor number for the table */
89126 int iDataCur; /* VDBE cursor for the canonical data source */
89127 int iIdxCur; /* Cursor number of the first index */
89128 int nIdx; /* Number of indices */
89129 sqlite3 *db; /* Main database structure */
89130 AuthContext sContext; /* Authorization context */
89131 NameContext sNC; /* Name context to resolve expressions in */
89132 int iDb; /* Database number */
89133 int memCnt = -1; /* Memory cell used for change counting */
89134 int rcauth; /* Value returned by authorization callback */
89135 int okOnePass; /* True for one-pass algorithm without the FIFO */
89136 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
89137 u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
89138 Index *pPk; /* The PRIMARY KEY index on the table */
89139 int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
89140 i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
89141 int iKey; /* Memory cell holding key of row to be deleted */
89142 i16 nKey; /* Number of memory cells in the row key */
89143 int iEphCur = 0; /* Ephemeral table holding all primary key values */
89144 int iRowSet = 0; /* Register for rowset of rows to delete */
89145 int addrBypass = 0; /* Address of jump over the delete logic */
89146 int addrLoop = 0; /* Top of the delete loop */
89147 int addrDelete = 0; /* Jump directly to the delete logic */
89148 int addrEphOpen = 0; /* Instruction to open the Ephermeral table */
89150 #ifndef SQLITE_OMIT_TRIGGER
89151 int isView; /* True if attempting to delete from a view */
89152 Trigger *pTrigger; /* List of table triggers, if required */
89153 #endif
89155 memset(&sContext, 0, sizeof(sContext));
89156 db = pParse->db;
89157 if( pParse->nErr || db->mallocFailed ){
89158 goto delete_from_cleanup;
89160 assert( pTabList->nSrc==1 );
89162 /* Locate the table which we want to delete. This table has to be
89163 ** put in an SrcList structure because some of the subroutines we
89164 ** will be calling are designed to work with multiple tables and expect
89165 ** an SrcList* parameter instead of just a Table* parameter.
89167 pTab = sqlite3SrcListLookup(pParse, pTabList);
89168 if( pTab==0 ) goto delete_from_cleanup;
89170 /* Figure out if we have any triggers and if the table being
89171 ** deleted from is a view
89173 #ifndef SQLITE_OMIT_TRIGGER
89174 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
89175 isView = pTab->pSelect!=0;
89176 #else
89177 # define pTrigger 0
89178 # define isView 0
89179 #endif
89180 #ifdef SQLITE_OMIT_VIEW
89181 # undef isView
89182 # define isView 0
89183 #endif
89185 /* If pTab is really a view, make sure it has been initialized.
89187 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89188 goto delete_from_cleanup;
89191 if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
89192 goto delete_from_cleanup;
89194 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89195 assert( iDb<db->nDb );
89196 zDb = db->aDb[iDb].zName;
89197 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
89198 assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
89199 if( rcauth==SQLITE_DENY ){
89200 goto delete_from_cleanup;
89202 assert(!isView || pTrigger);
89204 /* Assign cursor numbers to the table and all its indices.
89206 assert( pTabList->nSrc==1 );
89207 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
89208 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
89209 pParse->nTab++;
89212 /* Start the view context
89214 if( isView ){
89215 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
89218 /* Begin generating code.
89220 v = sqlite3GetVdbe(pParse);
89221 if( v==0 ){
89222 goto delete_from_cleanup;
89224 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
89225 sqlite3BeginWriteOperation(pParse, 1, iDb);
89227 /* If we are trying to delete from a view, realize that view into
89228 ** a ephemeral table.
89230 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
89231 if( isView ){
89232 sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
89233 iDataCur = iIdxCur = iTabCur;
89235 #endif
89237 /* Resolve the column names in the WHERE clause.
89239 memset(&sNC, 0, sizeof(sNC));
89240 sNC.pParse = pParse;
89241 sNC.pSrcList = pTabList;
89242 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
89243 goto delete_from_cleanup;
89246 /* Initialize the counter of the number of rows deleted, if
89247 ** we are counting rows.
89249 if( db->flags & SQLITE_CountRows ){
89250 memCnt = ++pParse->nMem;
89251 sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
89254 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
89255 /* Special case: A DELETE without a WHERE clause deletes everything.
89256 ** It is easier just to erase the whole table. Prior to version 3.6.5,
89257 ** this optimization caused the row change count (the value returned by
89258 ** API function sqlite3_count_changes) to be set incorrectly. */
89259 if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
89260 && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
89262 assert( !isView );
89263 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
89264 if( HasRowid(pTab) ){
89265 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
89266 pTab->zName, P4_STATIC);
89268 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
89269 assert( pIdx->pSchema==pTab->pSchema );
89270 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
89272 }else
89273 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
89275 if( HasRowid(pTab) ){
89276 /* For a rowid table, initialize the RowSet to an empty set */
89277 pPk = 0;
89278 nPk = 1;
89279 iRowSet = ++pParse->nMem;
89280 sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
89281 }else{
89282 /* For a WITHOUT ROWID table, create an ephermeral table used to
89283 ** hold all primary keys for rows to be deleted. */
89284 pPk = sqlite3PrimaryKeyIndex(pTab);
89285 assert( pPk!=0 );
89286 nPk = pPk->nKeyCol;
89287 iPk = pParse->nMem+1;
89288 pParse->nMem += nPk;
89289 iEphCur = pParse->nTab++;
89290 addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
89291 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
89294 /* Construct a query to find the rowid or primary key for every row
89295 ** to be deleted, based on the WHERE clause.
89297 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
89298 WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
89299 iTabCur+1);
89300 if( pWInfo==0 ) goto delete_from_cleanup;
89301 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
89303 /* Keep track of the number of rows to be deleted */
89304 if( db->flags & SQLITE_CountRows ){
89305 sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
89308 /* Extract the rowid or primary key for the current row */
89309 if( pPk ){
89310 for(i=0; i<nPk; i++){
89311 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
89312 pPk->aiColumn[i], iPk+i);
89314 iKey = iPk;
89315 }else{
89316 iKey = pParse->nMem + 1;
89317 iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
89318 if( iKey>pParse->nMem ) pParse->nMem = iKey;
89321 if( okOnePass ){
89322 /* For ONEPASS, no need to store the rowid/primary-key. There is only
89323 ** one, so just keep it in its register(s) and fall through to the
89324 ** delete code.
89326 nKey = nPk; /* OP_Found will use an unpacked key */
89327 aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
89328 if( aToOpen==0 ){
89329 sqlite3WhereEnd(pWInfo);
89330 goto delete_from_cleanup;
89332 memset(aToOpen, 1, nIdx+1);
89333 aToOpen[nIdx+1] = 0;
89334 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
89335 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
89336 if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
89337 addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
89338 }else if( pPk ){
89339 /* Construct a composite key for the row to be deleted and remember it */
89340 iKey = ++pParse->nMem;
89341 nKey = 0; /* Zero tells OP_Found to use a composite key */
89342 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
89343 sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT);
89344 sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
89345 }else{
89346 /* Get the rowid of the row to be deleted and remember it in the RowSet */
89347 nKey = 1; /* OP_Seek always uses a single rowid */
89348 sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
89351 /* End of the WHERE loop */
89352 sqlite3WhereEnd(pWInfo);
89353 if( okOnePass ){
89354 /* Bypass the delete logic below if the WHERE loop found zero rows */
89355 addrBypass = sqlite3VdbeMakeLabel(v);
89356 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
89357 sqlite3VdbeJumpHere(v, addrDelete);
89360 /* Unless this is a view, open cursors for the table we are
89361 ** deleting from and all its indices. If this is a view, then the
89362 ** only effect this statement has is to fire the INSTEAD OF
89363 ** triggers.
89365 if( !isView ){
89366 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
89367 &iDataCur, &iIdxCur);
89368 assert( pPk || iDataCur==iTabCur );
89369 assert( pPk || iIdxCur==iDataCur+1 );
89372 /* Set up a loop over the rowids/primary-keys that were found in the
89373 ** where-clause loop above.
89375 if( okOnePass ){
89376 /* Just one row. Hence the top-of-loop is a no-op */
89377 assert( nKey==nPk ); /* OP_Found will use an unpacked key */
89378 if( aToOpen[iDataCur-iTabCur] ){
89379 assert( pPk!=0 );
89380 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
89382 }else if( pPk ){
89383 addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur);
89384 sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
89385 assert( nKey==0 ); /* OP_Found will use a composite key */
89386 }else{
89387 addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
89388 assert( nKey==1 );
89391 /* Delete the row */
89392 #ifndef SQLITE_OMIT_VIRTUALTABLE
89393 if( IsVirtual(pTab) ){
89394 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
89395 sqlite3VtabMakeWritable(pParse, pTab);
89396 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
89397 sqlite3VdbeChangeP5(v, OE_Abort);
89398 sqlite3MayAbort(pParse);
89399 }else
89400 #endif
89402 int count = (pParse->nested==0); /* True to count changes */
89403 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
89404 iKey, nKey, count, OE_Default, okOnePass);
89407 /* End of the loop over all rowids/primary-keys. */
89408 if( okOnePass ){
89409 sqlite3VdbeResolveLabel(v, addrBypass);
89410 }else if( pPk ){
89411 sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1);
89412 sqlite3VdbeJumpHere(v, addrLoop);
89413 }else{
89414 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
89415 sqlite3VdbeJumpHere(v, addrLoop);
89418 /* Close the cursors open on the table and its indexes. */
89419 if( !isView && !IsVirtual(pTab) ){
89420 if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
89421 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
89422 sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
89425 } /* End non-truncate path */
89427 /* Update the sqlite_sequence table by storing the content of the
89428 ** maximum rowid counter values recorded while inserting into
89429 ** autoincrement tables.
89431 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89432 sqlite3AutoincrementEnd(pParse);
89435 /* Return the number of rows that were deleted. If this routine is
89436 ** generating code because of a call to sqlite3NestedParse(), do not
89437 ** invoke the callback function.
89439 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89440 sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
89441 sqlite3VdbeSetNumCols(v, 1);
89442 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
89445 delete_from_cleanup:
89446 sqlite3AuthContextPop(&sContext);
89447 sqlite3SrcListDelete(db, pTabList);
89448 sqlite3ExprDelete(db, pWhere);
89449 sqlite3DbFree(db, aToOpen);
89450 return;
89452 /* Make sure "isView" and other macros defined above are undefined. Otherwise
89453 ** thely may interfere with compilation of other functions in this file
89454 ** (or in another file, if this file becomes part of the amalgamation). */
89455 #ifdef isView
89456 #undef isView
89457 #endif
89458 #ifdef pTrigger
89459 #undef pTrigger
89460 #endif
89463 ** This routine generates VDBE code that causes a single row of a
89464 ** single table to be deleted. Both the original table entry and
89465 ** all indices are removed.
89467 ** Preconditions:
89469 ** 1. iDataCur is an open cursor on the btree that is the canonical data
89470 ** store for the table. (This will be either the table itself,
89471 ** in the case of a rowid table, or the PRIMARY KEY index in the case
89472 ** of a WITHOUT ROWID table.)
89474 ** 2. Read/write cursors for all indices of pTab must be open as
89475 ** cursor number iIdxCur+i for the i-th index.
89477 ** 3. The primary key for the row to be deleted must be stored in a
89478 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
89479 ** that a search record formed from OP_MakeRecord is contained in the
89480 ** single memory location iPk.
89482 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
89483 Parse *pParse, /* Parsing context */
89484 Table *pTab, /* Table containing the row to be deleted */
89485 Trigger *pTrigger, /* List of triggers to (potentially) fire */
89486 int iDataCur, /* Cursor from which column data is extracted */
89487 int iIdxCur, /* First index cursor */
89488 int iPk, /* First memory cell containing the PRIMARY KEY */
89489 i16 nPk, /* Number of PRIMARY KEY memory cells */
89490 u8 count, /* If non-zero, increment the row change counter */
89491 u8 onconf, /* Default ON CONFLICT policy for triggers */
89492 u8 bNoSeek /* iDataCur is already pointing to the row to delete */
89494 Vdbe *v = pParse->pVdbe; /* Vdbe */
89495 int iOld = 0; /* First register in OLD.* array */
89496 int iLabel; /* Label resolved to end of generated code */
89497 u8 opSeek; /* Seek opcode */
89499 /* Vdbe is guaranteed to have been allocated by this stage. */
89500 assert( v );
89501 VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
89502 iDataCur, iIdxCur, iPk, (int)nPk));
89504 /* Seek cursor iCur to the row to delete. If this row no longer exists
89505 ** (this can happen if a trigger program has already deleted it), do
89506 ** not attempt to delete it or fire any DELETE triggers. */
89507 iLabel = sqlite3VdbeMakeLabel(v);
89508 opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
89509 if( !bNoSeek ) sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
89511 /* If there are any triggers to fire, allocate a range of registers to
89512 ** use for the old.* references in the triggers. */
89513 if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
89514 u32 mask; /* Mask of OLD.* columns in use */
89515 int iCol; /* Iterator used while populating OLD.* */
89516 int addrStart; /* Start of BEFORE trigger programs */
89518 /* TODO: Could use temporary registers here. Also could attempt to
89519 ** avoid copying the contents of the rowid register. */
89520 mask = sqlite3TriggerColmask(
89521 pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
89523 mask |= sqlite3FkOldmask(pParse, pTab);
89524 iOld = pParse->nMem+1;
89525 pParse->nMem += (1 + pTab->nCol);
89527 /* Populate the OLD.* pseudo-table register array. These values will be
89528 ** used by any BEFORE and AFTER triggers that exist. */
89529 sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
89530 for(iCol=0; iCol<pTab->nCol; iCol++){
89531 testcase( mask!=0xffffffff && iCol==31 );
89532 testcase( mask!=0xffffffff && iCol==32 );
89533 if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
89534 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
89538 /* Invoke BEFORE DELETE trigger programs. */
89539 addrStart = sqlite3VdbeCurrentAddr(v);
89540 sqlite3CodeRowTrigger(pParse, pTrigger,
89541 TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
89544 /* If any BEFORE triggers were coded, then seek the cursor to the
89545 ** row to be deleted again. It may be that the BEFORE triggers moved
89546 ** the cursor or of already deleted the row that the cursor was
89547 ** pointing to.
89549 if( addrStart<sqlite3VdbeCurrentAddr(v) ){
89550 sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
89553 /* Do FK processing. This call checks that any FK constraints that
89554 ** refer to this table (i.e. constraints attached to other tables)
89555 ** are not violated by deleting this row. */
89556 sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
89559 /* Delete the index and table entries. Skip this step if pTab is really
89560 ** a view (in which case the only effect of the DELETE statement is to
89561 ** fire the INSTEAD OF triggers). */
89562 if( pTab->pSelect==0 ){
89563 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
89564 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
89565 if( count ){
89566 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
89570 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
89571 ** handle rows (possibly in other tables) that refer via a foreign key
89572 ** to the row just deleted. */
89573 sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
89575 /* Invoke AFTER DELETE trigger programs. */
89576 sqlite3CodeRowTrigger(pParse, pTrigger,
89577 TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
89580 /* Jump here if the row had already been deleted before any BEFORE
89581 ** trigger programs were invoked. Or if a trigger program throws a
89582 ** RAISE(IGNORE) exception. */
89583 sqlite3VdbeResolveLabel(v, iLabel);
89584 VdbeModuleComment((v, "END: GenRowDel()"));
89588 ** This routine generates VDBE code that causes the deletion of all
89589 ** index entries associated with a single row of a single table, pTab
89591 ** Preconditions:
89593 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
89594 ** btree for the table pTab. (This will be either the table itself
89595 ** for rowid tables or to the primary key index for WITHOUT ROWID
89596 ** tables.)
89598 ** 2. Read/write cursors for all indices of pTab must be open as
89599 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
89600 ** index is the 0-th index.)
89602 ** 3. The "iDataCur" cursor must be already be positioned on the row
89603 ** that is to be deleted.
89605 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
89606 Parse *pParse, /* Parsing and code generating context */
89607 Table *pTab, /* Table containing the row to be deleted */
89608 int iDataCur, /* Cursor of table holding data. */
89609 int iIdxCur, /* First index cursor */
89610 int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
89612 int i; /* Index loop counter */
89613 int r1 = -1; /* Register holding an index key */
89614 int iPartIdxLabel; /* Jump destination for skipping partial index entries */
89615 Index *pIdx; /* Current index */
89616 Index *pPrior = 0; /* Prior index */
89617 Vdbe *v; /* The prepared statement under construction */
89618 Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
89620 v = pParse->pVdbe;
89621 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
89622 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
89623 assert( iIdxCur+i!=iDataCur || pPk==pIdx );
89624 if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
89625 if( pIdx==pPk ) continue;
89626 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
89627 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
89628 &iPartIdxLabel, pPrior, r1);
89629 sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
89630 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
89631 sqlite3VdbeResolveLabel(v, iPartIdxLabel);
89632 pPrior = pIdx;
89637 ** Generate code that will assemble an index key and stores it in register
89638 ** regOut. The key with be for index pIdx which is an index on pTab.
89639 ** iCur is the index of a cursor open on the pTab table and pointing to
89640 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
89641 ** iCur must be the cursor of the PRIMARY KEY index.
89643 ** Return a register number which is the first in a block of
89644 ** registers that holds the elements of the index key. The
89645 ** block of registers has already been deallocated by the time
89646 ** this routine returns.
89648 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
89649 ** to that label if pIdx is a partial index that should be skipped.
89650 ** A partial index should be skipped if its WHERE clause evaluates
89651 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
89652 ** will be set to zero which is an empty label that is ignored by
89653 ** sqlite3VdbeResolveLabel().
89655 ** The pPrior and regPrior parameters are used to implement a cache to
89656 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
89657 ** a pointer to a different index for which an index key has just been
89658 ** computed into register regPrior. If the current pIdx index is generating
89659 ** its key into the same sequence of registers and if pPrior and pIdx share
89660 ** a column in common, then the register corresponding to that column already
89661 ** holds the correct value and the loading of that register is skipped.
89662 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
89663 ** on a table with multiple indices, and especially with the ROWID or
89664 ** PRIMARY KEY columns of the index.
89666 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
89667 Parse *pParse, /* Parsing context */
89668 Index *pIdx, /* The index for which to generate a key */
89669 int iDataCur, /* Cursor number from which to take column data */
89670 int regOut, /* Put the new key into this register if not 0 */
89671 int prefixOnly, /* Compute only a unique prefix of the key */
89672 int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
89673 Index *pPrior, /* Previously generated index key */
89674 int regPrior /* Register holding previous generated key */
89676 Vdbe *v = pParse->pVdbe;
89677 int j;
89678 Table *pTab = pIdx->pTable;
89679 int regBase;
89680 int nCol;
89682 if( piPartIdxLabel ){
89683 if( pIdx->pPartIdxWhere ){
89684 *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
89685 pParse->iPartIdxTab = iDataCur;
89686 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
89687 SQLITE_JUMPIFNULL);
89688 }else{
89689 *piPartIdxLabel = 0;
89692 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
89693 regBase = sqlite3GetTempRange(pParse, nCol);
89694 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
89695 for(j=0; j<nCol; j++){
89696 if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
89697 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
89698 regBase+j);
89699 /* If the column affinity is REAL but the number is an integer, then it
89700 ** might be stored in the table as an integer (using a compact
89701 ** representation) then converted to REAL by an OP_RealAffinity opcode.
89702 ** But we are getting ready to store this value back into an index, where
89703 ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
89704 ** opcode if it is present */
89705 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
89707 if( regOut ){
89708 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
89710 sqlite3ReleaseTempRange(pParse, regBase, nCol);
89711 return regBase;
89714 /************** End of delete.c **********************************************/
89715 /************** Begin file func.c ********************************************/
89717 ** 2002 February 23
89719 ** The author disclaims copyright to this source code. In place of
89720 ** a legal notice, here is a blessing:
89722 ** May you do good and not evil.
89723 ** May you find forgiveness for yourself and forgive others.
89724 ** May you share freely, never taking more than you give.
89726 *************************************************************************
89727 ** This file contains the C functions that implement various SQL
89728 ** functions of SQLite.
89730 ** There is only one exported symbol in this file - the function
89731 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
89732 ** All other code has file scope.
89734 /* #include <stdlib.h> */
89735 /* #include <assert.h> */
89738 ** Return the collating function associated with a function.
89740 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
89741 return context->pColl;
89745 ** Indicate that the accumulator load should be skipped on this
89746 ** iteration of the aggregate loop.
89748 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
89749 context->skipFlag = 1;
89753 ** Implementation of the non-aggregate min() and max() functions
89755 static void minmaxFunc(
89756 sqlite3_context *context,
89757 int argc,
89758 sqlite3_value **argv
89760 int i;
89761 int mask; /* 0 for min() or 0xffffffff for max() */
89762 int iBest;
89763 CollSeq *pColl;
89765 assert( argc>1 );
89766 mask = sqlite3_user_data(context)==0 ? 0 : -1;
89767 pColl = sqlite3GetFuncCollSeq(context);
89768 assert( pColl );
89769 assert( mask==-1 || mask==0 );
89770 iBest = 0;
89771 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
89772 for(i=1; i<argc; i++){
89773 if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
89774 if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
89775 testcase( mask==0 );
89776 iBest = i;
89779 sqlite3_result_value(context, argv[iBest]);
89783 ** Return the type of the argument.
89785 static void typeofFunc(
89786 sqlite3_context *context,
89787 int NotUsed,
89788 sqlite3_value **argv
89790 const char *z = 0;
89791 UNUSED_PARAMETER(NotUsed);
89792 switch( sqlite3_value_type(argv[0]) ){
89793 case SQLITE_INTEGER: z = "integer"; break;
89794 case SQLITE_TEXT: z = "text"; break;
89795 case SQLITE_FLOAT: z = "real"; break;
89796 case SQLITE_BLOB: z = "blob"; break;
89797 default: z = "null"; break;
89799 sqlite3_result_text(context, z, -1, SQLITE_STATIC);
89804 ** Implementation of the length() function
89806 static void lengthFunc(
89807 sqlite3_context *context,
89808 int argc,
89809 sqlite3_value **argv
89811 int len;
89813 assert( argc==1 );
89814 UNUSED_PARAMETER(argc);
89815 switch( sqlite3_value_type(argv[0]) ){
89816 case SQLITE_BLOB:
89817 case SQLITE_INTEGER:
89818 case SQLITE_FLOAT: {
89819 sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
89820 break;
89822 case SQLITE_TEXT: {
89823 const unsigned char *z = sqlite3_value_text(argv[0]);
89824 if( z==0 ) return;
89825 len = 0;
89826 while( *z ){
89827 len++;
89828 SQLITE_SKIP_UTF8(z);
89830 sqlite3_result_int(context, len);
89831 break;
89833 default: {
89834 sqlite3_result_null(context);
89835 break;
89841 ** Implementation of the abs() function.
89843 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
89844 ** the numeric argument X.
89846 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
89847 assert( argc==1 );
89848 UNUSED_PARAMETER(argc);
89849 switch( sqlite3_value_type(argv[0]) ){
89850 case SQLITE_INTEGER: {
89851 i64 iVal = sqlite3_value_int64(argv[0]);
89852 if( iVal<0 ){
89853 if( iVal==SMALLEST_INT64 ){
89854 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
89855 ** then abs(X) throws an integer overflow error since there is no
89856 ** equivalent positive 64-bit two complement value. */
89857 sqlite3_result_error(context, "integer overflow", -1);
89858 return;
89860 iVal = -iVal;
89862 sqlite3_result_int64(context, iVal);
89863 break;
89865 case SQLITE_NULL: {
89866 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
89867 sqlite3_result_null(context);
89868 break;
89870 default: {
89871 /* Because sqlite3_value_double() returns 0.0 if the argument is not
89872 ** something that can be converted into a number, we have:
89873 ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
89874 ** cannot be converted to a numeric value.
89876 double rVal = sqlite3_value_double(argv[0]);
89877 if( rVal<0 ) rVal = -rVal;
89878 sqlite3_result_double(context, rVal);
89879 break;
89885 ** Implementation of the instr() function.
89887 ** instr(haystack,needle) finds the first occurrence of needle
89888 ** in haystack and returns the number of previous characters plus 1,
89889 ** or 0 if needle does not occur within haystack.
89891 ** If both haystack and needle are BLOBs, then the result is one more than
89892 ** the number of bytes in haystack prior to the first occurrence of needle,
89893 ** or 0 if needle never occurs in haystack.
89895 static void instrFunc(
89896 sqlite3_context *context,
89897 int argc,
89898 sqlite3_value **argv
89900 const unsigned char *zHaystack;
89901 const unsigned char *zNeedle;
89902 int nHaystack;
89903 int nNeedle;
89904 int typeHaystack, typeNeedle;
89905 int N = 1;
89906 int isText;
89908 UNUSED_PARAMETER(argc);
89909 typeHaystack = sqlite3_value_type(argv[0]);
89910 typeNeedle = sqlite3_value_type(argv[1]);
89911 if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
89912 nHaystack = sqlite3_value_bytes(argv[0]);
89913 nNeedle = sqlite3_value_bytes(argv[1]);
89914 if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
89915 zHaystack = sqlite3_value_blob(argv[0]);
89916 zNeedle = sqlite3_value_blob(argv[1]);
89917 isText = 0;
89918 }else{
89919 zHaystack = sqlite3_value_text(argv[0]);
89920 zNeedle = sqlite3_value_text(argv[1]);
89921 isText = 1;
89923 while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
89924 N++;
89926 nHaystack--;
89927 zHaystack++;
89928 }while( isText && (zHaystack[0]&0xc0)==0x80 );
89930 if( nNeedle>nHaystack ) N = 0;
89931 sqlite3_result_int(context, N);
89935 ** Implementation of the printf() function.
89937 static void printfFunc(
89938 sqlite3_context *context,
89939 int argc,
89940 sqlite3_value **argv
89942 PrintfArguments x;
89943 StrAccum str;
89944 const char *zFormat;
89945 int n;
89947 if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
89948 x.nArg = argc-1;
89949 x.nUsed = 0;
89950 x.apArg = argv+1;
89951 sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
89952 str.db = sqlite3_context_db_handle(context);
89953 sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
89954 n = str.nChar;
89955 sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
89956 SQLITE_DYNAMIC);
89961 ** Implementation of the substr() function.
89963 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
89964 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
89965 ** of x. If x is text, then we actually count UTF-8 characters.
89966 ** If x is a blob, then we count bytes.
89968 ** If p1 is negative, then we begin abs(p1) from the end of x[].
89970 ** If p2 is negative, return the p2 characters preceding p1.
89972 static void substrFunc(
89973 sqlite3_context *context,
89974 int argc,
89975 sqlite3_value **argv
89977 const unsigned char *z;
89978 const unsigned char *z2;
89979 int len;
89980 int p0type;
89981 i64 p1, p2;
89982 int negP2 = 0;
89984 assert( argc==3 || argc==2 );
89985 if( sqlite3_value_type(argv[1])==SQLITE_NULL
89986 || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
89988 return;
89990 p0type = sqlite3_value_type(argv[0]);
89991 p1 = sqlite3_value_int(argv[1]);
89992 if( p0type==SQLITE_BLOB ){
89993 len = sqlite3_value_bytes(argv[0]);
89994 z = sqlite3_value_blob(argv[0]);
89995 if( z==0 ) return;
89996 assert( len==sqlite3_value_bytes(argv[0]) );
89997 }else{
89998 z = sqlite3_value_text(argv[0]);
89999 if( z==0 ) return;
90000 len = 0;
90001 if( p1<0 ){
90002 for(z2=z; *z2; len++){
90003 SQLITE_SKIP_UTF8(z2);
90007 if( argc==3 ){
90008 p2 = sqlite3_value_int(argv[2]);
90009 if( p2<0 ){
90010 p2 = -p2;
90011 negP2 = 1;
90013 }else{
90014 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
90016 if( p1<0 ){
90017 p1 += len;
90018 if( p1<0 ){
90019 p2 += p1;
90020 if( p2<0 ) p2 = 0;
90021 p1 = 0;
90023 }else if( p1>0 ){
90024 p1--;
90025 }else if( p2>0 ){
90026 p2--;
90028 if( negP2 ){
90029 p1 -= p2;
90030 if( p1<0 ){
90031 p2 += p1;
90032 p1 = 0;
90035 assert( p1>=0 && p2>=0 );
90036 if( p0type!=SQLITE_BLOB ){
90037 while( *z && p1 ){
90038 SQLITE_SKIP_UTF8(z);
90039 p1--;
90041 for(z2=z; *z2 && p2; p2--){
90042 SQLITE_SKIP_UTF8(z2);
90044 sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
90045 }else{
90046 if( p1+p2>len ){
90047 p2 = len-p1;
90048 if( p2<0 ) p2 = 0;
90050 sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
90055 ** Implementation of the round() function
90057 #ifndef SQLITE_OMIT_FLOATING_POINT
90058 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
90059 int n = 0;
90060 double r;
90061 char *zBuf;
90062 assert( argc==1 || argc==2 );
90063 if( argc==2 ){
90064 if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
90065 n = sqlite3_value_int(argv[1]);
90066 if( n>30 ) n = 30;
90067 if( n<0 ) n = 0;
90069 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
90070 r = sqlite3_value_double(argv[0]);
90071 /* If Y==0 and X will fit in a 64-bit int,
90072 ** handle the rounding directly,
90073 ** otherwise use printf.
90075 if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
90076 r = (double)((sqlite_int64)(r+0.5));
90077 }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
90078 r = -(double)((sqlite_int64)((-r)+0.5));
90079 }else{
90080 zBuf = sqlite3_mprintf("%.*f",n,r);
90081 if( zBuf==0 ){
90082 sqlite3_result_error_nomem(context);
90083 return;
90085 sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
90086 sqlite3_free(zBuf);
90088 sqlite3_result_double(context, r);
90090 #endif
90093 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
90094 ** allocation fails, call sqlite3_result_error_nomem() to notify
90095 ** the database handle that malloc() has failed and return NULL.
90096 ** If nByte is larger than the maximum string or blob length, then
90097 ** raise an SQLITE_TOOBIG exception and return NULL.
90099 static void *contextMalloc(sqlite3_context *context, i64 nByte){
90100 char *z;
90101 sqlite3 *db = sqlite3_context_db_handle(context);
90102 assert( nByte>0 );
90103 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
90104 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
90105 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
90106 sqlite3_result_error_toobig(context);
90107 z = 0;
90108 }else{
90109 z = sqlite3Malloc((int)nByte);
90110 if( !z ){
90111 sqlite3_result_error_nomem(context);
90114 return z;
90118 ** Implementation of the upper() and lower() SQL functions.
90120 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
90121 char *z1;
90122 const char *z2;
90123 int i, n;
90124 UNUSED_PARAMETER(argc);
90125 z2 = (char*)sqlite3_value_text(argv[0]);
90126 n = sqlite3_value_bytes(argv[0]);
90127 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
90128 assert( z2==(char*)sqlite3_value_text(argv[0]) );
90129 if( z2 ){
90130 z1 = contextMalloc(context, ((i64)n)+1);
90131 if( z1 ){
90132 for(i=0; i<n; i++){
90133 z1[i] = (char)sqlite3Toupper(z2[i]);
90135 sqlite3_result_text(context, z1, n, sqlite3_free);
90139 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
90140 char *z1;
90141 const char *z2;
90142 int i, n;
90143 UNUSED_PARAMETER(argc);
90144 z2 = (char*)sqlite3_value_text(argv[0]);
90145 n = sqlite3_value_bytes(argv[0]);
90146 /* Verify that the call to _bytes() does not invalidate the _text() pointer */
90147 assert( z2==(char*)sqlite3_value_text(argv[0]) );
90148 if( z2 ){
90149 z1 = contextMalloc(context, ((i64)n)+1);
90150 if( z1 ){
90151 for(i=0; i<n; i++){
90152 z1[i] = sqlite3Tolower(z2[i]);
90154 sqlite3_result_text(context, z1, n, sqlite3_free);
90160 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
90161 ** as VDBE code so that unused argument values do not have to be computed.
90162 ** However, we still need some kind of function implementation for this
90163 ** routines in the function table. The noopFunc macro provides this.
90164 ** noopFunc will never be called so it doesn't matter what the implementation
90165 ** is. We might as well use the "version()" function as a substitute.
90167 #define noopFunc versionFunc /* Substitute function - never called */
90170 ** Implementation of random(). Return a random integer.
90172 static void randomFunc(
90173 sqlite3_context *context,
90174 int NotUsed,
90175 sqlite3_value **NotUsed2
90177 sqlite_int64 r;
90178 UNUSED_PARAMETER2(NotUsed, NotUsed2);
90179 sqlite3_randomness(sizeof(r), &r);
90180 if( r<0 ){
90181 /* We need to prevent a random number of 0x8000000000000000
90182 ** (or -9223372036854775808) since when you do abs() of that
90183 ** number of you get the same value back again. To do this
90184 ** in a way that is testable, mask the sign bit off of negative
90185 ** values, resulting in a positive value. Then take the
90186 ** 2s complement of that positive value. The end result can
90187 ** therefore be no less than -9223372036854775807.
90189 r = -(r & LARGEST_INT64);
90191 sqlite3_result_int64(context, r);
90195 ** Implementation of randomblob(N). Return a random blob
90196 ** that is N bytes long.
90198 static void randomBlob(
90199 sqlite3_context *context,
90200 int argc,
90201 sqlite3_value **argv
90203 int n;
90204 unsigned char *p;
90205 assert( argc==1 );
90206 UNUSED_PARAMETER(argc);
90207 n = sqlite3_value_int(argv[0]);
90208 if( n<1 ){
90209 n = 1;
90211 p = contextMalloc(context, n);
90212 if( p ){
90213 sqlite3_randomness(n, p);
90214 sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
90219 ** Implementation of the last_insert_rowid() SQL function. The return
90220 ** value is the same as the sqlite3_last_insert_rowid() API function.
90222 static void last_insert_rowid(
90223 sqlite3_context *context,
90224 int NotUsed,
90225 sqlite3_value **NotUsed2
90227 sqlite3 *db = sqlite3_context_db_handle(context);
90228 UNUSED_PARAMETER2(NotUsed, NotUsed2);
90229 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
90230 ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
90231 ** function. */
90232 sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
90236 ** Implementation of the changes() SQL function.
90238 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
90239 ** around the sqlite3_changes() C/C++ function and hence follows the same
90240 ** rules for counting changes.
90242 static void changes(
90243 sqlite3_context *context,
90244 int NotUsed,
90245 sqlite3_value **NotUsed2
90247 sqlite3 *db = sqlite3_context_db_handle(context);
90248 UNUSED_PARAMETER2(NotUsed, NotUsed2);
90249 sqlite3_result_int(context, sqlite3_changes(db));
90253 ** Implementation of the total_changes() SQL function. The return value is
90254 ** the same as the sqlite3_total_changes() API function.
90256 static void total_changes(
90257 sqlite3_context *context,
90258 int NotUsed,
90259 sqlite3_value **NotUsed2
90261 sqlite3 *db = sqlite3_context_db_handle(context);
90262 UNUSED_PARAMETER2(NotUsed, NotUsed2);
90263 /* IMP: R-52756-41993 This function is a wrapper around the
90264 ** sqlite3_total_changes() C/C++ interface. */
90265 sqlite3_result_int(context, sqlite3_total_changes(db));
90269 ** A structure defining how to do GLOB-style comparisons.
90271 struct compareInfo {
90272 u8 matchAll;
90273 u8 matchOne;
90274 u8 matchSet;
90275 u8 noCase;
90279 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
90280 ** character is exactly one byte in size. Also, all characters are
90281 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
90282 ** whereas only characters less than 0x80 do in ASCII.
90284 #if defined(SQLITE_EBCDIC)
90285 # define sqlite3Utf8Read(A) (*((*A)++))
90286 # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
90287 #else
90288 # define GlobUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
90289 #endif
90291 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
90292 /* The correct SQL-92 behavior is for the LIKE operator to ignore
90293 ** case. Thus 'a' LIKE 'A' would be true. */
90294 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
90295 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
90296 ** is case sensitive causing 'a' LIKE 'A' to be false */
90297 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
90300 ** Compare two UTF-8 strings for equality where the first string can
90301 ** potentially be a "glob" expression. Return true (1) if they
90302 ** are the same and false (0) if they are different.
90304 ** Globbing rules:
90306 ** '*' Matches any sequence of zero or more characters.
90308 ** '?' Matches exactly one character.
90310 ** [...] Matches one character from the enclosed list of
90311 ** characters.
90313 ** [^...] Matches one character not in the enclosed list.
90315 ** With the [...] and [^...] matching, a ']' character can be included
90316 ** in the list by making it the first character after '[' or '^'. A
90317 ** range of characters can be specified using '-'. Example:
90318 ** "[a-z]" matches any single lower-case letter. To match a '-', make
90319 ** it the last character in the list.
90321 ** This routine is usually quick, but can be N**2 in the worst case.
90323 ** Hints: to match '*' or '?', put them in "[]". Like this:
90325 ** abc[*]xyz Matches "abc*xyz" only
90327 static int patternCompare(
90328 const u8 *zPattern, /* The glob pattern */
90329 const u8 *zString, /* The string to compare against the glob */
90330 const struct compareInfo *pInfo, /* Information about how to do the compare */
90331 u32 esc /* The escape character */
90333 u32 c, c2;
90334 int invert;
90335 int seen;
90336 u8 matchOne = pInfo->matchOne;
90337 u8 matchAll = pInfo->matchAll;
90338 u8 matchSet = pInfo->matchSet;
90339 u8 noCase = pInfo->noCase;
90340 int prevEscape = 0; /* True if the previous character was 'escape' */
90342 while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
90343 if( c==matchAll && !prevEscape ){
90344 while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
90345 || c == matchOne ){
90346 if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
90347 return 0;
90350 if( c==0 ){
90351 return 1;
90352 }else if( c==esc ){
90353 c = sqlite3Utf8Read(&zPattern);
90354 if( c==0 ){
90355 return 0;
90357 }else if( c==matchSet ){
90358 assert( esc==0 ); /* This is GLOB, not LIKE */
90359 assert( matchSet<0x80 ); /* '[' is a single-byte character */
90360 while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
90361 SQLITE_SKIP_UTF8(zString);
90363 return *zString!=0;
90365 while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
90366 if( noCase ){
90367 GlobUpperToLower(c2);
90368 GlobUpperToLower(c);
90369 while( c2 != 0 && c2 != c ){
90370 c2 = sqlite3Utf8Read(&zString);
90371 GlobUpperToLower(c2);
90373 }else{
90374 while( c2 != 0 && c2 != c ){
90375 c2 = sqlite3Utf8Read(&zString);
90378 if( c2==0 ) return 0;
90379 if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
90381 return 0;
90382 }else if( c==matchOne && !prevEscape ){
90383 if( sqlite3Utf8Read(&zString)==0 ){
90384 return 0;
90386 }else if( c==matchSet ){
90387 u32 prior_c = 0;
90388 assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
90389 seen = 0;
90390 invert = 0;
90391 c = sqlite3Utf8Read(&zString);
90392 if( c==0 ) return 0;
90393 c2 = sqlite3Utf8Read(&zPattern);
90394 if( c2=='^' ){
90395 invert = 1;
90396 c2 = sqlite3Utf8Read(&zPattern);
90398 if( c2==']' ){
90399 if( c==']' ) seen = 1;
90400 c2 = sqlite3Utf8Read(&zPattern);
90402 while( c2 && c2!=']' ){
90403 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
90404 c2 = sqlite3Utf8Read(&zPattern);
90405 if( c>=prior_c && c<=c2 ) seen = 1;
90406 prior_c = 0;
90407 }else{
90408 if( c==c2 ){
90409 seen = 1;
90411 prior_c = c2;
90413 c2 = sqlite3Utf8Read(&zPattern);
90415 if( c2==0 || (seen ^ invert)==0 ){
90416 return 0;
90418 }else if( esc==c && !prevEscape ){
90419 prevEscape = 1;
90420 }else{
90421 c2 = sqlite3Utf8Read(&zString);
90422 if( noCase ){
90423 GlobUpperToLower(c);
90424 GlobUpperToLower(c2);
90426 if( c!=c2 ){
90427 return 0;
90429 prevEscape = 0;
90432 return *zString==0;
90436 ** The sqlite3_strglob() interface.
90438 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
90439 return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
90443 ** Count the number of times that the LIKE operator (or GLOB which is
90444 ** just a variation of LIKE) gets called. This is used for testing
90445 ** only.
90447 #ifdef SQLITE_TEST
90448 SQLITE_API int sqlite3_like_count = 0;
90449 #endif
90453 ** Implementation of the like() SQL function. This function implements
90454 ** the build-in LIKE operator. The first argument to the function is the
90455 ** pattern and the second argument is the string. So, the SQL statements:
90457 ** A LIKE B
90459 ** is implemented as like(B,A).
90461 ** This same function (with a different compareInfo structure) computes
90462 ** the GLOB operator.
90464 static void likeFunc(
90465 sqlite3_context *context,
90466 int argc,
90467 sqlite3_value **argv
90469 const unsigned char *zA, *zB;
90470 u32 escape = 0;
90471 int nPat;
90472 sqlite3 *db = sqlite3_context_db_handle(context);
90474 zB = sqlite3_value_text(argv[0]);
90475 zA = sqlite3_value_text(argv[1]);
90477 /* Limit the length of the LIKE or GLOB pattern to avoid problems
90478 ** of deep recursion and N*N behavior in patternCompare().
90480 nPat = sqlite3_value_bytes(argv[0]);
90481 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
90482 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
90483 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
90484 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
90485 return;
90487 assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
90489 if( argc==3 ){
90490 /* The escape character string must consist of a single UTF-8 character.
90491 ** Otherwise, return an error.
90493 const unsigned char *zEsc = sqlite3_value_text(argv[2]);
90494 if( zEsc==0 ) return;
90495 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
90496 sqlite3_result_error(context,
90497 "ESCAPE expression must be a single character", -1);
90498 return;
90500 escape = sqlite3Utf8Read(&zEsc);
90502 if( zA && zB ){
90503 struct compareInfo *pInfo = sqlite3_user_data(context);
90504 #ifdef SQLITE_TEST
90505 sqlite3_like_count++;
90506 #endif
90508 sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
90513 ** Implementation of the NULLIF(x,y) function. The result is the first
90514 ** argument if the arguments are different. The result is NULL if the
90515 ** arguments are equal to each other.
90517 static void nullifFunc(
90518 sqlite3_context *context,
90519 int NotUsed,
90520 sqlite3_value **argv
90522 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
90523 UNUSED_PARAMETER(NotUsed);
90524 if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
90525 sqlite3_result_value(context, argv[0]);
90530 ** Implementation of the sqlite_version() function. The result is the version
90531 ** of the SQLite library that is running.
90533 static void versionFunc(
90534 sqlite3_context *context,
90535 int NotUsed,
90536 sqlite3_value **NotUsed2
90538 UNUSED_PARAMETER2(NotUsed, NotUsed2);
90539 /* IMP: R-48699-48617 This function is an SQL wrapper around the
90540 ** sqlite3_libversion() C-interface. */
90541 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
90545 ** Implementation of the sqlite_source_id() function. The result is a string
90546 ** that identifies the particular version of the source code used to build
90547 ** SQLite.
90549 static void sourceidFunc(
90550 sqlite3_context *context,
90551 int NotUsed,
90552 sqlite3_value **NotUsed2
90554 UNUSED_PARAMETER2(NotUsed, NotUsed2);
90555 /* IMP: R-24470-31136 This function is an SQL wrapper around the
90556 ** sqlite3_sourceid() C interface. */
90557 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
90561 ** Implementation of the sqlite_log() function. This is a wrapper around
90562 ** sqlite3_log(). The return value is NULL. The function exists purely for
90563 ** its side-effects.
90565 static void errlogFunc(
90566 sqlite3_context *context,
90567 int argc,
90568 sqlite3_value **argv
90570 UNUSED_PARAMETER(argc);
90571 UNUSED_PARAMETER(context);
90572 sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
90576 ** Implementation of the sqlite_compileoption_used() function.
90577 ** The result is an integer that identifies if the compiler option
90578 ** was used to build SQLite.
90580 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
90581 static void compileoptionusedFunc(
90582 sqlite3_context *context,
90583 int argc,
90584 sqlite3_value **argv
90586 const char *zOptName;
90587 assert( argc==1 );
90588 UNUSED_PARAMETER(argc);
90589 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
90590 ** function is a wrapper around the sqlite3_compileoption_used() C/C++
90591 ** function.
90593 if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
90594 sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
90597 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
90600 ** Implementation of the sqlite_compileoption_get() function.
90601 ** The result is a string that identifies the compiler options
90602 ** used to build SQLite.
90604 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
90605 static void compileoptiongetFunc(
90606 sqlite3_context *context,
90607 int argc,
90608 sqlite3_value **argv
90610 int n;
90611 assert( argc==1 );
90612 UNUSED_PARAMETER(argc);
90613 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
90614 ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
90616 n = sqlite3_value_int(argv[0]);
90617 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
90619 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
90621 /* Array for converting from half-bytes (nybbles) into ASCII hex
90622 ** digits. */
90623 static const char hexdigits[] = {
90624 '0', '1', '2', '3', '4', '5', '6', '7',
90625 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
90629 ** Implementation of the QUOTE() function. This function takes a single
90630 ** argument. If the argument is numeric, the return value is the same as
90631 ** the argument. If the argument is NULL, the return value is the string
90632 ** "NULL". Otherwise, the argument is enclosed in single quotes with
90633 ** single-quote escapes.
90635 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
90636 assert( argc==1 );
90637 UNUSED_PARAMETER(argc);
90638 switch( sqlite3_value_type(argv[0]) ){
90639 case SQLITE_FLOAT: {
90640 double r1, r2;
90641 char zBuf[50];
90642 r1 = sqlite3_value_double(argv[0]);
90643 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
90644 sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
90645 if( r1!=r2 ){
90646 sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
90648 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
90649 break;
90651 case SQLITE_INTEGER: {
90652 sqlite3_result_value(context, argv[0]);
90653 break;
90655 case SQLITE_BLOB: {
90656 char *zText = 0;
90657 char const *zBlob = sqlite3_value_blob(argv[0]);
90658 int nBlob = sqlite3_value_bytes(argv[0]);
90659 assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
90660 zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
90661 if( zText ){
90662 int i;
90663 for(i=0; i<nBlob; i++){
90664 zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
90665 zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
90667 zText[(nBlob*2)+2] = '\'';
90668 zText[(nBlob*2)+3] = '\0';
90669 zText[0] = 'X';
90670 zText[1] = '\'';
90671 sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
90672 sqlite3_free(zText);
90674 break;
90676 case SQLITE_TEXT: {
90677 int i,j;
90678 u64 n;
90679 const unsigned char *zArg = sqlite3_value_text(argv[0]);
90680 char *z;
90682 if( zArg==0 ) return;
90683 for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
90684 z = contextMalloc(context, ((i64)i)+((i64)n)+3);
90685 if( z ){
90686 z[0] = '\'';
90687 for(i=0, j=1; zArg[i]; i++){
90688 z[j++] = zArg[i];
90689 if( zArg[i]=='\'' ){
90690 z[j++] = '\'';
90693 z[j++] = '\'';
90694 z[j] = 0;
90695 sqlite3_result_text(context, z, j, sqlite3_free);
90697 break;
90699 default: {
90700 assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
90701 sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
90702 break;
90708 ** The unicode() function. Return the integer unicode code-point value
90709 ** for the first character of the input string.
90711 static void unicodeFunc(
90712 sqlite3_context *context,
90713 int argc,
90714 sqlite3_value **argv
90716 const unsigned char *z = sqlite3_value_text(argv[0]);
90717 (void)argc;
90718 if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
90722 ** The char() function takes zero or more arguments, each of which is
90723 ** an integer. It constructs a string where each character of the string
90724 ** is the unicode character for the corresponding integer argument.
90726 static void charFunc(
90727 sqlite3_context *context,
90728 int argc,
90729 sqlite3_value **argv
90731 unsigned char *z, *zOut;
90732 int i;
90733 zOut = z = sqlite3_malloc( argc*4 );
90734 if( z==0 ){
90735 sqlite3_result_error_nomem(context);
90736 return;
90738 for(i=0; i<argc; i++){
90739 sqlite3_int64 x;
90740 unsigned c;
90741 x = sqlite3_value_int64(argv[i]);
90742 if( x<0 || x>0x10ffff ) x = 0xfffd;
90743 c = (unsigned)(x & 0x1fffff);
90744 if( c<0x00080 ){
90745 *zOut++ = (u8)(c&0xFF);
90746 }else if( c<0x00800 ){
90747 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
90748 *zOut++ = 0x80 + (u8)(c & 0x3F);
90749 }else if( c<0x10000 ){
90750 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
90751 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
90752 *zOut++ = 0x80 + (u8)(c & 0x3F);
90753 }else{
90754 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
90755 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
90756 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
90757 *zOut++ = 0x80 + (u8)(c & 0x3F);
90760 sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
90764 ** The hex() function. Interpret the argument as a blob. Return
90765 ** a hexadecimal rendering as text.
90767 static void hexFunc(
90768 sqlite3_context *context,
90769 int argc,
90770 sqlite3_value **argv
90772 int i, n;
90773 const unsigned char *pBlob;
90774 char *zHex, *z;
90775 assert( argc==1 );
90776 UNUSED_PARAMETER(argc);
90777 pBlob = sqlite3_value_blob(argv[0]);
90778 n = sqlite3_value_bytes(argv[0]);
90779 assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
90780 z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
90781 if( zHex ){
90782 for(i=0; i<n; i++, pBlob++){
90783 unsigned char c = *pBlob;
90784 *(z++) = hexdigits[(c>>4)&0xf];
90785 *(z++) = hexdigits[c&0xf];
90787 *z = 0;
90788 sqlite3_result_text(context, zHex, n*2, sqlite3_free);
90793 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
90795 static void zeroblobFunc(
90796 sqlite3_context *context,
90797 int argc,
90798 sqlite3_value **argv
90800 i64 n;
90801 sqlite3 *db = sqlite3_context_db_handle(context);
90802 assert( argc==1 );
90803 UNUSED_PARAMETER(argc);
90804 n = sqlite3_value_int64(argv[0]);
90805 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
90806 testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
90807 if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
90808 sqlite3_result_error_toobig(context);
90809 }else{
90810 sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
90815 ** The replace() function. Three arguments are all strings: call
90816 ** them A, B, and C. The result is also a string which is derived
90817 ** from A by replacing every occurrence of B with C. The match
90818 ** must be exact. Collating sequences are not used.
90820 static void replaceFunc(
90821 sqlite3_context *context,
90822 int argc,
90823 sqlite3_value **argv
90825 const unsigned char *zStr; /* The input string A */
90826 const unsigned char *zPattern; /* The pattern string B */
90827 const unsigned char *zRep; /* The replacement string C */
90828 unsigned char *zOut; /* The output */
90829 int nStr; /* Size of zStr */
90830 int nPattern; /* Size of zPattern */
90831 int nRep; /* Size of zRep */
90832 i64 nOut; /* Maximum size of zOut */
90833 int loopLimit; /* Last zStr[] that might match zPattern[] */
90834 int i, j; /* Loop counters */
90836 assert( argc==3 );
90837 UNUSED_PARAMETER(argc);
90838 zStr = sqlite3_value_text(argv[0]);
90839 if( zStr==0 ) return;
90840 nStr = sqlite3_value_bytes(argv[0]);
90841 assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
90842 zPattern = sqlite3_value_text(argv[1]);
90843 if( zPattern==0 ){
90844 assert( sqlite3_value_type(argv[1])==SQLITE_NULL
90845 || sqlite3_context_db_handle(context)->mallocFailed );
90846 return;
90848 if( zPattern[0]==0 ){
90849 assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
90850 sqlite3_result_value(context, argv[0]);
90851 return;
90853 nPattern = sqlite3_value_bytes(argv[1]);
90854 assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
90855 zRep = sqlite3_value_text(argv[2]);
90856 if( zRep==0 ) return;
90857 nRep = sqlite3_value_bytes(argv[2]);
90858 assert( zRep==sqlite3_value_text(argv[2]) );
90859 nOut = nStr + 1;
90860 assert( nOut<SQLITE_MAX_LENGTH );
90861 zOut = contextMalloc(context, (i64)nOut);
90862 if( zOut==0 ){
90863 return;
90865 loopLimit = nStr - nPattern;
90866 for(i=j=0; i<=loopLimit; i++){
90867 if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
90868 zOut[j++] = zStr[i];
90869 }else{
90870 u8 *zOld;
90871 sqlite3 *db = sqlite3_context_db_handle(context);
90872 nOut += nRep - nPattern;
90873 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
90874 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
90875 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
90876 sqlite3_result_error_toobig(context);
90877 sqlite3_free(zOut);
90878 return;
90880 zOld = zOut;
90881 zOut = sqlite3_realloc(zOut, (int)nOut);
90882 if( zOut==0 ){
90883 sqlite3_result_error_nomem(context);
90884 sqlite3_free(zOld);
90885 return;
90887 memcpy(&zOut[j], zRep, nRep);
90888 j += nRep;
90889 i += nPattern-1;
90892 assert( j+nStr-i+1==nOut );
90893 memcpy(&zOut[j], &zStr[i], nStr-i);
90894 j += nStr - i;
90895 assert( j<=nOut );
90896 zOut[j] = 0;
90897 sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
90901 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
90902 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
90904 static void trimFunc(
90905 sqlite3_context *context,
90906 int argc,
90907 sqlite3_value **argv
90909 const unsigned char *zIn; /* Input string */
90910 const unsigned char *zCharSet; /* Set of characters to trim */
90911 int nIn; /* Number of bytes in input */
90912 int flags; /* 1: trimleft 2: trimright 3: trim */
90913 int i; /* Loop counter */
90914 unsigned char *aLen = 0; /* Length of each character in zCharSet */
90915 unsigned char **azChar = 0; /* Individual characters in zCharSet */
90916 int nChar; /* Number of characters in zCharSet */
90918 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
90919 return;
90921 zIn = sqlite3_value_text(argv[0]);
90922 if( zIn==0 ) return;
90923 nIn = sqlite3_value_bytes(argv[0]);
90924 assert( zIn==sqlite3_value_text(argv[0]) );
90925 if( argc==1 ){
90926 static const unsigned char lenOne[] = { 1 };
90927 static unsigned char * const azOne[] = { (u8*)" " };
90928 nChar = 1;
90929 aLen = (u8*)lenOne;
90930 azChar = (unsigned char **)azOne;
90931 zCharSet = 0;
90932 }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
90933 return;
90934 }else{
90935 const unsigned char *z;
90936 for(z=zCharSet, nChar=0; *z; nChar++){
90937 SQLITE_SKIP_UTF8(z);
90939 if( nChar>0 ){
90940 azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
90941 if( azChar==0 ){
90942 return;
90944 aLen = (unsigned char*)&azChar[nChar];
90945 for(z=zCharSet, nChar=0; *z; nChar++){
90946 azChar[nChar] = (unsigned char *)z;
90947 SQLITE_SKIP_UTF8(z);
90948 aLen[nChar] = (u8)(z - azChar[nChar]);
90952 if( nChar>0 ){
90953 flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
90954 if( flags & 1 ){
90955 while( nIn>0 ){
90956 int len = 0;
90957 for(i=0; i<nChar; i++){
90958 len = aLen[i];
90959 if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
90961 if( i>=nChar ) break;
90962 zIn += len;
90963 nIn -= len;
90966 if( flags & 2 ){
90967 while( nIn>0 ){
90968 int len = 0;
90969 for(i=0; i<nChar; i++){
90970 len = aLen[i];
90971 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
90973 if( i>=nChar ) break;
90974 nIn -= len;
90977 if( zCharSet ){
90978 sqlite3_free(azChar);
90981 sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
90985 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
90986 ** is only available if the SQLITE_SOUNDEX compile-time option is used
90987 ** when SQLite is built.
90989 #ifdef SQLITE_SOUNDEX
90991 ** Compute the soundex encoding of a word.
90993 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
90994 ** soundex encoding of the string X.
90996 static void soundexFunc(
90997 sqlite3_context *context,
90998 int argc,
90999 sqlite3_value **argv
91001 char zResult[8];
91002 const u8 *zIn;
91003 int i, j;
91004 static const unsigned char iCode[] = {
91005 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
91006 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
91007 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
91008 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
91009 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
91010 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
91011 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
91012 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
91014 assert( argc==1 );
91015 zIn = (u8*)sqlite3_value_text(argv[0]);
91016 if( zIn==0 ) zIn = (u8*)"";
91017 for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
91018 if( zIn[i] ){
91019 u8 prevcode = iCode[zIn[i]&0x7f];
91020 zResult[0] = sqlite3Toupper(zIn[i]);
91021 for(j=1; j<4 && zIn[i]; i++){
91022 int code = iCode[zIn[i]&0x7f];
91023 if( code>0 ){
91024 if( code!=prevcode ){
91025 prevcode = code;
91026 zResult[j++] = code + '0';
91028 }else{
91029 prevcode = 0;
91032 while( j<4 ){
91033 zResult[j++] = '0';
91035 zResult[j] = 0;
91036 sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
91037 }else{
91038 /* IMP: R-64894-50321 The string "?000" is returned if the argument
91039 ** is NULL or contains no ASCII alphabetic characters. */
91040 sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
91043 #endif /* SQLITE_SOUNDEX */
91045 #ifndef SQLITE_OMIT_LOAD_EXTENSION
91047 ** A function that loads a shared-library extension then returns NULL.
91049 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
91050 const char *zFile = (const char *)sqlite3_value_text(argv[0]);
91051 const char *zProc;
91052 sqlite3 *db = sqlite3_context_db_handle(context);
91053 char *zErrMsg = 0;
91055 if( argc==2 ){
91056 zProc = (const char *)sqlite3_value_text(argv[1]);
91057 }else{
91058 zProc = 0;
91060 if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
91061 sqlite3_result_error(context, zErrMsg, -1);
91062 sqlite3_free(zErrMsg);
91065 #endif
91069 ** An instance of the following structure holds the context of a
91070 ** sum() or avg() aggregate computation.
91072 typedef struct SumCtx SumCtx;
91073 struct SumCtx {
91074 double rSum; /* Floating point sum */
91075 i64 iSum; /* Integer sum */
91076 i64 cnt; /* Number of elements summed */
91077 u8 overflow; /* True if integer overflow seen */
91078 u8 approx; /* True if non-integer value was input to the sum */
91082 ** Routines used to compute the sum, average, and total.
91084 ** The SUM() function follows the (broken) SQL standard which means
91085 ** that it returns NULL if it sums over no inputs. TOTAL returns
91086 ** 0.0 in that case. In addition, TOTAL always returns a float where
91087 ** SUM might return an integer if it never encounters a floating point
91088 ** value. TOTAL never fails, but SUM might through an exception if
91089 ** it overflows an integer.
91091 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
91092 SumCtx *p;
91093 int type;
91094 assert( argc==1 );
91095 UNUSED_PARAMETER(argc);
91096 p = sqlite3_aggregate_context(context, sizeof(*p));
91097 type = sqlite3_value_numeric_type(argv[0]);
91098 if( p && type!=SQLITE_NULL ){
91099 p->cnt++;
91100 if( type==SQLITE_INTEGER ){
91101 i64 v = sqlite3_value_int64(argv[0]);
91102 p->rSum += v;
91103 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
91104 p->overflow = 1;
91106 }else{
91107 p->rSum += sqlite3_value_double(argv[0]);
91108 p->approx = 1;
91112 static void sumFinalize(sqlite3_context *context){
91113 SumCtx *p;
91114 p = sqlite3_aggregate_context(context, 0);
91115 if( p && p->cnt>0 ){
91116 if( p->overflow ){
91117 sqlite3_result_error(context,"integer overflow",-1);
91118 }else if( p->approx ){
91119 sqlite3_result_double(context, p->rSum);
91120 }else{
91121 sqlite3_result_int64(context, p->iSum);
91125 static void avgFinalize(sqlite3_context *context){
91126 SumCtx *p;
91127 p = sqlite3_aggregate_context(context, 0);
91128 if( p && p->cnt>0 ){
91129 sqlite3_result_double(context, p->rSum/(double)p->cnt);
91132 static void totalFinalize(sqlite3_context *context){
91133 SumCtx *p;
91134 p = sqlite3_aggregate_context(context, 0);
91135 /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
91136 sqlite3_result_double(context, p ? p->rSum : (double)0);
91140 ** The following structure keeps track of state information for the
91141 ** count() aggregate function.
91143 typedef struct CountCtx CountCtx;
91144 struct CountCtx {
91145 i64 n;
91149 ** Routines to implement the count() aggregate function.
91151 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
91152 CountCtx *p;
91153 p = sqlite3_aggregate_context(context, sizeof(*p));
91154 if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
91155 p->n++;
91158 #ifndef SQLITE_OMIT_DEPRECATED
91159 /* The sqlite3_aggregate_count() function is deprecated. But just to make
91160 ** sure it still operates correctly, verify that its count agrees with our
91161 ** internal count when using count(*) and when the total count can be
91162 ** expressed as a 32-bit integer. */
91163 assert( argc==1 || p==0 || p->n>0x7fffffff
91164 || p->n==sqlite3_aggregate_count(context) );
91165 #endif
91167 static void countFinalize(sqlite3_context *context){
91168 CountCtx *p;
91169 p = sqlite3_aggregate_context(context, 0);
91170 sqlite3_result_int64(context, p ? p->n : 0);
91174 ** Routines to implement min() and max() aggregate functions.
91176 static void minmaxStep(
91177 sqlite3_context *context,
91178 int NotUsed,
91179 sqlite3_value **argv
91181 Mem *pArg = (Mem *)argv[0];
91182 Mem *pBest;
91183 UNUSED_PARAMETER(NotUsed);
91185 pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
91186 if( !pBest ) return;
91188 if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
91189 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
91190 }else if( pBest->flags ){
91191 int max;
91192 int cmp;
91193 CollSeq *pColl = sqlite3GetFuncCollSeq(context);
91194 /* This step function is used for both the min() and max() aggregates,
91195 ** the only difference between the two being that the sense of the
91196 ** comparison is inverted. For the max() aggregate, the
91197 ** sqlite3_user_data() function returns (void *)-1. For min() it
91198 ** returns (void *)db, where db is the sqlite3* database pointer.
91199 ** Therefore the next statement sets variable 'max' to 1 for the max()
91200 ** aggregate, or 0 for min().
91202 max = sqlite3_user_data(context)!=0;
91203 cmp = sqlite3MemCompare(pBest, pArg, pColl);
91204 if( (max && cmp<0) || (!max && cmp>0) ){
91205 sqlite3VdbeMemCopy(pBest, pArg);
91206 }else{
91207 sqlite3SkipAccumulatorLoad(context);
91209 }else{
91210 sqlite3VdbeMemCopy(pBest, pArg);
91213 static void minMaxFinalize(sqlite3_context *context){
91214 sqlite3_value *pRes;
91215 pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
91216 if( pRes ){
91217 if( pRes->flags ){
91218 sqlite3_result_value(context, pRes);
91220 sqlite3VdbeMemRelease(pRes);
91225 ** group_concat(EXPR, ?SEPARATOR?)
91227 static void groupConcatStep(
91228 sqlite3_context *context,
91229 int argc,
91230 sqlite3_value **argv
91232 const char *zVal;
91233 StrAccum *pAccum;
91234 const char *zSep;
91235 int nVal, nSep;
91236 assert( argc==1 || argc==2 );
91237 if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
91238 pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
91240 if( pAccum ){
91241 sqlite3 *db = sqlite3_context_db_handle(context);
91242 int firstTerm = pAccum->useMalloc==0;
91243 pAccum->useMalloc = 2;
91244 pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
91245 if( !firstTerm ){
91246 if( argc==2 ){
91247 zSep = (char*)sqlite3_value_text(argv[1]);
91248 nSep = sqlite3_value_bytes(argv[1]);
91249 }else{
91250 zSep = ",";
91251 nSep = 1;
91253 if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
91255 zVal = (char*)sqlite3_value_text(argv[0]);
91256 nVal = sqlite3_value_bytes(argv[0]);
91257 if( nVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
91260 static void groupConcatFinalize(sqlite3_context *context){
91261 StrAccum *pAccum;
91262 pAccum = sqlite3_aggregate_context(context, 0);
91263 if( pAccum ){
91264 if( pAccum->accError==STRACCUM_TOOBIG ){
91265 sqlite3_result_error_toobig(context);
91266 }else if( pAccum->accError==STRACCUM_NOMEM ){
91267 sqlite3_result_error_nomem(context);
91268 }else{
91269 sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
91270 sqlite3_free);
91276 ** This routine does per-connection function registration. Most
91277 ** of the built-in functions above are part of the global function set.
91278 ** This routine only deals with those that are not global.
91280 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
91281 int rc = sqlite3_overload_function(db, "MATCH", 2);
91282 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
91283 if( rc==SQLITE_NOMEM ){
91284 db->mallocFailed = 1;
91289 ** Set the LIKEOPT flag on the 2-argument function with the given name.
91291 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
91292 FuncDef *pDef;
91293 pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
91294 2, SQLITE_UTF8, 0);
91295 if( ALWAYS(pDef) ){
91296 pDef->funcFlags |= flagVal;
91301 ** Register the built-in LIKE and GLOB functions. The caseSensitive
91302 ** parameter determines whether or not the LIKE operator is case
91303 ** sensitive. GLOB is always case sensitive.
91305 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
91306 struct compareInfo *pInfo;
91307 if( caseSensitive ){
91308 pInfo = (struct compareInfo*)&likeInfoAlt;
91309 }else{
91310 pInfo = (struct compareInfo*)&likeInfoNorm;
91312 sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
91313 sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
91314 sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
91315 (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
91316 setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
91317 setLikeOptFlag(db, "like",
91318 caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
91322 ** pExpr points to an expression which implements a function. If
91323 ** it is appropriate to apply the LIKE optimization to that function
91324 ** then set aWc[0] through aWc[2] to the wildcard characters and
91325 ** return TRUE. If the function is not a LIKE-style function then
91326 ** return FALSE.
91328 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
91329 FuncDef *pDef;
91330 if( pExpr->op!=TK_FUNCTION
91331 || !pExpr->x.pList
91332 || pExpr->x.pList->nExpr!=2
91334 return 0;
91336 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91337 pDef = sqlite3FindFunction(db, pExpr->u.zToken,
91338 sqlite3Strlen30(pExpr->u.zToken),
91339 2, SQLITE_UTF8, 0);
91340 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
91341 return 0;
91344 /* The memcpy() statement assumes that the wildcard characters are
91345 ** the first three statements in the compareInfo structure. The
91346 ** asserts() that follow verify that assumption
91348 memcpy(aWc, pDef->pUserData, 3);
91349 assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
91350 assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
91351 assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
91352 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
91353 return 1;
91357 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
91358 ** to the global function hash table. This occurs at start-time (as
91359 ** a consequence of calling sqlite3_initialize()).
91361 ** After this routine runs
91363 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
91365 ** The following array holds FuncDef structures for all of the functions
91366 ** defined in this file.
91368 ** The array cannot be constant since changes are made to the
91369 ** FuncDef.pHash elements at start-time. The elements of this array
91370 ** are read-only after initialization is complete.
91372 static SQLITE_WSD FuncDef aBuiltinFunc[] = {
91373 FUNCTION(ltrim, 1, 1, 0, trimFunc ),
91374 FUNCTION(ltrim, 2, 1, 0, trimFunc ),
91375 FUNCTION(rtrim, 1, 2, 0, trimFunc ),
91376 FUNCTION(rtrim, 2, 2, 0, trimFunc ),
91377 FUNCTION(trim, 1, 3, 0, trimFunc ),
91378 FUNCTION(trim, 2, 3, 0, trimFunc ),
91379 FUNCTION(min, -1, 0, 1, minmaxFunc ),
91380 FUNCTION(min, 0, 0, 1, 0 ),
91381 AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
91382 FUNCTION(max, -1, 1, 1, minmaxFunc ),
91383 FUNCTION(max, 0, 1, 1, 0 ),
91384 AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
91385 FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
91386 FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
91387 FUNCTION(instr, 2, 0, 0, instrFunc ),
91388 FUNCTION(substr, 2, 0, 0, substrFunc ),
91389 FUNCTION(substr, 3, 0, 0, substrFunc ),
91390 FUNCTION(printf, -1, 0, 0, printfFunc ),
91391 FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
91392 FUNCTION(char, -1, 0, 0, charFunc ),
91393 FUNCTION(abs, 1, 0, 0, absFunc ),
91394 #ifndef SQLITE_OMIT_FLOATING_POINT
91395 FUNCTION(round, 1, 0, 0, roundFunc ),
91396 FUNCTION(round, 2, 0, 0, roundFunc ),
91397 #endif
91398 FUNCTION(upper, 1, 0, 0, upperFunc ),
91399 FUNCTION(lower, 1, 0, 0, lowerFunc ),
91400 FUNCTION(coalesce, 1, 0, 0, 0 ),
91401 FUNCTION(coalesce, 0, 0, 0, 0 ),
91402 FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
91403 FUNCTION(hex, 1, 0, 0, hexFunc ),
91404 FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
91405 FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
91406 FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
91407 VFUNCTION(random, 0, 0, 0, randomFunc ),
91408 VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
91409 FUNCTION(nullif, 2, 0, 1, nullifFunc ),
91410 FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
91411 FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
91412 FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
91413 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91414 FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
91415 FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
91416 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
91417 FUNCTION(quote, 1, 0, 0, quoteFunc ),
91418 VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
91419 VFUNCTION(changes, 0, 0, 0, changes ),
91420 VFUNCTION(total_changes, 0, 0, 0, total_changes ),
91421 FUNCTION(replace, 3, 0, 0, replaceFunc ),
91422 FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
91423 #ifdef SQLITE_SOUNDEX
91424 FUNCTION(soundex, 1, 0, 0, soundexFunc ),
91425 #endif
91426 #ifndef SQLITE_OMIT_LOAD_EXTENSION
91427 FUNCTION(load_extension, 1, 0, 0, loadExt ),
91428 FUNCTION(load_extension, 2, 0, 0, loadExt ),
91429 #endif
91430 AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
91431 AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
91432 AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
91433 /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
91434 {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
91435 AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
91436 AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
91437 AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
91439 LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
91440 #ifdef SQLITE_CASE_SENSITIVE_LIKE
91441 LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
91442 LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
91443 #else
91444 LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
91445 LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
91446 #endif
91449 int i;
91450 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
91451 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
91453 for(i=0; i<ArraySize(aBuiltinFunc); i++){
91454 sqlite3FuncDefInsert(pHash, &aFunc[i]);
91456 sqlite3RegisterDateTimeFunctions();
91457 #ifndef SQLITE_OMIT_ALTERTABLE
91458 sqlite3AlterFunctions();
91459 #endif
91460 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
91461 sqlite3AnalyzeFunctions();
91462 #endif
91465 /************** End of func.c ************************************************/
91466 /************** Begin file fkey.c ********************************************/
91469 ** The author disclaims copyright to this source code. In place of
91470 ** a legal notice, here is a blessing:
91472 ** May you do good and not evil.
91473 ** May you find forgiveness for yourself and forgive others.
91474 ** May you share freely, never taking more than you give.
91476 *************************************************************************
91477 ** This file contains code used by the compiler to add foreign key
91478 ** support to compiled SQL statements.
91481 #ifndef SQLITE_OMIT_FOREIGN_KEY
91482 #ifndef SQLITE_OMIT_TRIGGER
91485 ** Deferred and Immediate FKs
91486 ** --------------------------
91488 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
91489 ** If an immediate foreign key constraint is violated,
91490 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
91491 ** statement transaction rolled back. If a
91492 ** deferred foreign key constraint is violated, no action is taken
91493 ** immediately. However if the application attempts to commit the
91494 ** transaction before fixing the constraint violation, the attempt fails.
91496 ** Deferred constraints are implemented using a simple counter associated
91497 ** with the database handle. The counter is set to zero each time a
91498 ** database transaction is opened. Each time a statement is executed
91499 ** that causes a foreign key violation, the counter is incremented. Each
91500 ** time a statement is executed that removes an existing violation from
91501 ** the database, the counter is decremented. When the transaction is
91502 ** committed, the commit fails if the current value of the counter is
91503 ** greater than zero. This scheme has two big drawbacks:
91505 ** * When a commit fails due to a deferred foreign key constraint,
91506 ** there is no way to tell which foreign constraint is not satisfied,
91507 ** or which row it is not satisfied for.
91509 ** * If the database contains foreign key violations when the
91510 ** transaction is opened, this may cause the mechanism to malfunction.
91512 ** Despite these problems, this approach is adopted as it seems simpler
91513 ** than the alternatives.
91515 ** INSERT operations:
91517 ** I.1) For each FK for which the table is the child table, search
91518 ** the parent table for a match. If none is found increment the
91519 ** constraint counter.
91521 ** I.2) For each FK for which the table is the parent table,
91522 ** search the child table for rows that correspond to the new
91523 ** row in the parent table. Decrement the counter for each row
91524 ** found (as the constraint is now satisfied).
91526 ** DELETE operations:
91528 ** D.1) For each FK for which the table is the child table,
91529 ** search the parent table for a row that corresponds to the
91530 ** deleted row in the child table. If such a row is not found,
91531 ** decrement the counter.
91533 ** D.2) For each FK for which the table is the parent table, search
91534 ** the child table for rows that correspond to the deleted row
91535 ** in the parent table. For each found increment the counter.
91537 ** UPDATE operations:
91539 ** An UPDATE command requires that all 4 steps above are taken, but only
91540 ** for FK constraints for which the affected columns are actually
91541 ** modified (values must be compared at runtime).
91543 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
91544 ** This simplifies the implementation a bit.
91546 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
91547 ** resolution is considered to delete rows before the new row is inserted.
91548 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
91549 ** is thrown, even if the FK constraint would be satisfied after the new
91550 ** row is inserted.
91552 ** Immediate constraints are usually handled similarly. The only difference
91553 ** is that the counter used is stored as part of each individual statement
91554 ** object (struct Vdbe). If, after the statement has run, its immediate
91555 ** constraint counter is greater than zero,
91556 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
91557 ** and the statement transaction is rolled back. An exception is an INSERT
91558 ** statement that inserts a single row only (no triggers). In this case,
91559 ** instead of using a counter, an exception is thrown immediately if the
91560 ** INSERT violates a foreign key constraint. This is necessary as such
91561 ** an INSERT does not open a statement transaction.
91563 ** TODO: How should dropping a table be handled? How should renaming a
91564 ** table be handled?
91567 ** Query API Notes
91568 ** ---------------
91570 ** Before coding an UPDATE or DELETE row operation, the code-generator
91571 ** for those two operations needs to know whether or not the operation
91572 ** requires any FK processing and, if so, which columns of the original
91573 ** row are required by the FK processing VDBE code (i.e. if FKs were
91574 ** implemented using triggers, which of the old.* columns would be
91575 ** accessed). No information is required by the code-generator before
91576 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
91577 ** generation code to query for this information are:
91579 ** sqlite3FkRequired() - Test to see if FK processing is required.
91580 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
91583 ** Externally accessible module functions
91584 ** --------------------------------------
91586 ** sqlite3FkCheck() - Check for foreign key violations.
91587 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
91588 ** sqlite3FkDelete() - Delete an FKey structure.
91592 ** VDBE Calling Convention
91593 ** -----------------------
91595 ** Example:
91597 ** For the following INSERT statement:
91599 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
91600 ** INSERT INTO t1 VALUES(1, 2, 3.1);
91602 ** Register (x): 2 (type integer)
91603 ** Register (x+1): 1 (type integer)
91604 ** Register (x+2): NULL (type NULL)
91605 ** Register (x+3): 3.1 (type real)
91609 ** A foreign key constraint requires that the key columns in the parent
91610 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
91611 ** Given that pParent is the parent table for foreign key constraint pFKey,
91612 ** search the schema for a unique index on the parent key columns.
91614 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
91615 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
91616 ** is set to point to the unique index.
91618 ** If the parent key consists of a single column (the foreign key constraint
91619 ** is not a composite foreign key), output variable *paiCol is set to NULL.
91620 ** Otherwise, it is set to point to an allocated array of size N, where
91621 ** N is the number of columns in the parent key. The first element of the
91622 ** array is the index of the child table column that is mapped by the FK
91623 ** constraint to the parent table column stored in the left-most column
91624 ** of index *ppIdx. The second element of the array is the index of the
91625 ** child table column that corresponds to the second left-most column of
91626 ** *ppIdx, and so on.
91628 ** If the required index cannot be found, either because:
91630 ** 1) The named parent key columns do not exist, or
91632 ** 2) The named parent key columns do exist, but are not subject to a
91633 ** UNIQUE or PRIMARY KEY constraint, or
91635 ** 3) No parent key columns were provided explicitly as part of the
91636 ** foreign key definition, and the parent table does not have a
91637 ** PRIMARY KEY, or
91639 ** 4) No parent key columns were provided explicitly as part of the
91640 ** foreign key definition, and the PRIMARY KEY of the parent table
91641 ** consists of a a different number of columns to the child key in
91642 ** the child table.
91644 ** then non-zero is returned, and a "foreign key mismatch" error loaded
91645 ** into pParse. If an OOM error occurs, non-zero is returned and the
91646 ** pParse->db->mallocFailed flag is set.
91648 SQLITE_PRIVATE int sqlite3FkLocateIndex(
91649 Parse *pParse, /* Parse context to store any error in */
91650 Table *pParent, /* Parent table of FK constraint pFKey */
91651 FKey *pFKey, /* Foreign key to find index for */
91652 Index **ppIdx, /* OUT: Unique index on parent table */
91653 int **paiCol /* OUT: Map of index columns in pFKey */
91655 Index *pIdx = 0; /* Value to return via *ppIdx */
91656 int *aiCol = 0; /* Value to return via *paiCol */
91657 int nCol = pFKey->nCol; /* Number of columns in parent key */
91658 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
91660 /* The caller is responsible for zeroing output parameters. */
91661 assert( ppIdx && *ppIdx==0 );
91662 assert( !paiCol || *paiCol==0 );
91663 assert( pParse );
91665 /* If this is a non-composite (single column) foreign key, check if it
91666 ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
91667 ** and *paiCol set to zero and return early.
91669 ** Otherwise, for a composite foreign key (more than one column), allocate
91670 ** space for the aiCol array (returned via output parameter *paiCol).
91671 ** Non-composite foreign keys do not require the aiCol array.
91673 if( nCol==1 ){
91674 /* The FK maps to the IPK if any of the following are true:
91676 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
91677 ** mapped to the primary key of table pParent, or
91678 ** 2) The FK is explicitly mapped to a column declared as INTEGER
91679 ** PRIMARY KEY.
91681 if( pParent->iPKey>=0 ){
91682 if( !zKey ) return 0;
91683 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
91685 }else if( paiCol ){
91686 assert( nCol>1 );
91687 aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
91688 if( !aiCol ) return 1;
91689 *paiCol = aiCol;
91692 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
91693 if( pIdx->nKeyCol==nCol && pIdx->onError!=OE_None ){
91694 /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
91695 ** of columns. If each indexed column corresponds to a foreign key
91696 ** column of pFKey, then this index is a winner. */
91698 if( zKey==0 ){
91699 /* If zKey is NULL, then this foreign key is implicitly mapped to
91700 ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
91701 ** identified by the test (Index.autoIndex==2). */
91702 if( pIdx->autoIndex==2 ){
91703 if( aiCol ){
91704 int i;
91705 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
91707 break;
91709 }else{
91710 /* If zKey is non-NULL, then this foreign key was declared to
91711 ** map to an explicit list of columns in table pParent. Check if this
91712 ** index matches those columns. Also, check that the index uses
91713 ** the default collation sequences for each column. */
91714 int i, j;
91715 for(i=0; i<nCol; i++){
91716 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
91717 char *zDfltColl; /* Def. collation for column */
91718 char *zIdxCol; /* Name of indexed column */
91720 /* If the index uses a collation sequence that is different from
91721 ** the default collation sequence for the column, this index is
91722 ** unusable. Bail out early in this case. */
91723 zDfltColl = pParent->aCol[iCol].zColl;
91724 if( !zDfltColl ){
91725 zDfltColl = "BINARY";
91727 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
91729 zIdxCol = pParent->aCol[iCol].zName;
91730 for(j=0; j<nCol; j++){
91731 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
91732 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
91733 break;
91736 if( j==nCol ) break;
91738 if( i==nCol ) break; /* pIdx is usable */
91743 if( !pIdx ){
91744 if( !pParse->disableTriggers ){
91745 sqlite3ErrorMsg(pParse,
91746 "foreign key mismatch - \"%w\" referencing \"%w\"",
91747 pFKey->pFrom->zName, pFKey->zTo);
91749 sqlite3DbFree(pParse->db, aiCol);
91750 return 1;
91753 *ppIdx = pIdx;
91754 return 0;
91758 ** This function is called when a row is inserted into or deleted from the
91759 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
91760 ** on the child table of pFKey, this function is invoked twice for each row
91761 ** affected - once to "delete" the old row, and then again to "insert" the
91762 ** new row.
91764 ** Each time it is called, this function generates VDBE code to locate the
91765 ** row in the parent table that corresponds to the row being inserted into
91766 ** or deleted from the child table. If the parent row can be found, no
91767 ** special action is taken. Otherwise, if the parent row can *not* be
91768 ** found in the parent table:
91770 ** Operation | FK type | Action taken
91771 ** --------------------------------------------------------------------------
91772 ** INSERT immediate Increment the "immediate constraint counter".
91774 ** DELETE immediate Decrement the "immediate constraint counter".
91776 ** INSERT deferred Increment the "deferred constraint counter".
91778 ** DELETE deferred Decrement the "deferred constraint counter".
91780 ** These operations are identified in the comment at the top of this file
91781 ** (fkey.c) as "I.1" and "D.1".
91783 static void fkLookupParent(
91784 Parse *pParse, /* Parse context */
91785 int iDb, /* Index of database housing pTab */
91786 Table *pTab, /* Parent table of FK pFKey */
91787 Index *pIdx, /* Unique index on parent key columns in pTab */
91788 FKey *pFKey, /* Foreign key constraint */
91789 int *aiCol, /* Map from parent key columns to child table columns */
91790 int regData, /* Address of array containing child table row */
91791 int nIncr, /* Increment constraint counter by this */
91792 int isIgnore /* If true, pretend pTab contains all NULL values */
91794 int i; /* Iterator variable */
91795 Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
91796 int iCur = pParse->nTab - 1; /* Cursor number to use */
91797 int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
91799 /* If nIncr is less than zero, then check at runtime if there are any
91800 ** outstanding constraints to resolve. If there are not, there is no need
91801 ** to check if deleting this row resolves any outstanding violations.
91803 ** Check if any of the key columns in the child table row are NULL. If
91804 ** any are, then the constraint is considered satisfied. No need to
91805 ** search for a matching row in the parent table. */
91806 if( nIncr<0 ){
91807 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
91809 for(i=0; i<pFKey->nCol; i++){
91810 int iReg = aiCol[i] + regData + 1;
91811 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
91814 if( isIgnore==0 ){
91815 if( pIdx==0 ){
91816 /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
91817 ** column of the parent table (table pTab). */
91818 int iMustBeInt; /* Address of MustBeInt instruction */
91819 int regTemp = sqlite3GetTempReg(pParse);
91821 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
91822 ** apply the affinity of the parent key). If this fails, then there
91823 ** is no matching parent key. Before using MustBeInt, make a copy of
91824 ** the value. Otherwise, the value inserted into the child key column
91825 ** will have INTEGER affinity applied to it, which may not be correct. */
91826 sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
91827 iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
91829 /* If the parent table is the same as the child table, and we are about
91830 ** to increment the constraint-counter (i.e. this is an INSERT operation),
91831 ** then check if the row being inserted matches itself. If so, do not
91832 ** increment the constraint-counter. */
91833 if( pTab==pFKey->pFrom && nIncr==1 ){
91834 sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
91837 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
91838 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
91839 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
91840 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
91841 sqlite3VdbeJumpHere(v, iMustBeInt);
91842 sqlite3ReleaseTempReg(pParse, regTemp);
91843 }else{
91844 int nCol = pFKey->nCol;
91845 int regTemp = sqlite3GetTempRange(pParse, nCol);
91846 int regRec = sqlite3GetTempReg(pParse);
91848 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
91849 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
91850 for(i=0; i<nCol; i++){
91851 sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
91854 /* If the parent table is the same as the child table, and we are about
91855 ** to increment the constraint-counter (i.e. this is an INSERT operation),
91856 ** then check if the row being inserted matches itself. If so, do not
91857 ** increment the constraint-counter.
91859 ** If any of the parent-key values are NULL, then the row cannot match
91860 ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
91861 ** of the parent-key values are NULL (at this point it is known that
91862 ** none of the child key values are).
91864 if( pTab==pFKey->pFrom && nIncr==1 ){
91865 int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
91866 for(i=0; i<nCol; i++){
91867 int iChild = aiCol[i]+1+regData;
91868 int iParent = pIdx->aiColumn[i]+1+regData;
91869 assert( aiCol[i]!=pTab->iPKey );
91870 if( pIdx->aiColumn[i]==pTab->iPKey ){
91871 /* The parent key is a composite key that includes the IPK column */
91872 iParent = regData;
91874 sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
91875 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
91877 sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
91880 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
91881 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
91882 sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
91884 sqlite3ReleaseTempReg(pParse, regRec);
91885 sqlite3ReleaseTempRange(pParse, regTemp, nCol);
91889 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
91890 && !pParse->pToplevel
91891 && !pParse->isMultiWrite
91893 /* Special case: If this is an INSERT statement that will insert exactly
91894 ** one row into the table, raise a constraint immediately instead of
91895 ** incrementing a counter. This is necessary as the VM code is being
91896 ** generated for will not open a statement transaction. */
91897 assert( nIncr==1 );
91898 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
91899 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
91900 }else{
91901 if( nIncr>0 && pFKey->isDeferred==0 ){
91902 sqlite3ParseToplevel(pParse)->mayAbort = 1;
91904 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
91907 sqlite3VdbeResolveLabel(v, iOk);
91908 sqlite3VdbeAddOp1(v, OP_Close, iCur);
91913 ** Return an Expr object that refers to a memory register corresponding
91914 ** to column iCol of table pTab.
91916 ** regBase is the first of an array of register that contains the data
91917 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
91918 ** column. regBase+2 holds the second column, and so forth.
91920 static Expr *exprTableRegister(
91921 Parse *pParse, /* Parsing and code generating context */
91922 Table *pTab, /* The table whose content is at r[regBase]... */
91923 int regBase, /* Contents of table pTab */
91924 i16 iCol /* Which column of pTab is desired */
91926 Expr *pExpr;
91927 Column *pCol;
91928 const char *zColl;
91929 sqlite3 *db = pParse->db;
91931 pExpr = sqlite3Expr(db, TK_REGISTER, 0);
91932 if( pExpr ){
91933 if( iCol>=0 && iCol!=pTab->iPKey ){
91934 pCol = &pTab->aCol[iCol];
91935 pExpr->iTable = regBase + iCol + 1;
91936 pExpr->affinity = pCol->affinity;
91937 zColl = pCol->zColl;
91938 if( zColl==0 ) zColl = db->pDfltColl->zName;
91939 pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
91940 }else{
91941 pExpr->iTable = regBase;
91942 pExpr->affinity = SQLITE_AFF_INTEGER;
91945 return pExpr;
91949 ** Return an Expr object that refers to column iCol of table pTab which
91950 ** has cursor iCur.
91952 static Expr *exprTableColumn(
91953 sqlite3 *db, /* The database connection */
91954 Table *pTab, /* The table whose column is desired */
91955 int iCursor, /* The open cursor on the table */
91956 i16 iCol /* The column that is wanted */
91958 Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
91959 if( pExpr ){
91960 pExpr->pTab = pTab;
91961 pExpr->iTable = iCursor;
91962 pExpr->iColumn = iCol;
91964 return pExpr;
91968 ** This function is called to generate code executed when a row is deleted
91969 ** from the parent table of foreign key constraint pFKey and, if pFKey is
91970 ** deferred, when a row is inserted into the same table. When generating
91971 ** code for an SQL UPDATE operation, this function may be called twice -
91972 ** once to "delete" the old row and once to "insert" the new row.
91974 ** The code generated by this function scans through the rows in the child
91975 ** table that correspond to the parent table row being deleted or inserted.
91976 ** For each child row found, one of the following actions is taken:
91978 ** Operation | FK type | Action taken
91979 ** --------------------------------------------------------------------------
91980 ** DELETE immediate Increment the "immediate constraint counter".
91981 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
91982 ** throw a "FOREIGN KEY constraint failed" exception.
91984 ** INSERT immediate Decrement the "immediate constraint counter".
91986 ** DELETE deferred Increment the "deferred constraint counter".
91987 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
91988 ** throw a "FOREIGN KEY constraint failed" exception.
91990 ** INSERT deferred Decrement the "deferred constraint counter".
91992 ** These operations are identified in the comment at the top of this file
91993 ** (fkey.c) as "I.2" and "D.2".
91995 static void fkScanChildren(
91996 Parse *pParse, /* Parse context */
91997 SrcList *pSrc, /* The child table to be scanned */
91998 Table *pTab, /* The parent table */
91999 Index *pIdx, /* Index on parent covering the foreign key */
92000 FKey *pFKey, /* The foreign key linking pSrc to pTab */
92001 int *aiCol, /* Map from pIdx cols to child table cols */
92002 int regData, /* Parent row data starts here */
92003 int nIncr /* Amount to increment deferred counter by */
92005 sqlite3 *db = pParse->db; /* Database handle */
92006 int i; /* Iterator variable */
92007 Expr *pWhere = 0; /* WHERE clause to scan with */
92008 NameContext sNameContext; /* Context used to resolve WHERE clause */
92009 WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
92010 int iFkIfZero = 0; /* Address of OP_FkIfZero */
92011 Vdbe *v = sqlite3GetVdbe(pParse);
92013 assert( pIdx==0 || pIdx->pTable==pTab );
92014 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
92015 assert( pIdx!=0 || pFKey->nCol==1 );
92016 assert( pIdx!=0 || HasRowid(pTab) );
92018 if( nIncr<0 ){
92019 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
92022 /* Create an Expr object representing an SQL expression like:
92024 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
92026 ** The collation sequence used for the comparison should be that of
92027 ** the parent key columns. The affinity of the parent key column should
92028 ** be applied to each child key value before the comparison takes place.
92030 for(i=0; i<pFKey->nCol; i++){
92031 Expr *pLeft; /* Value from parent table row */
92032 Expr *pRight; /* Column ref to child table */
92033 Expr *pEq; /* Expression (pLeft = pRight) */
92034 i16 iCol; /* Index of column in child table */
92035 const char *zCol; /* Name of column in child table */
92037 iCol = pIdx ? pIdx->aiColumn[i] : -1;
92038 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
92039 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
92040 assert( iCol>=0 );
92041 zCol = pFKey->pFrom->aCol[iCol].zName;
92042 pRight = sqlite3Expr(db, TK_ID, zCol);
92043 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
92044 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
92047 /* If the child table is the same as the parent table, then add terms
92048 ** to the WHERE clause that prevent this entry from being scanned.
92049 ** The added WHERE clause terms are like this:
92051 ** $current_rowid!=rowid
92052 ** NOT( $current_a==a AND $current_b==b AND ... )
92054 ** The first form is used for rowid tables. The second form is used
92055 ** for WITHOUT ROWID tables. In the second form, the primary key is
92056 ** (a,b,...)
92058 if( pTab==pFKey->pFrom && nIncr>0 ){
92059 Expr *pNe; /* Expression (pLeft != pRight) */
92060 Expr *pLeft; /* Value from parent table row */
92061 Expr *pRight; /* Column ref to child table */
92062 if( HasRowid(pTab) ){
92063 pLeft = exprTableRegister(pParse, pTab, regData, -1);
92064 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
92065 pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
92066 }else{
92067 Expr *pEq, *pAll = 0;
92068 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
92069 assert( pIdx!=0 );
92070 for(i=0; i<pPk->nKeyCol; i++){
92071 i16 iCol = pIdx->aiColumn[i];
92072 pLeft = exprTableRegister(pParse, pTab, regData, iCol);
92073 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
92074 pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
92075 pAll = sqlite3ExprAnd(db, pAll, pEq);
92077 pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
92079 pWhere = sqlite3ExprAnd(db, pWhere, pNe);
92082 /* Resolve the references in the WHERE clause. */
92083 memset(&sNameContext, 0, sizeof(NameContext));
92084 sNameContext.pSrcList = pSrc;
92085 sNameContext.pParse = pParse;
92086 sqlite3ResolveExprNames(&sNameContext, pWhere);
92088 /* Create VDBE to loop through the entries in pSrc that match the WHERE
92089 ** clause. If the constraint is not deferred, throw an exception for
92090 ** each row found. Otherwise, for deferred constraints, increment the
92091 ** deferred constraint counter by nIncr for each row selected. */
92092 pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
92093 if( nIncr>0 && pFKey->isDeferred==0 ){
92094 sqlite3ParseToplevel(pParse)->mayAbort = 1;
92096 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
92097 if( pWInfo ){
92098 sqlite3WhereEnd(pWInfo);
92101 /* Clean up the WHERE clause constructed above. */
92102 sqlite3ExprDelete(db, pWhere);
92103 if( iFkIfZero ){
92104 sqlite3VdbeJumpHere(v, iFkIfZero);
92109 ** This function returns a linked list of FKey objects (connected by
92110 ** FKey.pNextTo) holding all children of table pTab. For example,
92111 ** given the following schema:
92113 ** CREATE TABLE t1(a PRIMARY KEY);
92114 ** CREATE TABLE t2(b REFERENCES t1(a);
92116 ** Calling this function with table "t1" as an argument returns a pointer
92117 ** to the FKey structure representing the foreign key constraint on table
92118 ** "t2". Calling this function with "t2" as the argument would return a
92119 ** NULL pointer (as there are no FK constraints for which t2 is the parent
92120 ** table).
92122 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
92123 int nName = sqlite3Strlen30(pTab->zName);
92124 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
92128 ** The second argument is a Trigger structure allocated by the
92129 ** fkActionTrigger() routine. This function deletes the Trigger structure
92130 ** and all of its sub-components.
92132 ** The Trigger structure or any of its sub-components may be allocated from
92133 ** the lookaside buffer belonging to database handle dbMem.
92135 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
92136 if( p ){
92137 TriggerStep *pStep = p->step_list;
92138 sqlite3ExprDelete(dbMem, pStep->pWhere);
92139 sqlite3ExprListDelete(dbMem, pStep->pExprList);
92140 sqlite3SelectDelete(dbMem, pStep->pSelect);
92141 sqlite3ExprDelete(dbMem, p->pWhen);
92142 sqlite3DbFree(dbMem, p);
92147 ** This function is called to generate code that runs when table pTab is
92148 ** being dropped from the database. The SrcList passed as the second argument
92149 ** to this function contains a single entry guaranteed to resolve to
92150 ** table pTab.
92152 ** Normally, no code is required. However, if either
92154 ** (a) The table is the parent table of a FK constraint, or
92155 ** (b) The table is the child table of a deferred FK constraint and it is
92156 ** determined at runtime that there are outstanding deferred FK
92157 ** constraint violations in the database,
92159 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
92160 ** the table from the database. Triggers are disabled while running this
92161 ** DELETE, but foreign key actions are not.
92163 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
92164 sqlite3 *db = pParse->db;
92165 if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
92166 int iSkip = 0;
92167 Vdbe *v = sqlite3GetVdbe(pParse);
92169 assert( v ); /* VDBE has already been allocated */
92170 if( sqlite3FkReferences(pTab)==0 ){
92171 /* Search for a deferred foreign key constraint for which this table
92172 ** is the child table. If one cannot be found, return without
92173 ** generating any VDBE code. If one can be found, then jump over
92174 ** the entire DELETE if there are no outstanding deferred constraints
92175 ** when this statement is run. */
92176 FKey *p;
92177 for(p=pTab->pFKey; p; p=p->pNextFrom){
92178 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
92180 if( !p ) return;
92181 iSkip = sqlite3VdbeMakeLabel(v);
92182 sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
92185 pParse->disableTriggers = 1;
92186 sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
92187 pParse->disableTriggers = 0;
92189 /* If the DELETE has generated immediate foreign key constraint
92190 ** violations, halt the VDBE and return an error at this point, before
92191 ** any modifications to the schema are made. This is because statement
92192 ** transactions are not able to rollback schema changes.
92194 ** If the SQLITE_DeferFKs flag is set, then this is not required, as
92195 ** the statement transaction will not be rolled back even if FK
92196 ** constraints are violated.
92198 if( (db->flags & SQLITE_DeferFKs)==0 ){
92199 sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
92200 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
92201 OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
92204 if( iSkip ){
92205 sqlite3VdbeResolveLabel(v, iSkip);
92212 ** The second argument points to an FKey object representing a foreign key
92213 ** for which pTab is the child table. An UPDATE statement against pTab
92214 ** is currently being processed. For each column of the table that is
92215 ** actually updated, the corresponding element in the aChange[] array
92216 ** is zero or greater (if a column is unmodified the corresponding element
92217 ** is set to -1). If the rowid column is modified by the UPDATE statement
92218 ** the bChngRowid argument is non-zero.
92220 ** This function returns true if any of the columns that are part of the
92221 ** child key for FK constraint *p are modified.
92223 static int fkChildIsModified(
92224 Table *pTab, /* Table being updated */
92225 FKey *p, /* Foreign key for which pTab is the child */
92226 int *aChange, /* Array indicating modified columns */
92227 int bChngRowid /* True if rowid is modified by this update */
92229 int i;
92230 for(i=0; i<p->nCol; i++){
92231 int iChildKey = p->aCol[i].iFrom;
92232 if( aChange[iChildKey]>=0 ) return 1;
92233 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
92235 return 0;
92239 ** The second argument points to an FKey object representing a foreign key
92240 ** for which pTab is the parent table. An UPDATE statement against pTab
92241 ** is currently being processed. For each column of the table that is
92242 ** actually updated, the corresponding element in the aChange[] array
92243 ** is zero or greater (if a column is unmodified the corresponding element
92244 ** is set to -1). If the rowid column is modified by the UPDATE statement
92245 ** the bChngRowid argument is non-zero.
92247 ** This function returns true if any of the columns that are part of the
92248 ** parent key for FK constraint *p are modified.
92250 static int fkParentIsModified(
92251 Table *pTab,
92252 FKey *p,
92253 int *aChange,
92254 int bChngRowid
92256 int i;
92257 for(i=0; i<p->nCol; i++){
92258 char *zKey = p->aCol[i].zCol;
92259 int iKey;
92260 for(iKey=0; iKey<pTab->nCol; iKey++){
92261 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
92262 Column *pCol = &pTab->aCol[iKey];
92263 if( zKey ){
92264 if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
92265 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
92266 return 1;
92271 return 0;
92275 ** This function is called when inserting, deleting or updating a row of
92276 ** table pTab to generate VDBE code to perform foreign key constraint
92277 ** processing for the operation.
92279 ** For a DELETE operation, parameter regOld is passed the index of the
92280 ** first register in an array of (pTab->nCol+1) registers containing the
92281 ** rowid of the row being deleted, followed by each of the column values
92282 ** of the row being deleted, from left to right. Parameter regNew is passed
92283 ** zero in this case.
92285 ** For an INSERT operation, regOld is passed zero and regNew is passed the
92286 ** first register of an array of (pTab->nCol+1) registers containing the new
92287 ** row data.
92289 ** For an UPDATE operation, this function is called twice. Once before
92290 ** the original record is deleted from the table using the calling convention
92291 ** described for DELETE. Then again after the original record is deleted
92292 ** but before the new record is inserted using the INSERT convention.
92294 SQLITE_PRIVATE void sqlite3FkCheck(
92295 Parse *pParse, /* Parse context */
92296 Table *pTab, /* Row is being deleted from this table */
92297 int regOld, /* Previous row data is stored here */
92298 int regNew, /* New row data is stored here */
92299 int *aChange, /* Array indicating UPDATEd columns (or 0) */
92300 int bChngRowid /* True if rowid is UPDATEd */
92302 sqlite3 *db = pParse->db; /* Database handle */
92303 FKey *pFKey; /* Used to iterate through FKs */
92304 int iDb; /* Index of database containing pTab */
92305 const char *zDb; /* Name of database containing pTab */
92306 int isIgnoreErrors = pParse->disableTriggers;
92308 /* Exactly one of regOld and regNew should be non-zero. */
92309 assert( (regOld==0)!=(regNew==0) );
92311 /* If foreign-keys are disabled, this function is a no-op. */
92312 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
92314 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92315 zDb = db->aDb[iDb].zName;
92317 /* Loop through all the foreign key constraints for which pTab is the
92318 ** child table (the table that the foreign key definition is part of). */
92319 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
92320 Table *pTo; /* Parent table of foreign key pFKey */
92321 Index *pIdx = 0; /* Index on key columns in pTo */
92322 int *aiFree = 0;
92323 int *aiCol;
92324 int iCol;
92325 int i;
92326 int isIgnore = 0;
92328 if( aChange
92329 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
92330 && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
92332 continue;
92335 /* Find the parent table of this foreign key. Also find a unique index
92336 ** on the parent key columns in the parent table. If either of these
92337 ** schema items cannot be located, set an error in pParse and return
92338 ** early. */
92339 if( pParse->disableTriggers ){
92340 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
92341 }else{
92342 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
92344 if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
92345 assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
92346 if( !isIgnoreErrors || db->mallocFailed ) return;
92347 if( pTo==0 ){
92348 /* If isIgnoreErrors is true, then a table is being dropped. In this
92349 ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
92350 ** before actually dropping it in order to check FK constraints.
92351 ** If the parent table of an FK constraint on the current table is
92352 ** missing, behave as if it is empty. i.e. decrement the relevant
92353 ** FK counter for each row of the current table with non-NULL keys.
92355 Vdbe *v = sqlite3GetVdbe(pParse);
92356 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
92357 for(i=0; i<pFKey->nCol; i++){
92358 int iReg = pFKey->aCol[i].iFrom + regOld + 1;
92359 sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
92361 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
92363 continue;
92365 assert( pFKey->nCol==1 || (aiFree && pIdx) );
92367 if( aiFree ){
92368 aiCol = aiFree;
92369 }else{
92370 iCol = pFKey->aCol[0].iFrom;
92371 aiCol = &iCol;
92373 for(i=0; i<pFKey->nCol; i++){
92374 if( aiCol[i]==pTab->iPKey ){
92375 aiCol[i] = -1;
92377 #ifndef SQLITE_OMIT_AUTHORIZATION
92378 /* Request permission to read the parent key columns. If the
92379 ** authorization callback returns SQLITE_IGNORE, behave as if any
92380 ** values read from the parent table are NULL. */
92381 if( db->xAuth ){
92382 int rcauth;
92383 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
92384 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
92385 isIgnore = (rcauth==SQLITE_IGNORE);
92387 #endif
92390 /* Take a shared-cache advisory read-lock on the parent table. Allocate
92391 ** a cursor to use to search the unique index on the parent key columns
92392 ** in the parent table. */
92393 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
92394 pParse->nTab++;
92396 if( regOld!=0 ){
92397 /* A row is being removed from the child table. Search for the parent.
92398 ** If the parent does not exist, removing the child row resolves an
92399 ** outstanding foreign key constraint violation. */
92400 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
92402 if( regNew!=0 ){
92403 /* A row is being added to the child table. If a parent row cannot
92404 ** be found, adding the child row has violated the FK constraint. */
92405 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
92408 sqlite3DbFree(db, aiFree);
92411 /* Loop through all the foreign key constraints that refer to this table.
92412 ** (the "child" constraints) */
92413 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
92414 Index *pIdx = 0; /* Foreign key index for pFKey */
92415 SrcList *pSrc;
92416 int *aiCol = 0;
92418 if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
92419 continue;
92422 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
92423 && !pParse->pToplevel && !pParse->isMultiWrite
92425 assert( regOld==0 && regNew!=0 );
92426 /* Inserting a single row into a parent table cannot cause an immediate
92427 ** foreign key violation. So do nothing in this case. */
92428 continue;
92431 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
92432 if( !isIgnoreErrors || db->mallocFailed ) return;
92433 continue;
92435 assert( aiCol || pFKey->nCol==1 );
92437 /* Create a SrcList structure containing the child table. We need the
92438 ** child table as a SrcList for sqlite3WhereBegin() */
92439 pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
92440 if( pSrc ){
92441 struct SrcList_item *pItem = pSrc->a;
92442 pItem->pTab = pFKey->pFrom;
92443 pItem->zName = pFKey->pFrom->zName;
92444 pItem->pTab->nRef++;
92445 pItem->iCursor = pParse->nTab++;
92447 if( regNew!=0 ){
92448 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
92450 if( regOld!=0 ){
92451 /* If there is a RESTRICT action configured for the current operation
92452 ** on the parent table of this FK, then throw an exception
92453 ** immediately if the FK constraint is violated, even if this is a
92454 ** deferred trigger. That's what RESTRICT means. To defer checking
92455 ** the constraint, the FK should specify NO ACTION (represented
92456 ** using OE_None). NO ACTION is the default. */
92457 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
92459 pItem->zName = 0;
92460 sqlite3SrcListDelete(db, pSrc);
92462 sqlite3DbFree(db, aiCol);
92466 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
92469 ** This function is called before generating code to update or delete a
92470 ** row contained in table pTab.
92472 SQLITE_PRIVATE u32 sqlite3FkOldmask(
92473 Parse *pParse, /* Parse context */
92474 Table *pTab /* Table being modified */
92476 u32 mask = 0;
92477 if( pParse->db->flags&SQLITE_ForeignKeys ){
92478 FKey *p;
92479 int i;
92480 for(p=pTab->pFKey; p; p=p->pNextFrom){
92481 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
92483 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
92484 Index *pIdx = 0;
92485 sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
92486 if( pIdx ){
92487 for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
92491 return mask;
92496 ** This function is called before generating code to update or delete a
92497 ** row contained in table pTab. If the operation is a DELETE, then
92498 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
92499 ** to an array of size N, where N is the number of columns in table pTab.
92500 ** If the i'th column is not modified by the UPDATE, then the corresponding
92501 ** entry in the aChange[] array is set to -1. If the column is modified,
92502 ** the value is 0 or greater. Parameter chngRowid is set to true if the
92503 ** UPDATE statement modifies the rowid fields of the table.
92505 ** If any foreign key processing will be required, this function returns
92506 ** true. If there is no foreign key related processing, this function
92507 ** returns false.
92509 SQLITE_PRIVATE int sqlite3FkRequired(
92510 Parse *pParse, /* Parse context */
92511 Table *pTab, /* Table being modified */
92512 int *aChange, /* Non-NULL for UPDATE operations */
92513 int chngRowid /* True for UPDATE that affects rowid */
92515 if( pParse->db->flags&SQLITE_ForeignKeys ){
92516 if( !aChange ){
92517 /* A DELETE operation. Foreign key processing is required if the
92518 ** table in question is either the child or parent table for any
92519 ** foreign key constraint. */
92520 return (sqlite3FkReferences(pTab) || pTab->pFKey);
92521 }else{
92522 /* This is an UPDATE. Foreign key processing is only required if the
92523 ** operation modifies one or more child or parent key columns. */
92524 FKey *p;
92526 /* Check if any child key columns are being modified. */
92527 for(p=pTab->pFKey; p; p=p->pNextFrom){
92528 if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
92531 /* Check if any parent key columns are being modified. */
92532 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
92533 if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
92537 return 0;
92541 ** This function is called when an UPDATE or DELETE operation is being
92542 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
92543 ** If the current operation is an UPDATE, then the pChanges parameter is
92544 ** passed a pointer to the list of columns being modified. If it is a
92545 ** DELETE, pChanges is passed a NULL pointer.
92547 ** It returns a pointer to a Trigger structure containing a trigger
92548 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
92549 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
92550 ** returned (these actions require no special handling by the triggers
92551 ** sub-system, code for them is created by fkScanChildren()).
92553 ** For example, if pFKey is the foreign key and pTab is table "p" in
92554 ** the following schema:
92556 ** CREATE TABLE p(pk PRIMARY KEY);
92557 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
92559 ** then the returned trigger structure is equivalent to:
92561 ** CREATE TRIGGER ... DELETE ON p BEGIN
92562 ** DELETE FROM c WHERE ck = old.pk;
92563 ** END;
92565 ** The returned pointer is cached as part of the foreign key object. It
92566 ** is eventually freed along with the rest of the foreign key object by
92567 ** sqlite3FkDelete().
92569 static Trigger *fkActionTrigger(
92570 Parse *pParse, /* Parse context */
92571 Table *pTab, /* Table being updated or deleted from */
92572 FKey *pFKey, /* Foreign key to get action for */
92573 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
92575 sqlite3 *db = pParse->db; /* Database handle */
92576 int action; /* One of OE_None, OE_Cascade etc. */
92577 Trigger *pTrigger; /* Trigger definition to return */
92578 int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
92580 action = pFKey->aAction[iAction];
92581 pTrigger = pFKey->apTrigger[iAction];
92583 if( action!=OE_None && !pTrigger ){
92584 u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
92585 char const *zFrom; /* Name of child table */
92586 int nFrom; /* Length in bytes of zFrom */
92587 Index *pIdx = 0; /* Parent key index for this FK */
92588 int *aiCol = 0; /* child table cols -> parent key cols */
92589 TriggerStep *pStep = 0; /* First (only) step of trigger program */
92590 Expr *pWhere = 0; /* WHERE clause of trigger step */
92591 ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
92592 Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
92593 int i; /* Iterator variable */
92594 Expr *pWhen = 0; /* WHEN clause for the trigger */
92596 if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
92597 assert( aiCol || pFKey->nCol==1 );
92599 for(i=0; i<pFKey->nCol; i++){
92600 Token tOld = { "old", 3 }; /* Literal "old" token */
92601 Token tNew = { "new", 3 }; /* Literal "new" token */
92602 Token tFromCol; /* Name of column in child table */
92603 Token tToCol; /* Name of column in parent table */
92604 int iFromCol; /* Idx of column in child table */
92605 Expr *pEq; /* tFromCol = OLD.tToCol */
92607 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
92608 assert( iFromCol>=0 );
92609 tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
92610 tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
92612 tToCol.n = sqlite3Strlen30(tToCol.z);
92613 tFromCol.n = sqlite3Strlen30(tFromCol.z);
92615 /* Create the expression "OLD.zToCol = zFromCol". It is important
92616 ** that the "OLD.zToCol" term is on the LHS of the = operator, so
92617 ** that the affinity and collation sequence associated with the
92618 ** parent table are used for the comparison. */
92619 pEq = sqlite3PExpr(pParse, TK_EQ,
92620 sqlite3PExpr(pParse, TK_DOT,
92621 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
92622 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
92623 , 0),
92624 sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
92625 , 0);
92626 pWhere = sqlite3ExprAnd(db, pWhere, pEq);
92628 /* For ON UPDATE, construct the next term of the WHEN clause.
92629 ** The final WHEN clause will be like this:
92631 ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
92633 if( pChanges ){
92634 pEq = sqlite3PExpr(pParse, TK_IS,
92635 sqlite3PExpr(pParse, TK_DOT,
92636 sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
92637 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
92639 sqlite3PExpr(pParse, TK_DOT,
92640 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
92641 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
92644 pWhen = sqlite3ExprAnd(db, pWhen, pEq);
92647 if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
92648 Expr *pNew;
92649 if( action==OE_Cascade ){
92650 pNew = sqlite3PExpr(pParse, TK_DOT,
92651 sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
92652 sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
92653 , 0);
92654 }else if( action==OE_SetDflt ){
92655 Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
92656 if( pDflt ){
92657 pNew = sqlite3ExprDup(db, pDflt, 0);
92658 }else{
92659 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
92661 }else{
92662 pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
92664 pList = sqlite3ExprListAppend(pParse, pList, pNew);
92665 sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
92668 sqlite3DbFree(db, aiCol);
92670 zFrom = pFKey->pFrom->zName;
92671 nFrom = sqlite3Strlen30(zFrom);
92673 if( action==OE_Restrict ){
92674 Token tFrom;
92675 Expr *pRaise;
92677 tFrom.z = zFrom;
92678 tFrom.n = nFrom;
92679 pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
92680 if( pRaise ){
92681 pRaise->affinity = OE_Abort;
92683 pSelect = sqlite3SelectNew(pParse,
92684 sqlite3ExprListAppend(pParse, 0, pRaise),
92685 sqlite3SrcListAppend(db, 0, &tFrom, 0),
92686 pWhere,
92687 0, 0, 0, 0, 0, 0
92689 pWhere = 0;
92692 /* Disable lookaside memory allocation */
92693 enableLookaside = db->lookaside.bEnabled;
92694 db->lookaside.bEnabled = 0;
92696 pTrigger = (Trigger *)sqlite3DbMallocZero(db,
92697 sizeof(Trigger) + /* struct Trigger */
92698 sizeof(TriggerStep) + /* Single step in trigger program */
92699 nFrom + 1 /* Space for pStep->target.z */
92701 if( pTrigger ){
92702 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
92703 pStep->target.z = (char *)&pStep[1];
92704 pStep->target.n = nFrom;
92705 memcpy((char *)pStep->target.z, zFrom, nFrom);
92707 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
92708 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
92709 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
92710 if( pWhen ){
92711 pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
92712 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
92716 /* Re-enable the lookaside buffer, if it was disabled earlier. */
92717 db->lookaside.bEnabled = enableLookaside;
92719 sqlite3ExprDelete(db, pWhere);
92720 sqlite3ExprDelete(db, pWhen);
92721 sqlite3ExprListDelete(db, pList);
92722 sqlite3SelectDelete(db, pSelect);
92723 if( db->mallocFailed==1 ){
92724 fkTriggerDelete(db, pTrigger);
92725 return 0;
92727 assert( pStep!=0 );
92729 switch( action ){
92730 case OE_Restrict:
92731 pStep->op = TK_SELECT;
92732 break;
92733 case OE_Cascade:
92734 if( !pChanges ){
92735 pStep->op = TK_DELETE;
92736 break;
92738 default:
92739 pStep->op = TK_UPDATE;
92741 pStep->pTrig = pTrigger;
92742 pTrigger->pSchema = pTab->pSchema;
92743 pTrigger->pTabSchema = pTab->pSchema;
92744 pFKey->apTrigger[iAction] = pTrigger;
92745 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
92748 return pTrigger;
92752 ** This function is called when deleting or updating a row to implement
92753 ** any required CASCADE, SET NULL or SET DEFAULT actions.
92755 SQLITE_PRIVATE void sqlite3FkActions(
92756 Parse *pParse, /* Parse context */
92757 Table *pTab, /* Table being updated or deleted from */
92758 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
92759 int regOld, /* Address of array containing old row */
92760 int *aChange, /* Array indicating UPDATEd columns (or 0) */
92761 int bChngRowid /* True if rowid is UPDATEd */
92763 /* If foreign-key support is enabled, iterate through all FKs that
92764 ** refer to table pTab. If there is an action associated with the FK
92765 ** for this operation (either update or delete), invoke the associated
92766 ** trigger sub-program. */
92767 if( pParse->db->flags&SQLITE_ForeignKeys ){
92768 FKey *pFKey; /* Iterator variable */
92769 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
92770 if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
92771 Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
92772 if( pAct ){
92773 sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
92780 #endif /* ifndef SQLITE_OMIT_TRIGGER */
92783 ** Free all memory associated with foreign key definitions attached to
92784 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
92785 ** hash table.
92787 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
92788 FKey *pFKey; /* Iterator variable */
92789 FKey *pNext; /* Copy of pFKey->pNextFrom */
92791 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
92792 for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
92794 /* Remove the FK from the fkeyHash hash table. */
92795 if( !db || db->pnBytesFreed==0 ){
92796 if( pFKey->pPrevTo ){
92797 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
92798 }else{
92799 void *p = (void *)pFKey->pNextTo;
92800 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
92801 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
92803 if( pFKey->pNextTo ){
92804 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
92808 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
92809 ** classified as either immediate or deferred.
92811 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
92813 /* Delete any triggers created to implement actions for this FK. */
92814 #ifndef SQLITE_OMIT_TRIGGER
92815 fkTriggerDelete(db, pFKey->apTrigger[0]);
92816 fkTriggerDelete(db, pFKey->apTrigger[1]);
92817 #endif
92819 pNext = pFKey->pNextFrom;
92820 sqlite3DbFree(db, pFKey);
92823 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
92825 /************** End of fkey.c ************************************************/
92826 /************** Begin file insert.c ******************************************/
92828 ** 2001 September 15
92830 ** The author disclaims copyright to this source code. In place of
92831 ** a legal notice, here is a blessing:
92833 ** May you do good and not evil.
92834 ** May you find forgiveness for yourself and forgive others.
92835 ** May you share freely, never taking more than you give.
92837 *************************************************************************
92838 ** This file contains C code routines that are called by the parser
92839 ** to handle INSERT statements in SQLite.
92843 ** Generate code that will
92845 ** (1) acquire a lock for table pTab then
92846 ** (2) open pTab as cursor iCur.
92848 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
92849 ** for that table that is actually opened.
92851 SQLITE_PRIVATE void sqlite3OpenTable(
92852 Parse *pParse, /* Generate code into this VDBE */
92853 int iCur, /* The cursor number of the table */
92854 int iDb, /* The database index in sqlite3.aDb[] */
92855 Table *pTab, /* The table to be opened */
92856 int opcode /* OP_OpenRead or OP_OpenWrite */
92858 Vdbe *v;
92859 assert( !IsVirtual(pTab) );
92860 v = sqlite3GetVdbe(pParse);
92861 assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
92862 sqlite3TableLock(pParse, iDb, pTab->tnum,
92863 (opcode==OP_OpenWrite)?1:0, pTab->zName);
92864 if( HasRowid(pTab) ){
92865 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
92866 VdbeComment((v, "%s", pTab->zName));
92867 }else{
92868 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
92869 assert( pPk!=0 );
92870 assert( pPk->tnum=pTab->tnum );
92871 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
92872 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
92873 VdbeComment((v, "%s", pTab->zName));
92878 ** Return a pointer to the column affinity string associated with index
92879 ** pIdx. A column affinity string has one character for each column in
92880 ** the table, according to the affinity of the column:
92882 ** Character Column affinity
92883 ** ------------------------------
92884 ** 'a' TEXT
92885 ** 'b' NONE
92886 ** 'c' NUMERIC
92887 ** 'd' INTEGER
92888 ** 'e' REAL
92890 ** An extra 'd' is appended to the end of the string to cover the
92891 ** rowid that appears as the last column in every index.
92893 ** Memory for the buffer containing the column index affinity string
92894 ** is managed along with the rest of the Index structure. It will be
92895 ** released when sqlite3DeleteIndex() is called.
92897 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
92898 if( !pIdx->zColAff ){
92899 /* The first time a column affinity string for a particular index is
92900 ** required, it is allocated and populated here. It is then stored as
92901 ** a member of the Index structure for subsequent use.
92903 ** The column affinity string will eventually be deleted by
92904 ** sqliteDeleteIndex() when the Index structure itself is cleaned
92905 ** up.
92907 int n;
92908 Table *pTab = pIdx->pTable;
92909 sqlite3 *db = sqlite3VdbeDb(v);
92910 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
92911 if( !pIdx->zColAff ){
92912 db->mallocFailed = 1;
92913 return 0;
92915 for(n=0; n<pIdx->nColumn; n++){
92916 i16 x = pIdx->aiColumn[n];
92917 pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
92919 pIdx->zColAff[n] = 0;
92922 return pIdx->zColAff;
92926 ** Set P4 of the most recently inserted opcode to a column affinity
92927 ** string for table pTab. A column affinity string has one character
92928 ** for each column indexed by the index, according to the affinity of the
92929 ** column:
92931 ** Character Column affinity
92932 ** ------------------------------
92933 ** 'a' TEXT
92934 ** 'b' NONE
92935 ** 'c' NUMERIC
92936 ** 'd' INTEGER
92937 ** 'e' REAL
92939 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
92940 /* The first time a column affinity string for a particular table
92941 ** is required, it is allocated and populated here. It is then
92942 ** stored as a member of the Table structure for subsequent use.
92944 ** The column affinity string will eventually be deleted by
92945 ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
92947 if( !pTab->zColAff ){
92948 char *zColAff;
92949 int i;
92950 sqlite3 *db = sqlite3VdbeDb(v);
92952 zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
92953 if( !zColAff ){
92954 db->mallocFailed = 1;
92955 return;
92958 for(i=0; i<pTab->nCol; i++){
92959 zColAff[i] = pTab->aCol[i].affinity;
92961 zColAff[pTab->nCol] = '\0';
92963 pTab->zColAff = zColAff;
92966 sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
92970 ** Return non-zero if the table pTab in database iDb or any of its indices
92971 ** have been opened at any point in the VDBE program beginning at location
92972 ** iStartAddr throught the end of the program. This is used to see if
92973 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
92974 ** run without using temporary table for the results of the SELECT.
92976 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
92977 Vdbe *v = sqlite3GetVdbe(p);
92978 int i;
92979 int iEnd = sqlite3VdbeCurrentAddr(v);
92980 #ifndef SQLITE_OMIT_VIRTUALTABLE
92981 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
92982 #endif
92984 for(i=iStartAddr; i<iEnd; i++){
92985 VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
92986 assert( pOp!=0 );
92987 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
92988 Index *pIndex;
92989 int tnum = pOp->p2;
92990 if( tnum==pTab->tnum ){
92991 return 1;
92993 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
92994 if( tnum==pIndex->tnum ){
92995 return 1;
92999 #ifndef SQLITE_OMIT_VIRTUALTABLE
93000 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
93001 assert( pOp->p4.pVtab!=0 );
93002 assert( pOp->p4type==P4_VTAB );
93003 return 1;
93005 #endif
93007 return 0;
93010 #ifndef SQLITE_OMIT_AUTOINCREMENT
93012 ** Locate or create an AutoincInfo structure associated with table pTab
93013 ** which is in database iDb. Return the register number for the register
93014 ** that holds the maximum rowid.
93016 ** There is at most one AutoincInfo structure per table even if the
93017 ** same table is autoincremented multiple times due to inserts within
93018 ** triggers. A new AutoincInfo structure is created if this is the
93019 ** first use of table pTab. On 2nd and subsequent uses, the original
93020 ** AutoincInfo structure is used.
93022 ** Three memory locations are allocated:
93024 ** (1) Register to hold the name of the pTab table.
93025 ** (2) Register to hold the maximum ROWID of pTab.
93026 ** (3) Register to hold the rowid in sqlite_sequence of pTab
93028 ** The 2nd register is the one that is returned. That is all the
93029 ** insert routine needs to know about.
93031 static int autoIncBegin(
93032 Parse *pParse, /* Parsing context */
93033 int iDb, /* Index of the database holding pTab */
93034 Table *pTab /* The table we are writing to */
93036 int memId = 0; /* Register holding maximum rowid */
93037 if( pTab->tabFlags & TF_Autoincrement ){
93038 Parse *pToplevel = sqlite3ParseToplevel(pParse);
93039 AutoincInfo *pInfo;
93041 pInfo = pToplevel->pAinc;
93042 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
93043 if( pInfo==0 ){
93044 pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
93045 if( pInfo==0 ) return 0;
93046 pInfo->pNext = pToplevel->pAinc;
93047 pToplevel->pAinc = pInfo;
93048 pInfo->pTab = pTab;
93049 pInfo->iDb = iDb;
93050 pToplevel->nMem++; /* Register to hold name of table */
93051 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
93052 pToplevel->nMem++; /* Rowid in sqlite_sequence */
93054 memId = pInfo->regCtr;
93056 return memId;
93060 ** This routine generates code that will initialize all of the
93061 ** register used by the autoincrement tracker.
93063 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
93064 AutoincInfo *p; /* Information about an AUTOINCREMENT */
93065 sqlite3 *db = pParse->db; /* The database connection */
93066 Db *pDb; /* Database only autoinc table */
93067 int memId; /* Register holding max rowid */
93068 int addr; /* A VDBE address */
93069 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
93071 /* This routine is never called during trigger-generation. It is
93072 ** only called from the top-level */
93073 assert( pParse->pTriggerTab==0 );
93074 assert( pParse==sqlite3ParseToplevel(pParse) );
93076 assert( v ); /* We failed long ago if this is not so */
93077 for(p = pParse->pAinc; p; p = p->pNext){
93078 pDb = &db->aDb[p->iDb];
93079 memId = p->regCtr;
93080 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
93081 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
93082 sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
93083 addr = sqlite3VdbeCurrentAddr(v);
93084 sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
93085 sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
93086 sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
93087 sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
93088 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
93089 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
93090 sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
93091 sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
93092 sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
93093 sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
93094 sqlite3VdbeAddOp0(v, OP_Close);
93099 ** Update the maximum rowid for an autoincrement calculation.
93101 ** This routine should be called when the top of the stack holds a
93102 ** new rowid that is about to be inserted. If that new rowid is
93103 ** larger than the maximum rowid in the memId memory cell, then the
93104 ** memory cell is updated. The stack is unchanged.
93106 static void autoIncStep(Parse *pParse, int memId, int regRowid){
93107 if( memId>0 ){
93108 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
93113 ** This routine generates the code needed to write autoincrement
93114 ** maximum rowid values back into the sqlite_sequence register.
93115 ** Every statement that might do an INSERT into an autoincrement
93116 ** table (either directly or through triggers) needs to call this
93117 ** routine just before the "exit" code.
93119 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
93120 AutoincInfo *p;
93121 Vdbe *v = pParse->pVdbe;
93122 sqlite3 *db = pParse->db;
93124 assert( v );
93125 for(p = pParse->pAinc; p; p = p->pNext){
93126 Db *pDb = &db->aDb[p->iDb];
93127 int j1, j2, j3, j4, j5;
93128 int iRec;
93129 int memId = p->regCtr;
93131 iRec = sqlite3GetTempReg(pParse);
93132 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
93133 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
93134 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
93135 j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
93136 j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
93137 j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
93138 sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
93139 sqlite3VdbeJumpHere(v, j2);
93140 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
93141 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
93142 sqlite3VdbeJumpHere(v, j4);
93143 sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
93144 sqlite3VdbeJumpHere(v, j1);
93145 sqlite3VdbeJumpHere(v, j5);
93146 sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
93147 sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
93148 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
93149 sqlite3VdbeAddOp0(v, OP_Close);
93150 sqlite3ReleaseTempReg(pParse, iRec);
93153 #else
93155 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
93156 ** above are all no-ops
93158 # define autoIncBegin(A,B,C) (0)
93159 # define autoIncStep(A,B,C)
93160 #endif /* SQLITE_OMIT_AUTOINCREMENT */
93164 ** Generate code for a co-routine that will evaluate a subquery one
93165 ** row at a time.
93167 ** The pSelect parameter is the subquery that the co-routine will evaluation.
93168 ** Information about the location of co-routine and the registers it will use
93169 ** is returned by filling in the pDest object.
93171 ** Registers are allocated as follows:
93173 ** pDest->iSDParm The register holding the next entry-point of the
93174 ** co-routine. Run the co-routine to its next breakpoint
93175 ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
93177 ** pDest->iSDParm+1 The register holding the "completed" flag for the
93178 ** co-routine. This register is 0 if the previous Yield
93179 ** generated a new result row, or 1 if the subquery
93180 ** has completed. If the Yield is called again
93181 ** after this register becomes 1, then the VDBE will
93182 ** halt with an SQLITE_INTERNAL error.
93184 ** pDest->iSdst First result register.
93186 ** pDest->nSdst Number of result registers.
93188 ** This routine handles all of the register allocation and fills in the
93189 ** pDest structure appropriately.
93191 ** Here is a schematic of the generated code assuming that X is the
93192 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
93193 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
93194 ** registers that hold the result set, reg[pDest->iSdst] through
93195 ** reg[pDest->iSdst+pDest->nSdst-1]:
93197 ** X <- A
93198 ** EOF <- 0
93199 ** goto B
93200 ** A: setup for the SELECT
93201 ** loop rows in the SELECT
93202 ** load results into registers R..S
93203 ** yield X
93204 ** end loop
93205 ** cleanup after the SELECT
93206 ** EOF <- 1
93207 ** yield X
93208 ** halt-error
93209 ** B:
93211 ** To use this subroutine, the caller generates code as follows:
93213 ** [ Co-routine generated by this subroutine, shown above ]
93214 ** S: yield X
93215 ** if EOF goto E
93216 ** if skip this row, goto C
93217 ** if terminate loop, goto E
93218 ** deal with this row
93219 ** C: goto S
93220 ** E:
93222 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
93223 int regYield; /* Register holding co-routine entry-point */
93224 int regEof; /* Register holding co-routine completion flag */
93225 int addrTop; /* Top of the co-routine */
93226 int j1; /* Jump instruction */
93227 int rc; /* Result code */
93228 Vdbe *v; /* VDBE under construction */
93230 regYield = ++pParse->nMem;
93231 regEof = ++pParse->nMem;
93232 v = sqlite3GetVdbe(pParse);
93233 addrTop = sqlite3VdbeCurrentAddr(v);
93234 sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
93235 VdbeComment((v, "Co-routine entry point"));
93236 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
93237 VdbeComment((v, "Co-routine completion flag"));
93238 sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
93239 j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
93240 rc = sqlite3Select(pParse, pSelect, pDest);
93241 assert( pParse->nErr==0 || rc );
93242 if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
93243 if( rc ) return rc;
93244 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
93245 sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
93246 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
93247 VdbeComment((v, "End of coroutine"));
93248 sqlite3VdbeJumpHere(v, j1); /* label B: */
93249 return rc;
93254 /* Forward declaration */
93255 static int xferOptimization(
93256 Parse *pParse, /* Parser context */
93257 Table *pDest, /* The table we are inserting into */
93258 Select *pSelect, /* A SELECT statement to use as the data source */
93259 int onError, /* How to handle constraint errors */
93260 int iDbDest /* The database of pDest */
93264 ** This routine is called to handle SQL of the following forms:
93266 ** insert into TABLE (IDLIST) values(EXPRLIST)
93267 ** insert into TABLE (IDLIST) select
93269 ** The IDLIST following the table name is always optional. If omitted,
93270 ** then a list of all columns for the table is substituted. The IDLIST
93271 ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
93273 ** The pList parameter holds EXPRLIST in the first form of the INSERT
93274 ** statement above, and pSelect is NULL. For the second form, pList is
93275 ** NULL and pSelect is a pointer to the select statement used to generate
93276 ** data for the insert.
93278 ** The code generated follows one of four templates. For a simple
93279 ** insert with data coming from a VALUES clause, the code executes
93280 ** once straight down through. Pseudo-code follows (we call this
93281 ** the "1st template"):
93283 ** open write cursor to <table> and its indices
93284 ** put VALUES clause expressions into registers
93285 ** write the resulting record into <table>
93286 ** cleanup
93288 ** The three remaining templates assume the statement is of the form
93290 ** INSERT INTO <table> SELECT ...
93292 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
93293 ** in other words if the SELECT pulls all columns from a single table
93294 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
93295 ** if <table2> and <table1> are distinct tables but have identical
93296 ** schemas, including all the same indices, then a special optimization
93297 ** is invoked that copies raw records from <table2> over to <table1>.
93298 ** See the xferOptimization() function for the implementation of this
93299 ** template. This is the 2nd template.
93301 ** open a write cursor to <table>
93302 ** open read cursor on <table2>
93303 ** transfer all records in <table2> over to <table>
93304 ** close cursors
93305 ** foreach index on <table>
93306 ** open a write cursor on the <table> index
93307 ** open a read cursor on the corresponding <table2> index
93308 ** transfer all records from the read to the write cursors
93309 ** close cursors
93310 ** end foreach
93312 ** The 3rd template is for when the second template does not apply
93313 ** and the SELECT clause does not read from <table> at any time.
93314 ** The generated code follows this template:
93316 ** EOF <- 0
93317 ** X <- A
93318 ** goto B
93319 ** A: setup for the SELECT
93320 ** loop over the rows in the SELECT
93321 ** load values into registers R..R+n
93322 ** yield X
93323 ** end loop
93324 ** cleanup after the SELECT
93325 ** EOF <- 1
93326 ** yield X
93327 ** goto A
93328 ** B: open write cursor to <table> and its indices
93329 ** C: yield X
93330 ** if EOF goto D
93331 ** insert the select result into <table> from R..R+n
93332 ** goto C
93333 ** D: cleanup
93335 ** The 4th template is used if the insert statement takes its
93336 ** values from a SELECT but the data is being inserted into a table
93337 ** that is also read as part of the SELECT. In the third form,
93338 ** we have to use a intermediate table to store the results of
93339 ** the select. The template is like this:
93341 ** EOF <- 0
93342 ** X <- A
93343 ** goto B
93344 ** A: setup for the SELECT
93345 ** loop over the tables in the SELECT
93346 ** load value into register R..R+n
93347 ** yield X
93348 ** end loop
93349 ** cleanup after the SELECT
93350 ** EOF <- 1
93351 ** yield X
93352 ** halt-error
93353 ** B: open temp table
93354 ** L: yield X
93355 ** if EOF goto M
93356 ** insert row from R..R+n into temp table
93357 ** goto L
93358 ** M: open write cursor to <table> and its indices
93359 ** rewind temp table
93360 ** C: loop over rows of intermediate table
93361 ** transfer values form intermediate table into <table>
93362 ** end loop
93363 ** D: cleanup
93365 SQLITE_PRIVATE void sqlite3Insert(
93366 Parse *pParse, /* Parser context */
93367 SrcList *pTabList, /* Name of table into which we are inserting */
93368 Select *pSelect, /* A SELECT statement to use as the data source */
93369 IdList *pColumn, /* Column names corresponding to IDLIST. */
93370 int onError /* How to handle constraint errors */
93372 sqlite3 *db; /* The main database structure */
93373 Table *pTab; /* The table to insert into. aka TABLE */
93374 char *zTab; /* Name of the table into which we are inserting */
93375 const char *zDb; /* Name of the database holding this table */
93376 int i, j, idx; /* Loop counters */
93377 Vdbe *v; /* Generate code into this virtual machine */
93378 Index *pIdx; /* For looping over indices of the table */
93379 int nColumn; /* Number of columns in the data */
93380 int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
93381 int iDataCur = 0; /* VDBE cursor that is the main data repository */
93382 int iIdxCur = 0; /* First index cursor */
93383 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
93384 int endOfLoop; /* Label for the end of the insertion loop */
93385 int useTempTable = 0; /* Store SELECT results in intermediate table */
93386 int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
93387 int addrInsTop = 0; /* Jump to label "D" */
93388 int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
93389 int addrSelect = 0; /* Address of coroutine that implements the SELECT */
93390 SelectDest dest; /* Destination for SELECT on rhs of INSERT */
93391 int iDb; /* Index of database holding TABLE */
93392 Db *pDb; /* The database containing table being inserted into */
93393 int appendFlag = 0; /* True if the insert is likely to be an append */
93394 int withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
93395 ExprList *pList = 0; /* List of VALUES() to be inserted */
93397 /* Register allocations */
93398 int regFromSelect = 0;/* Base register for data coming from SELECT */
93399 int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
93400 int regRowCount = 0; /* Memory cell used for the row counter */
93401 int regIns; /* Block of regs holding rowid+data being inserted */
93402 int regRowid; /* registers holding insert rowid */
93403 int regData; /* register holding first column to insert */
93404 int regEof = 0; /* Register recording end of SELECT data */
93405 int *aRegIdx = 0; /* One register allocated to each index */
93407 #ifndef SQLITE_OMIT_TRIGGER
93408 int isView; /* True if attempting to insert into a view */
93409 Trigger *pTrigger; /* List of triggers on pTab, if required */
93410 int tmask; /* Mask of trigger times */
93411 #endif
93413 db = pParse->db;
93414 memset(&dest, 0, sizeof(dest));
93415 if( pParse->nErr || db->mallocFailed ){
93416 goto insert_cleanup;
93419 /* If the Select object is really just a simple VALUES() list with a
93420 ** single row values (the common case) then keep that one row of values
93421 ** and go ahead and discard the Select object
93423 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
93424 pList = pSelect->pEList;
93425 pSelect->pEList = 0;
93426 sqlite3SelectDelete(db, pSelect);
93427 pSelect = 0;
93430 /* Locate the table into which we will be inserting new information.
93432 assert( pTabList->nSrc==1 );
93433 zTab = pTabList->a[0].zName;
93434 if( NEVER(zTab==0) ) goto insert_cleanup;
93435 pTab = sqlite3SrcListLookup(pParse, pTabList);
93436 if( pTab==0 ){
93437 goto insert_cleanup;
93439 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93440 assert( iDb<db->nDb );
93441 pDb = &db->aDb[iDb];
93442 zDb = pDb->zName;
93443 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
93444 goto insert_cleanup;
93446 withoutRowid = !HasRowid(pTab);
93448 /* Figure out if we have any triggers and if the table being
93449 ** inserted into is a view
93451 #ifndef SQLITE_OMIT_TRIGGER
93452 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
93453 isView = pTab->pSelect!=0;
93454 #else
93455 # define pTrigger 0
93456 # define tmask 0
93457 # define isView 0
93458 #endif
93459 #ifdef SQLITE_OMIT_VIEW
93460 # undef isView
93461 # define isView 0
93462 #endif
93463 assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
93465 /* If pTab is really a view, make sure it has been initialized.
93466 ** ViewGetColumnNames() is a no-op if pTab is not a view.
93468 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93469 goto insert_cleanup;
93472 /* Cannot insert into a read-only table.
93474 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
93475 goto insert_cleanup;
93478 /* Allocate a VDBE
93480 v = sqlite3GetVdbe(pParse);
93481 if( v==0 ) goto insert_cleanup;
93482 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
93483 sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
93485 #ifndef SQLITE_OMIT_XFER_OPT
93486 /* If the statement is of the form
93488 ** INSERT INTO <table1> SELECT * FROM <table2>;
93490 ** Then special optimizations can be applied that make the transfer
93491 ** very fast and which reduce fragmentation of indices.
93493 ** This is the 2nd template.
93495 if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
93496 assert( !pTrigger );
93497 assert( pList==0 );
93498 goto insert_end;
93500 #endif /* SQLITE_OMIT_XFER_OPT */
93502 /* If this is an AUTOINCREMENT table, look up the sequence number in the
93503 ** sqlite_sequence table and store it in memory cell regAutoinc.
93505 regAutoinc = autoIncBegin(pParse, iDb, pTab);
93507 /* Figure out how many columns of data are supplied. If the data
93508 ** is coming from a SELECT statement, then generate a co-routine that
93509 ** produces a single row of the SELECT on each invocation. The
93510 ** co-routine is the common header to the 3rd and 4th templates.
93512 if( pSelect ){
93513 /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */
93514 int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
93515 if( rc ) goto insert_cleanup;
93517 regEof = dest.iSDParm + 1;
93518 regFromSelect = dest.iSdst;
93519 assert( pSelect->pEList );
93520 nColumn = pSelect->pEList->nExpr;
93521 assert( dest.nSdst==nColumn );
93523 /* Set useTempTable to TRUE if the result of the SELECT statement
93524 ** should be written into a temporary table (template 4). Set to
93525 ** FALSE if each output row of the SELECT can be written directly into
93526 ** the destination table (template 3).
93528 ** A temp table must be used if the table being updated is also one
93529 ** of the tables being read by the SELECT statement. Also use a
93530 ** temp table in the case of row triggers.
93532 if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
93533 useTempTable = 1;
93536 if( useTempTable ){
93537 /* Invoke the coroutine to extract information from the SELECT
93538 ** and add it to a transient table srcTab. The code generated
93539 ** here is from the 4th template:
93541 ** B: open temp table
93542 ** L: yield X
93543 ** if EOF goto M
93544 ** insert row from R..R+n into temp table
93545 ** goto L
93546 ** M: ...
93548 int regRec; /* Register to hold packed record */
93549 int regTempRowid; /* Register to hold temp table ROWID */
93550 int addrTop; /* Label "L" */
93551 int addrIf; /* Address of jump to M */
93553 srcTab = pParse->nTab++;
93554 regRec = sqlite3GetTempReg(pParse);
93555 regTempRowid = sqlite3GetTempReg(pParse);
93556 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
93557 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
93558 addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
93559 sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
93560 sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
93561 sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
93562 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
93563 sqlite3VdbeJumpHere(v, addrIf);
93564 sqlite3ReleaseTempReg(pParse, regRec);
93565 sqlite3ReleaseTempReg(pParse, regTempRowid);
93567 }else{
93568 /* This is the case if the data for the INSERT is coming from a VALUES
93569 ** clause
93571 NameContext sNC;
93572 memset(&sNC, 0, sizeof(sNC));
93573 sNC.pParse = pParse;
93574 srcTab = -1;
93575 assert( useTempTable==0 );
93576 nColumn = pList ? pList->nExpr : 0;
93577 for(i=0; i<nColumn; i++){
93578 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
93579 goto insert_cleanup;
93584 /* Make sure the number of columns in the source data matches the number
93585 ** of columns to be inserted into the table.
93587 if( IsVirtual(pTab) ){
93588 for(i=0; i<pTab->nCol; i++){
93589 nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
93592 if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
93593 sqlite3ErrorMsg(pParse,
93594 "table %S has %d columns but %d values were supplied",
93595 pTabList, 0, pTab->nCol-nHidden, nColumn);
93596 goto insert_cleanup;
93598 if( pColumn!=0 && nColumn!=pColumn->nId ){
93599 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
93600 goto insert_cleanup;
93603 /* If the INSERT statement included an IDLIST term, then make sure
93604 ** all elements of the IDLIST really are columns of the table and
93605 ** remember the column indices.
93607 ** If the table has an INTEGER PRIMARY KEY column and that column
93608 ** is named in the IDLIST, then record in the ipkColumn variable
93609 ** the index into IDLIST of the primary key column. ipkColumn is
93610 ** the index of the primary key as it appears in IDLIST, not as
93611 ** is appears in the original table. (The index of the INTEGER
93612 ** PRIMARY KEY in the original table is pTab->iPKey.)
93614 if( pColumn ){
93615 for(i=0; i<pColumn->nId; i++){
93616 pColumn->a[i].idx = -1;
93618 for(i=0; i<pColumn->nId; i++){
93619 for(j=0; j<pTab->nCol; j++){
93620 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
93621 pColumn->a[i].idx = j;
93622 if( j==pTab->iPKey ){
93623 ipkColumn = i; assert( !withoutRowid );
93625 break;
93628 if( j>=pTab->nCol ){
93629 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
93630 ipkColumn = i;
93631 }else{
93632 sqlite3ErrorMsg(pParse, "table %S has no column named %s",
93633 pTabList, 0, pColumn->a[i].zName);
93634 pParse->checkSchema = 1;
93635 goto insert_cleanup;
93641 /* If there is no IDLIST term but the table has an integer primary
93642 ** key, the set the ipkColumn variable to the integer primary key
93643 ** column index in the original table definition.
93645 if( pColumn==0 && nColumn>0 ){
93646 ipkColumn = pTab->iPKey;
93649 /* Initialize the count of rows to be inserted
93651 if( db->flags & SQLITE_CountRows ){
93652 regRowCount = ++pParse->nMem;
93653 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
93656 /* If this is not a view, open the table and and all indices */
93657 if( !isView ){
93658 int nIdx;
93659 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
93660 &iDataCur, &iIdxCur);
93661 aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
93662 if( aRegIdx==0 ){
93663 goto insert_cleanup;
93665 for(i=0; i<nIdx; i++){
93666 aRegIdx[i] = ++pParse->nMem;
93670 /* This is the top of the main insertion loop */
93671 if( useTempTable ){
93672 /* This block codes the top of loop only. The complete loop is the
93673 ** following pseudocode (template 4):
93675 ** rewind temp table
93676 ** C: loop over rows of intermediate table
93677 ** transfer values form intermediate table into <table>
93678 ** end loop
93679 ** D: ...
93681 addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
93682 addrCont = sqlite3VdbeCurrentAddr(v);
93683 }else if( pSelect ){
93684 /* This block codes the top of loop only. The complete loop is the
93685 ** following pseudocode (template 3):
93687 ** C: yield X
93688 ** if EOF goto D
93689 ** insert the select result into <table> from R..R+n
93690 ** goto C
93691 ** D: ...
93693 addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
93694 addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
93697 /* Allocate registers for holding the rowid of the new row,
93698 ** the content of the new row, and the assemblied row record.
93700 regRowid = regIns = pParse->nMem+1;
93701 pParse->nMem += pTab->nCol + 1;
93702 if( IsVirtual(pTab) ){
93703 regRowid++;
93704 pParse->nMem++;
93706 regData = regRowid+1;
93708 /* Run the BEFORE and INSTEAD OF triggers, if there are any
93710 endOfLoop = sqlite3VdbeMakeLabel(v);
93711 if( tmask & TRIGGER_BEFORE ){
93712 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
93714 /* build the NEW.* reference row. Note that if there is an INTEGER
93715 ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
93716 ** translated into a unique ID for the row. But on a BEFORE trigger,
93717 ** we do not know what the unique ID will be (because the insert has
93718 ** not happened yet) so we substitute a rowid of -1
93720 if( ipkColumn<0 ){
93721 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
93722 }else{
93723 int j1;
93724 assert( !withoutRowid );
93725 if( useTempTable ){
93726 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
93727 }else{
93728 assert( pSelect==0 ); /* Otherwise useTempTable is true */
93729 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
93731 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
93732 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
93733 sqlite3VdbeJumpHere(v, j1);
93734 sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
93737 /* Cannot have triggers on a virtual table. If it were possible,
93738 ** this block would have to account for hidden column.
93740 assert( !IsVirtual(pTab) );
93742 /* Create the new column data
93744 for(i=0; i<pTab->nCol; i++){
93745 if( pColumn==0 ){
93746 j = i;
93747 }else{
93748 for(j=0; j<pColumn->nId; j++){
93749 if( pColumn->a[j].idx==i ) break;
93752 if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
93753 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
93754 }else if( useTempTable ){
93755 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
93756 }else{
93757 assert( pSelect==0 ); /* Otherwise useTempTable is true */
93758 sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
93762 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
93763 ** do not attempt any conversions before assembling the record.
93764 ** If this is a real table, attempt conversions as required by the
93765 ** table column affinities.
93767 if( !isView ){
93768 sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
93769 sqlite3TableAffinityStr(v, pTab);
93772 /* Fire BEFORE or INSTEAD OF triggers */
93773 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
93774 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
93776 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
93779 /* Compute the content of the next row to insert into a range of
93780 ** registers beginning at regIns.
93782 if( !isView ){
93783 if( IsVirtual(pTab) ){
93784 /* The row that the VUpdate opcode will delete: none */
93785 sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
93787 if( ipkColumn>=0 ){
93788 if( useTempTable ){
93789 sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
93790 }else if( pSelect ){
93791 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid);
93792 }else{
93793 VdbeOp *pOp;
93794 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
93795 pOp = sqlite3VdbeGetOp(v, -1);
93796 if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
93797 appendFlag = 1;
93798 pOp->opcode = OP_NewRowid;
93799 pOp->p1 = iDataCur;
93800 pOp->p2 = regRowid;
93801 pOp->p3 = regAutoinc;
93804 /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
93805 ** to generate a unique primary key value.
93807 if( !appendFlag ){
93808 int j1;
93809 if( !IsVirtual(pTab) ){
93810 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
93811 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
93812 sqlite3VdbeJumpHere(v, j1);
93813 }else{
93814 j1 = sqlite3VdbeCurrentAddr(v);
93815 sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
93817 sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
93819 }else if( IsVirtual(pTab) || withoutRowid ){
93820 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
93821 }else{
93822 sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
93823 appendFlag = 1;
93825 autoIncStep(pParse, regAutoinc, regRowid);
93827 /* Compute data for all columns of the new entry, beginning
93828 ** with the first column.
93830 nHidden = 0;
93831 for(i=0; i<pTab->nCol; i++){
93832 int iRegStore = regRowid+1+i;
93833 if( i==pTab->iPKey ){
93834 /* The value of the INTEGER PRIMARY KEY column is always a NULL.
93835 ** Whenever this column is read, the rowid will be substituted
93836 ** in its place. Hence, fill this column with a NULL to avoid
93837 ** taking up data space with information that will never be used. */
93838 sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
93839 continue;
93841 if( pColumn==0 ){
93842 if( IsHiddenColumn(&pTab->aCol[i]) ){
93843 assert( IsVirtual(pTab) );
93844 j = -1;
93845 nHidden++;
93846 }else{
93847 j = i - nHidden;
93849 }else{
93850 for(j=0; j<pColumn->nId; j++){
93851 if( pColumn->a[j].idx==i ) break;
93854 if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
93855 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
93856 }else if( useTempTable ){
93857 sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
93858 }else if( pSelect ){
93859 sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
93860 }else{
93861 sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
93865 /* Generate code to check constraints and generate index keys and
93866 ** do the insertion.
93868 #ifndef SQLITE_OMIT_VIRTUALTABLE
93869 if( IsVirtual(pTab) ){
93870 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
93871 sqlite3VtabMakeWritable(pParse, pTab);
93872 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
93873 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
93874 sqlite3MayAbort(pParse);
93875 }else
93876 #endif
93878 int isReplace; /* Set to true if constraints may cause a replace */
93879 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
93880 regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
93882 sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
93883 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
93884 regIns, aRegIdx, 0, appendFlag, isReplace==0);
93888 /* Update the count of rows that are inserted
93890 if( (db->flags & SQLITE_CountRows)!=0 ){
93891 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
93894 if( pTrigger ){
93895 /* Code AFTER triggers */
93896 sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
93897 pTab, regData-2-pTab->nCol, onError, endOfLoop);
93900 /* The bottom of the main insertion loop, if the data source
93901 ** is a SELECT statement.
93903 sqlite3VdbeResolveLabel(v, endOfLoop);
93904 if( useTempTable ){
93905 sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
93906 sqlite3VdbeJumpHere(v, addrInsTop);
93907 sqlite3VdbeAddOp1(v, OP_Close, srcTab);
93908 }else if( pSelect ){
93909 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
93910 sqlite3VdbeJumpHere(v, addrInsTop);
93913 if( !IsVirtual(pTab) && !isView ){
93914 /* Close all tables opened */
93915 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
93916 for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
93917 sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
93921 insert_end:
93922 /* Update the sqlite_sequence table by storing the content of the
93923 ** maximum rowid counter values recorded while inserting into
93924 ** autoincrement tables.
93926 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
93927 sqlite3AutoincrementEnd(pParse);
93931 ** Return the number of rows inserted. If this routine is
93932 ** generating code because of a call to sqlite3NestedParse(), do not
93933 ** invoke the callback function.
93935 if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
93936 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
93937 sqlite3VdbeSetNumCols(v, 1);
93938 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
93941 insert_cleanup:
93942 sqlite3SrcListDelete(db, pTabList);
93943 sqlite3ExprListDelete(db, pList);
93944 sqlite3SelectDelete(db, pSelect);
93945 sqlite3IdListDelete(db, pColumn);
93946 sqlite3DbFree(db, aRegIdx);
93949 /* Make sure "isView" and other macros defined above are undefined. Otherwise
93950 ** thely may interfere with compilation of other functions in this file
93951 ** (or in another file, if this file becomes part of the amalgamation). */
93952 #ifdef isView
93953 #undef isView
93954 #endif
93955 #ifdef pTrigger
93956 #undef pTrigger
93957 #endif
93958 #ifdef tmask
93959 #undef tmask
93960 #endif
93963 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
93964 ** on table pTab.
93966 ** The regNewData parameter is the first register in a range that contains
93967 ** the data to be inserted or the data after the update. There will be
93968 ** pTab->nCol+1 registers in this range. The first register (the one
93969 ** that regNewData points to) will contain the new rowid, or NULL in the
93970 ** case of a WITHOUT ROWID table. The second register in the range will
93971 ** contain the content of the first table column. The third register will
93972 ** contain the content of the second table column. And so forth.
93974 ** The regOldData parameter is similar to regNewData except that it contains
93975 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
93976 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
93977 ** checking regOldData for zero.
93979 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
93980 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
93981 ** might be modified by the UPDATE. If pkChng is false, then the key of
93982 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
93984 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
93985 ** was explicitly specified as part of the INSERT statement. If pkChng
93986 ** is zero, it means that the either rowid is computed automatically or
93987 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
93988 ** pkChng will only be true if the INSERT statement provides an integer
93989 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
93991 ** The code generated by this routine will store new index entries into
93992 ** registers identified by aRegIdx[]. No index entry is created for
93993 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
93994 ** the same as the order of indices on the linked list of indices
93995 ** at pTab->pIndex.
93997 ** The caller must have already opened writeable cursors on the main
93998 ** table and all applicable indices (that is to say, all indices for which
93999 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
94000 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
94001 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
94002 ** for the first index in the pTab->pIndex list. Cursors for other indices
94003 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
94005 ** This routine also generates code to check constraints. NOT NULL,
94006 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
94007 ** then the appropriate action is performed. There are five possible
94008 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
94010 ** Constraint type Action What Happens
94011 ** --------------- ---------- ----------------------------------------
94012 ** any ROLLBACK The current transaction is rolled back and
94013 ** sqlite3_step() returns immediately with a
94014 ** return code of SQLITE_CONSTRAINT.
94016 ** any ABORT Back out changes from the current command
94017 ** only (do not do a complete rollback) then
94018 ** cause sqlite3_step() to return immediately
94019 ** with SQLITE_CONSTRAINT.
94021 ** any FAIL Sqlite3_step() returns immediately with a
94022 ** return code of SQLITE_CONSTRAINT. The
94023 ** transaction is not rolled back and any
94024 ** changes to prior rows are retained.
94026 ** any IGNORE The attempt in insert or update the current
94027 ** row is skipped, without throwing an error.
94028 ** Processing continues with the next row.
94029 ** (There is an immediate jump to ignoreDest.)
94031 ** NOT NULL REPLACE The NULL value is replace by the default
94032 ** value for that column. If the default value
94033 ** is NULL, the action is the same as ABORT.
94035 ** UNIQUE REPLACE The other row that conflicts with the row
94036 ** being inserted is removed.
94038 ** CHECK REPLACE Illegal. The results in an exception.
94040 ** Which action to take is determined by the overrideError parameter.
94041 ** Or if overrideError==OE_Default, then the pParse->onError parameter
94042 ** is used. Or if pParse->onError==OE_Default then the onError value
94043 ** for the constraint is used.
94045 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
94046 Parse *pParse, /* The parser context */
94047 Table *pTab, /* The table being inserted or updated */
94048 int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
94049 int iDataCur, /* Canonical data cursor (main table or PK index) */
94050 int iIdxCur, /* First index cursor */
94051 int regNewData, /* First register in a range holding values to insert */
94052 int regOldData, /* Previous content. 0 for INSERTs */
94053 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
94054 u8 overrideError, /* Override onError to this if not OE_Default */
94055 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
94056 int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
94058 Vdbe *v; /* VDBE under constrution */
94059 Index *pIdx; /* Pointer to one of the indices */
94060 Index *pPk = 0; /* The PRIMARY KEY index */
94061 sqlite3 *db; /* Database connection */
94062 int i; /* loop counter */
94063 int ix; /* Index loop counter */
94064 int nCol; /* Number of columns */
94065 int onError; /* Conflict resolution strategy */
94066 int j1; /* Addresss of jump instruction */
94067 int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
94068 int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
94069 int ipkTop = 0; /* Top of the rowid change constraint check */
94070 int ipkBottom = 0; /* Bottom of the rowid change constraint check */
94071 u8 isUpdate; /* True if this is an UPDATE operation */
94072 int regRowid = -1; /* Register holding ROWID value */
94074 isUpdate = regOldData!=0;
94075 db = pParse->db;
94076 v = sqlite3GetVdbe(pParse);
94077 assert( v!=0 );
94078 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
94079 nCol = pTab->nCol;
94081 /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
94082 ** normal rowid tables. nPkField is the number of key fields in the
94083 ** pPk index or 1 for a rowid table. In other words, nPkField is the
94084 ** number of fields in the true primary key of the table. */
94085 if( HasRowid(pTab) ){
94086 pPk = 0;
94087 nPkField = 1;
94088 }else{
94089 pPk = sqlite3PrimaryKeyIndex(pTab);
94090 nPkField = pPk->nKeyCol;
94093 /* Record that this module has started */
94094 VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
94095 iDataCur, iIdxCur, regNewData, regOldData, pkChng));
94097 /* Test all NOT NULL constraints.
94099 for(i=0; i<nCol; i++){
94100 if( i==pTab->iPKey ){
94101 continue;
94103 onError = pTab->aCol[i].notNull;
94104 if( onError==OE_None ) continue;
94105 if( overrideError!=OE_Default ){
94106 onError = overrideError;
94107 }else if( onError==OE_Default ){
94108 onError = OE_Abort;
94110 if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
94111 onError = OE_Abort;
94113 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
94114 || onError==OE_Ignore || onError==OE_Replace );
94115 switch( onError ){
94116 case OE_Abort:
94117 sqlite3MayAbort(pParse);
94118 /* Fall through */
94119 case OE_Rollback:
94120 case OE_Fail: {
94121 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
94122 pTab->aCol[i].zName);
94123 sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
94124 regNewData+1+i, zMsg, P4_DYNAMIC);
94125 sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
94126 break;
94128 case OE_Ignore: {
94129 sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
94130 break;
94132 default: {
94133 assert( onError==OE_Replace );
94134 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
94135 sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
94136 sqlite3VdbeJumpHere(v, j1);
94137 break;
94142 /* Test all CHECK constraints
94144 #ifndef SQLITE_OMIT_CHECK
94145 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
94146 ExprList *pCheck = pTab->pCheck;
94147 pParse->ckBase = regNewData+1;
94148 onError = overrideError!=OE_Default ? overrideError : OE_Abort;
94149 for(i=0; i<pCheck->nExpr; i++){
94150 int allOk = sqlite3VdbeMakeLabel(v);
94151 sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
94152 if( onError==OE_Ignore ){
94153 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
94154 }else{
94155 char *zName = pCheck->a[i].zName;
94156 if( zName==0 ) zName = pTab->zName;
94157 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
94158 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
94159 onError, zName, P4_TRANSIENT,
94160 P5_ConstraintCheck);
94162 sqlite3VdbeResolveLabel(v, allOk);
94165 #endif /* !defined(SQLITE_OMIT_CHECK) */
94167 /* If rowid is changing, make sure the new rowid does not previously
94168 ** exist in the table.
94170 if( pkChng && pPk==0 ){
94171 int addrRowidOk = sqlite3VdbeMakeLabel(v);
94173 /* Figure out what action to take in case of a rowid collision */
94174 onError = pTab->keyConf;
94175 if( overrideError!=OE_Default ){
94176 onError = overrideError;
94177 }else if( onError==OE_Default ){
94178 onError = OE_Abort;
94181 if( isUpdate ){
94182 /* pkChng!=0 does not mean that the rowid has change, only that
94183 ** it might have changed. Skip the conflict logic below if the rowid
94184 ** is unchanged. */
94185 sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
94188 /* If the response to a rowid conflict is REPLACE but the response
94189 ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
94190 ** to defer the running of the rowid conflict checking until after
94191 ** the UNIQUE constraints have run.
94193 if( onError==OE_Replace && overrideError!=OE_Replace ){
94194 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94195 if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
94196 ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
94197 break;
94202 /* Check to see if the new rowid already exists in the table. Skip
94203 ** the following conflict logic if it does not. */
94204 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
94206 /* Generate code that deals with a rowid collision */
94207 switch( onError ){
94208 default: {
94209 onError = OE_Abort;
94210 /* Fall thru into the next case */
94212 case OE_Rollback:
94213 case OE_Abort:
94214 case OE_Fail: {
94215 sqlite3RowidConstraint(pParse, onError, pTab);
94216 break;
94218 case OE_Replace: {
94219 /* If there are DELETE triggers on this table and the
94220 ** recursive-triggers flag is set, call GenerateRowDelete() to
94221 ** remove the conflicting row from the table. This will fire
94222 ** the triggers and remove both the table and index b-tree entries.
94224 ** Otherwise, if there are no triggers or the recursive-triggers
94225 ** flag is not set, but the table has one or more indexes, call
94226 ** GenerateRowIndexDelete(). This removes the index b-tree entries
94227 ** only. The table b-tree entry will be replaced by the new entry
94228 ** when it is inserted.
94230 ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
94231 ** also invoke MultiWrite() to indicate that this VDBE may require
94232 ** statement rollback (if the statement is aborted after the delete
94233 ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
94234 ** but being more selective here allows statements like:
94236 ** REPLACE INTO t(rowid) VALUES($newrowid)
94238 ** to run without a statement journal if there are no indexes on the
94239 ** table.
94241 Trigger *pTrigger = 0;
94242 if( db->flags&SQLITE_RecTriggers ){
94243 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
94245 if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
94246 sqlite3MultiWrite(pParse);
94247 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
94248 regNewData, 1, 0, OE_Replace, 1);
94249 }else if( pTab->pIndex ){
94250 sqlite3MultiWrite(pParse);
94251 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
94253 seenReplace = 1;
94254 break;
94256 case OE_Ignore: {
94257 /*assert( seenReplace==0 );*/
94258 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
94259 break;
94262 sqlite3VdbeResolveLabel(v, addrRowidOk);
94263 if( ipkTop ){
94264 ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
94265 sqlite3VdbeJumpHere(v, ipkTop);
94269 /* Test all UNIQUE constraints by creating entries for each UNIQUE
94270 ** index and making sure that duplicate entries do not already exist.
94271 ** Compute the revised record entries for indices as we go.
94273 ** This loop also handles the case of the PRIMARY KEY index for a
94274 ** WITHOUT ROWID table.
94276 for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
94277 int regIdx; /* Range of registers hold conent for pIdx */
94278 int regR; /* Range of registers holding conflicting PK */
94279 int iThisCur; /* Cursor for this UNIQUE index */
94280 int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
94282 if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
94283 iThisCur = iIdxCur+ix;
94284 addrUniqueOk = sqlite3VdbeMakeLabel(v);
94286 /* Skip partial indices for which the WHERE clause is not true */
94287 if( pIdx->pPartIdxWhere ){
94288 sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
94289 pParse->ckBase = regNewData+1;
94290 sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
94291 SQLITE_JUMPIFNULL);
94292 pParse->ckBase = 0;
94295 /* Create a record for this index entry as it should appear after
94296 ** the insert or update. Store that record in the aRegIdx[ix] register
94298 regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
94299 for(i=0; i<pIdx->nColumn; i++){
94300 int iField = pIdx->aiColumn[i];
94301 int x;
94302 if( iField<0 || iField==pTab->iPKey ){
94303 if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
94304 x = regNewData;
94305 regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
94306 }else{
94307 x = iField + regNewData + 1;
94309 sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
94310 VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
94312 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
94313 sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
94314 VdbeComment((v, "for %s", pIdx->zName));
94315 sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
94317 /* In an UPDATE operation, if this index is the PRIMARY KEY index
94318 ** of a WITHOUT ROWID table and there has been no change the
94319 ** primary key, then no collision is possible. The collision detection
94320 ** logic below can all be skipped. */
94321 if( isUpdate && pPk==pIdx && pkChng==0 ){
94322 sqlite3VdbeResolveLabel(v, addrUniqueOk);
94323 continue;
94326 /* Find out what action to take in case there is a uniqueness conflict */
94327 onError = pIdx->onError;
94328 if( onError==OE_None ){
94329 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
94330 sqlite3VdbeResolveLabel(v, addrUniqueOk);
94331 continue; /* pIdx is not a UNIQUE index */
94333 if( overrideError!=OE_Default ){
94334 onError = overrideError;
94335 }else if( onError==OE_Default ){
94336 onError = OE_Abort;
94339 /* Check to see if the new index entry will be unique */
94340 sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
94341 regIdx, pIdx->nKeyCol);
94343 /* Generate code to handle collisions */
94344 regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
94345 if( isUpdate || onError==OE_Replace ){
94346 if( HasRowid(pTab) ){
94347 sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
94348 /* Conflict only if the rowid of the existing index entry
94349 ** is different from old-rowid */
94350 if( isUpdate ){
94351 sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
94353 }else{
94354 int x;
94355 /* Extract the PRIMARY KEY from the end of the index entry and
94356 ** store it in registers regR..regR+nPk-1 */
94357 if( pIdx!=pPk ){
94358 for(i=0; i<pPk->nKeyCol; i++){
94359 x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
94360 sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
94361 VdbeComment((v, "%s.%s", pTab->zName,
94362 pTab->aCol[pPk->aiColumn[i]].zName));
94365 if( isUpdate ){
94366 /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
94367 ** table, only conflict if the new PRIMARY KEY values are actually
94368 ** different from the old.
94370 ** For a UNIQUE index, only conflict if the PRIMARY KEY values
94371 ** of the matched index row are different from the original PRIMARY
94372 ** KEY values of this row before the update. */
94373 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
94374 int op = OP_Ne;
94375 int regCmp = (pIdx->autoIndex==2 ? regIdx : regR);
94377 for(i=0; i<pPk->nKeyCol; i++){
94378 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
94379 x = pPk->aiColumn[i];
94380 if( i==(pPk->nKeyCol-1) ){
94381 addrJump = addrUniqueOk;
94382 op = OP_Eq;
94384 sqlite3VdbeAddOp4(v, op,
94385 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
94392 /* Generate code that executes if the new index entry is not unique */
94393 assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
94394 || onError==OE_Ignore || onError==OE_Replace );
94395 switch( onError ){
94396 case OE_Rollback:
94397 case OE_Abort:
94398 case OE_Fail: {
94399 sqlite3UniqueConstraint(pParse, onError, pIdx);
94400 break;
94402 case OE_Ignore: {
94403 sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
94404 break;
94406 default: {
94407 Trigger *pTrigger = 0;
94408 assert( onError==OE_Replace );
94409 sqlite3MultiWrite(pParse);
94410 if( db->flags&SQLITE_RecTriggers ){
94411 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
94413 sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
94414 regR, nPkField, 0, OE_Replace, pIdx==pPk);
94415 seenReplace = 1;
94416 break;
94419 sqlite3VdbeResolveLabel(v, addrUniqueOk);
94420 sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
94421 if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
94423 if( ipkTop ){
94424 sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
94425 sqlite3VdbeJumpHere(v, ipkBottom);
94428 *pbMayReplace = seenReplace;
94429 VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
94433 ** This routine generates code to finish the INSERT or UPDATE operation
94434 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
94435 ** A consecutive range of registers starting at regNewData contains the
94436 ** rowid and the content to be inserted.
94438 ** The arguments to this routine should be the same as the first six
94439 ** arguments to sqlite3GenerateConstraintChecks.
94441 SQLITE_PRIVATE void sqlite3CompleteInsertion(
94442 Parse *pParse, /* The parser context */
94443 Table *pTab, /* the table into which we are inserting */
94444 int iDataCur, /* Cursor of the canonical data source */
94445 int iIdxCur, /* First index cursor */
94446 int regNewData, /* Range of content */
94447 int *aRegIdx, /* Register used by each index. 0 for unused indices */
94448 int isUpdate, /* True for UPDATE, False for INSERT */
94449 int appendBias, /* True if this is likely to be an append */
94450 int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
94452 Vdbe *v; /* Prepared statements under construction */
94453 Index *pIdx; /* An index being inserted or updated */
94454 u8 pik_flags; /* flag values passed to the btree insert */
94455 int regData; /* Content registers (after the rowid) */
94456 int regRec; /* Register holding assemblied record for the table */
94457 int i; /* Loop counter */
94459 v = sqlite3GetVdbe(pParse);
94460 assert( v!=0 );
94461 assert( pTab->pSelect==0 ); /* This table is not a VIEW */
94462 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
94463 if( aRegIdx[i]==0 ) continue;
94464 if( pIdx->pPartIdxWhere ){
94465 sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
94467 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
94468 pik_flags = 0;
94469 if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
94470 if( pIdx->autoIndex==2 && !HasRowid(pTab) ){
94471 assert( pParse->nested==0 );
94472 pik_flags |= OPFLAG_NCHANGE;
94474 if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
94476 if( !HasRowid(pTab) ) return;
94477 regData = regNewData + 1;
94478 regRec = sqlite3GetTempReg(pParse);
94479 sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
94480 sqlite3TableAffinityStr(v, pTab);
94481 sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
94482 if( pParse->nested ){
94483 pik_flags = 0;
94484 }else{
94485 pik_flags = OPFLAG_NCHANGE;
94486 pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
94488 if( appendBias ){
94489 pik_flags |= OPFLAG_APPEND;
94491 if( useSeekResult ){
94492 pik_flags |= OPFLAG_USESEEKRESULT;
94494 sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
94495 if( !pParse->nested ){
94496 sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
94498 sqlite3VdbeChangeP5(v, pik_flags);
94502 ** Allocate cursors for the pTab table and all its indices and generate
94503 ** code to open and initialized those cursors.
94505 ** The cursor for the object that contains the complete data (normally
94506 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
94507 ** ROWID table) is returned in *piDataCur. The first index cursor is
94508 ** returned in *piIdxCur. The number of indices is returned.
94510 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
94511 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
94512 ** If iBase is negative, then allocate the next available cursor.
94514 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
94515 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
94516 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
94517 ** pTab->pIndex list.
94519 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
94520 Parse *pParse, /* Parsing context */
94521 Table *pTab, /* Table to be opened */
94522 int op, /* OP_OpenRead or OP_OpenWrite */
94523 int iBase, /* Use this for the table cursor, if there is one */
94524 u8 *aToOpen, /* If not NULL: boolean for each table and index */
94525 int *piDataCur, /* Write the database source cursor number here */
94526 int *piIdxCur /* Write the first index cursor number here */
94528 int i;
94529 int iDb;
94530 int iDataCur;
94531 Index *pIdx;
94532 Vdbe *v;
94534 assert( op==OP_OpenRead || op==OP_OpenWrite );
94535 if( IsVirtual(pTab) ){
94536 assert( aToOpen==0 );
94537 *piDataCur = 0;
94538 *piIdxCur = 1;
94539 return 0;
94541 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94542 v = sqlite3GetVdbe(pParse);
94543 assert( v!=0 );
94544 if( iBase<0 ) iBase = pParse->nTab;
94545 iDataCur = iBase++;
94546 if( piDataCur ) *piDataCur = iDataCur;
94547 if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
94548 sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
94549 }else{
94550 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
94552 if( piIdxCur ) *piIdxCur = iBase;
94553 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
94554 int iIdxCur = iBase++;
94555 assert( pIdx->pSchema==pTab->pSchema );
94556 if( pIdx->autoIndex==2 && !HasRowid(pTab) && piDataCur ){
94557 *piDataCur = iIdxCur;
94559 if( aToOpen==0 || aToOpen[i+1] ){
94560 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
94561 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
94562 VdbeComment((v, "%s", pIdx->zName));
94565 if( iBase>pParse->nTab ) pParse->nTab = iBase;
94566 return i;
94570 #ifdef SQLITE_TEST
94572 ** The following global variable is incremented whenever the
94573 ** transfer optimization is used. This is used for testing
94574 ** purposes only - to make sure the transfer optimization really
94575 ** is happening when it is suppose to.
94577 SQLITE_API int sqlite3_xferopt_count;
94578 #endif /* SQLITE_TEST */
94581 #ifndef SQLITE_OMIT_XFER_OPT
94583 ** Check to collation names to see if they are compatible.
94585 static int xferCompatibleCollation(const char *z1, const char *z2){
94586 if( z1==0 ){
94587 return z2==0;
94589 if( z2==0 ){
94590 return 0;
94592 return sqlite3StrICmp(z1, z2)==0;
94597 ** Check to see if index pSrc is compatible as a source of data
94598 ** for index pDest in an insert transfer optimization. The rules
94599 ** for a compatible index:
94601 ** * The index is over the same set of columns
94602 ** * The same DESC and ASC markings occurs on all columns
94603 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
94604 ** * The same collating sequence on each column
94605 ** * The index has the exact same WHERE clause
94607 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
94608 int i;
94609 assert( pDest && pSrc );
94610 assert( pDest->pTable!=pSrc->pTable );
94611 if( pDest->nKeyCol!=pSrc->nKeyCol ){
94612 return 0; /* Different number of columns */
94614 if( pDest->onError!=pSrc->onError ){
94615 return 0; /* Different conflict resolution strategies */
94617 for(i=0; i<pSrc->nKeyCol; i++){
94618 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
94619 return 0; /* Different columns indexed */
94621 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
94622 return 0; /* Different sort orders */
94624 if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
94625 return 0; /* Different collating sequences */
94628 if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
94629 return 0; /* Different WHERE clauses */
94632 /* If no test above fails then the indices must be compatible */
94633 return 1;
94637 ** Attempt the transfer optimization on INSERTs of the form
94639 ** INSERT INTO tab1 SELECT * FROM tab2;
94641 ** The xfer optimization transfers raw records from tab2 over to tab1.
94642 ** Columns are not decoded and reassemblied, which greatly improves
94643 ** performance. Raw index records are transferred in the same way.
94645 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
94646 ** There are lots of rules for determining compatibility - see comments
94647 ** embedded in the code for details.
94649 ** This routine returns TRUE if the optimization is guaranteed to be used.
94650 ** Sometimes the xfer optimization will only work if the destination table
94651 ** is empty - a factor that can only be determined at run-time. In that
94652 ** case, this routine generates code for the xfer optimization but also
94653 ** does a test to see if the destination table is empty and jumps over the
94654 ** xfer optimization code if the test fails. In that case, this routine
94655 ** returns FALSE so that the caller will know to go ahead and generate
94656 ** an unoptimized transfer. This routine also returns FALSE if there
94657 ** is no chance that the xfer optimization can be applied.
94659 ** This optimization is particularly useful at making VACUUM run faster.
94661 static int xferOptimization(
94662 Parse *pParse, /* Parser context */
94663 Table *pDest, /* The table we are inserting into */
94664 Select *pSelect, /* A SELECT statement to use as the data source */
94665 int onError, /* How to handle constraint errors */
94666 int iDbDest /* The database of pDest */
94668 ExprList *pEList; /* The result set of the SELECT */
94669 Table *pSrc; /* The table in the FROM clause of SELECT */
94670 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
94671 struct SrcList_item *pItem; /* An element of pSelect->pSrc */
94672 int i; /* Loop counter */
94673 int iDbSrc; /* The database of pSrc */
94674 int iSrc, iDest; /* Cursors from source and destination */
94675 int addr1, addr2; /* Loop addresses */
94676 int emptyDestTest = 0; /* Address of test for empty pDest */
94677 int emptySrcTest = 0; /* Address of test for empty pSrc */
94678 Vdbe *v; /* The VDBE we are building */
94679 int regAutoinc; /* Memory register used by AUTOINC */
94680 int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
94681 int regData, regRowid; /* Registers holding data and rowid */
94683 if( pSelect==0 ){
94684 return 0; /* Must be of the form INSERT INTO ... SELECT ... */
94686 if( pParse->pWith || pSelect->pWith ){
94687 /* Do not attempt to process this query if there are an WITH clauses
94688 ** attached to it. Proceeding may generate a false "no such table: xxx"
94689 ** error if pSelect reads from a CTE named "xxx". */
94690 return 0;
94692 if( sqlite3TriggerList(pParse, pDest) ){
94693 return 0; /* tab1 must not have triggers */
94695 #ifndef SQLITE_OMIT_VIRTUALTABLE
94696 if( pDest->tabFlags & TF_Virtual ){
94697 return 0; /* tab1 must not be a virtual table */
94699 #endif
94700 if( onError==OE_Default ){
94701 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
94702 if( onError==OE_Default ) onError = OE_Abort;
94704 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
94705 if( pSelect->pSrc->nSrc!=1 ){
94706 return 0; /* FROM clause must have exactly one term */
94708 if( pSelect->pSrc->a[0].pSelect ){
94709 return 0; /* FROM clause cannot contain a subquery */
94711 if( pSelect->pWhere ){
94712 return 0; /* SELECT may not have a WHERE clause */
94714 if( pSelect->pOrderBy ){
94715 return 0; /* SELECT may not have an ORDER BY clause */
94717 /* Do not need to test for a HAVING clause. If HAVING is present but
94718 ** there is no ORDER BY, we will get an error. */
94719 if( pSelect->pGroupBy ){
94720 return 0; /* SELECT may not have a GROUP BY clause */
94722 if( pSelect->pLimit ){
94723 return 0; /* SELECT may not have a LIMIT clause */
94725 assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
94726 if( pSelect->pPrior ){
94727 return 0; /* SELECT may not be a compound query */
94729 if( pSelect->selFlags & SF_Distinct ){
94730 return 0; /* SELECT may not be DISTINCT */
94732 pEList = pSelect->pEList;
94733 assert( pEList!=0 );
94734 if( pEList->nExpr!=1 ){
94735 return 0; /* The result set must have exactly one column */
94737 assert( pEList->a[0].pExpr );
94738 if( pEList->a[0].pExpr->op!=TK_ALL ){
94739 return 0; /* The result set must be the special operator "*" */
94742 /* At this point we have established that the statement is of the
94743 ** correct syntactic form to participate in this optimization. Now
94744 ** we have to check the semantics.
94746 pItem = pSelect->pSrc->a;
94747 pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
94748 if( pSrc==0 ){
94749 return 0; /* FROM clause does not contain a real table */
94751 if( pSrc==pDest ){
94752 return 0; /* tab1 and tab2 may not be the same table */
94754 if( HasRowid(pDest)!=HasRowid(pSrc) ){
94755 return 0; /* source and destination must both be WITHOUT ROWID or not */
94757 #ifndef SQLITE_OMIT_VIRTUALTABLE
94758 if( pSrc->tabFlags & TF_Virtual ){
94759 return 0; /* tab2 must not be a virtual table */
94761 #endif
94762 if( pSrc->pSelect ){
94763 return 0; /* tab2 may not be a view */
94765 if( pDest->nCol!=pSrc->nCol ){
94766 return 0; /* Number of columns must be the same in tab1 and tab2 */
94768 if( pDest->iPKey!=pSrc->iPKey ){
94769 return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
94771 for(i=0; i<pDest->nCol; i++){
94772 if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
94773 return 0; /* Affinity must be the same on all columns */
94775 if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
94776 return 0; /* Collating sequence must be the same on all columns */
94778 if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
94779 return 0; /* tab2 must be NOT NULL if tab1 is */
94782 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
94783 if( pDestIdx->onError!=OE_None ){
94784 destHasUniqueIdx = 1;
94786 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
94787 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
94789 if( pSrcIdx==0 ){
94790 return 0; /* pDestIdx has no corresponding index in pSrc */
94793 #ifndef SQLITE_OMIT_CHECK
94794 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
94795 return 0; /* Tables have different CHECK constraints. Ticket #2252 */
94797 #endif
94798 #ifndef SQLITE_OMIT_FOREIGN_KEY
94799 /* Disallow the transfer optimization if the destination table constains
94800 ** any foreign key constraints. This is more restrictive than necessary.
94801 ** But the main beneficiary of the transfer optimization is the VACUUM
94802 ** command, and the VACUUM command disables foreign key constraints. So
94803 ** the extra complication to make this rule less restrictive is probably
94804 ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
94806 if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
94807 return 0;
94809 #endif
94810 if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
94811 return 0; /* xfer opt does not play well with PRAGMA count_changes */
94814 /* If we get this far, it means that the xfer optimization is at
94815 ** least a possibility, though it might only work if the destination
94816 ** table (tab1) is initially empty.
94818 #ifdef SQLITE_TEST
94819 sqlite3_xferopt_count++;
94820 #endif
94821 iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
94822 v = sqlite3GetVdbe(pParse);
94823 sqlite3CodeVerifySchema(pParse, iDbSrc);
94824 iSrc = pParse->nTab++;
94825 iDest = pParse->nTab++;
94826 regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
94827 regData = sqlite3GetTempReg(pParse);
94828 regRowid = sqlite3GetTempReg(pParse);
94829 sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
94830 assert( HasRowid(pDest) || destHasUniqueIdx );
94831 if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
94832 || destHasUniqueIdx /* (2) */
94833 || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
94835 /* In some circumstances, we are able to run the xfer optimization
94836 ** only if the destination table is initially empty. This code makes
94837 ** that determination. Conditions under which the destination must
94838 ** be empty:
94840 ** (1) There is no INTEGER PRIMARY KEY but there are indices.
94841 ** (If the destination is not initially empty, the rowid fields
94842 ** of index entries might need to change.)
94844 ** (2) The destination has a unique index. (The xfer optimization
94845 ** is unable to test uniqueness.)
94847 ** (3) onError is something other than OE_Abort and OE_Rollback.
94849 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
94850 emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
94851 sqlite3VdbeJumpHere(v, addr1);
94853 if( HasRowid(pSrc) ){
94854 sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
94855 emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
94856 if( pDest->iPKey>=0 ){
94857 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
94858 addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
94859 sqlite3RowidConstraint(pParse, onError, pDest);
94860 sqlite3VdbeJumpHere(v, addr2);
94861 autoIncStep(pParse, regAutoinc, regRowid);
94862 }else if( pDest->pIndex==0 ){
94863 addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
94864 }else{
94865 addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
94866 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
94868 sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
94869 sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
94870 sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
94871 sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
94872 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
94873 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
94874 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
94875 }else{
94876 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
94877 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
94879 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
94880 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
94881 if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
94883 assert( pSrcIdx );
94884 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
94885 sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
94886 VdbeComment((v, "%s", pSrcIdx->zName));
94887 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
94888 sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
94889 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
94890 VdbeComment((v, "%s", pDestIdx->zName));
94891 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
94892 sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
94893 sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
94894 sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
94895 sqlite3VdbeJumpHere(v, addr1);
94896 sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
94897 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
94899 sqlite3VdbeJumpHere(v, emptySrcTest);
94900 sqlite3ReleaseTempReg(pParse, regRowid);
94901 sqlite3ReleaseTempReg(pParse, regData);
94902 if( emptyDestTest ){
94903 sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
94904 sqlite3VdbeJumpHere(v, emptyDestTest);
94905 sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
94906 return 0;
94907 }else{
94908 return 1;
94911 #endif /* SQLITE_OMIT_XFER_OPT */
94913 /************** End of insert.c **********************************************/
94914 /************** Begin file legacy.c ******************************************/
94916 ** 2001 September 15
94918 ** The author disclaims copyright to this source code. In place of
94919 ** a legal notice, here is a blessing:
94921 ** May you do good and not evil.
94922 ** May you find forgiveness for yourself and forgive others.
94923 ** May you share freely, never taking more than you give.
94925 *************************************************************************
94926 ** Main file for the SQLite library. The routines in this file
94927 ** implement the programmer interface to the library. Routines in
94928 ** other files are for internal use by SQLite and should not be
94929 ** accessed by users of the library.
94934 ** Execute SQL code. Return one of the SQLITE_ success/failure
94935 ** codes. Also write an error message into memory obtained from
94936 ** malloc() and make *pzErrMsg point to that message.
94938 ** If the SQL is a query, then for each row in the query result
94939 ** the xCallback() function is called. pArg becomes the first
94940 ** argument to xCallback(). If xCallback=NULL then no callback
94941 ** is invoked, even for queries.
94943 SQLITE_API int sqlite3_exec(
94944 sqlite3 *db, /* The database on which the SQL executes */
94945 const char *zSql, /* The SQL to be executed */
94946 sqlite3_callback xCallback, /* Invoke this callback routine */
94947 void *pArg, /* First argument to xCallback() */
94948 char **pzErrMsg /* Write error messages here */
94950 int rc = SQLITE_OK; /* Return code */
94951 const char *zLeftover; /* Tail of unprocessed SQL */
94952 sqlite3_stmt *pStmt = 0; /* The current SQL statement */
94953 char **azCols = 0; /* Names of result columns */
94954 int callbackIsInit; /* True if callback data is initialized */
94956 if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
94957 if( zSql==0 ) zSql = "";
94959 sqlite3_mutex_enter(db->mutex);
94960 sqlite3Error(db, SQLITE_OK, 0);
94961 while( rc==SQLITE_OK && zSql[0] ){
94962 int nCol;
94963 char **azVals = 0;
94965 pStmt = 0;
94966 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
94967 assert( rc==SQLITE_OK || pStmt==0 );
94968 if( rc!=SQLITE_OK ){
94969 continue;
94971 if( !pStmt ){
94972 /* this happens for a comment or white-space */
94973 zSql = zLeftover;
94974 continue;
94977 callbackIsInit = 0;
94978 nCol = sqlite3_column_count(pStmt);
94980 while( 1 ){
94981 int i;
94982 rc = sqlite3_step(pStmt);
94984 /* Invoke the callback function if required */
94985 if( xCallback && (SQLITE_ROW==rc ||
94986 (SQLITE_DONE==rc && !callbackIsInit
94987 && db->flags&SQLITE_NullCallback)) ){
94988 if( !callbackIsInit ){
94989 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
94990 if( azCols==0 ){
94991 goto exec_out;
94993 for(i=0; i<nCol; i++){
94994 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
94995 /* sqlite3VdbeSetColName() installs column names as UTF8
94996 ** strings so there is no way for sqlite3_column_name() to fail. */
94997 assert( azCols[i]!=0 );
94999 callbackIsInit = 1;
95001 if( rc==SQLITE_ROW ){
95002 azVals = &azCols[nCol];
95003 for(i=0; i<nCol; i++){
95004 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
95005 if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
95006 db->mallocFailed = 1;
95007 goto exec_out;
95011 if( xCallback(pArg, nCol, azVals, azCols) ){
95012 rc = SQLITE_ABORT;
95013 sqlite3VdbeFinalize((Vdbe *)pStmt);
95014 pStmt = 0;
95015 sqlite3Error(db, SQLITE_ABORT, 0);
95016 goto exec_out;
95020 if( rc!=SQLITE_ROW ){
95021 rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
95022 pStmt = 0;
95023 zSql = zLeftover;
95024 while( sqlite3Isspace(zSql[0]) ) zSql++;
95025 break;
95029 sqlite3DbFree(db, azCols);
95030 azCols = 0;
95033 exec_out:
95034 if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
95035 sqlite3DbFree(db, azCols);
95037 rc = sqlite3ApiExit(db, rc);
95038 if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
95039 int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
95040 *pzErrMsg = sqlite3Malloc(nErrMsg);
95041 if( *pzErrMsg ){
95042 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
95043 }else{
95044 rc = SQLITE_NOMEM;
95045 sqlite3Error(db, SQLITE_NOMEM, 0);
95047 }else if( pzErrMsg ){
95048 *pzErrMsg = 0;
95051 assert( (rc&db->errMask)==rc );
95052 sqlite3_mutex_leave(db->mutex);
95053 return rc;
95056 /************** End of legacy.c **********************************************/
95057 /************** Begin file loadext.c *****************************************/
95059 ** 2006 June 7
95061 ** The author disclaims copyright to this source code. In place of
95062 ** a legal notice, here is a blessing:
95064 ** May you do good and not evil.
95065 ** May you find forgiveness for yourself and forgive others.
95066 ** May you share freely, never taking more than you give.
95068 *************************************************************************
95069 ** This file contains code used to dynamically load extensions into
95070 ** the SQLite library.
95073 #ifndef SQLITE_CORE
95074 #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
95075 #endif
95076 /************** Include sqlite3ext.h in the middle of loadext.c **************/
95077 /************** Begin file sqlite3ext.h **************************************/
95079 ** 2006 June 7
95081 ** The author disclaims copyright to this source code. In place of
95082 ** a legal notice, here is a blessing:
95084 ** May you do good and not evil.
95085 ** May you find forgiveness for yourself and forgive others.
95086 ** May you share freely, never taking more than you give.
95088 *************************************************************************
95089 ** This header file defines the SQLite interface for use by
95090 ** shared libraries that want to be imported as extensions into
95091 ** an SQLite instance. Shared libraries that intend to be loaded
95092 ** as extensions by SQLite should #include this file instead of
95093 ** sqlite3.h.
95095 #ifndef _SQLITE3EXT_H_
95096 #define _SQLITE3EXT_H_
95098 typedef struct sqlite3_api_routines sqlite3_api_routines;
95101 ** The following structure holds pointers to all of the SQLite API
95102 ** routines.
95104 ** WARNING: In order to maintain backwards compatibility, add new
95105 ** interfaces to the end of this structure only. If you insert new
95106 ** interfaces in the middle of this structure, then older different
95107 ** versions of SQLite will not be able to load each others' shared
95108 ** libraries!
95110 struct sqlite3_api_routines {
95111 void * (*aggregate_context)(sqlite3_context*,int nBytes);
95112 int (*aggregate_count)(sqlite3_context*);
95113 int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
95114 int (*bind_double)(sqlite3_stmt*,int,double);
95115 int (*bind_int)(sqlite3_stmt*,int,int);
95116 int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
95117 int (*bind_null)(sqlite3_stmt*,int);
95118 int (*bind_parameter_count)(sqlite3_stmt*);
95119 int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
95120 const char * (*bind_parameter_name)(sqlite3_stmt*,int);
95121 int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
95122 int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
95123 int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
95124 int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
95125 int (*busy_timeout)(sqlite3*,int ms);
95126 int (*changes)(sqlite3*);
95127 int (*close)(sqlite3*);
95128 int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
95129 int eTextRep,const char*));
95130 int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
95131 int eTextRep,const void*));
95132 const void * (*column_blob)(sqlite3_stmt*,int iCol);
95133 int (*column_bytes)(sqlite3_stmt*,int iCol);
95134 int (*column_bytes16)(sqlite3_stmt*,int iCol);
95135 int (*column_count)(sqlite3_stmt*pStmt);
95136 const char * (*column_database_name)(sqlite3_stmt*,int);
95137 const void * (*column_database_name16)(sqlite3_stmt*,int);
95138 const char * (*column_decltype)(sqlite3_stmt*,int i);
95139 const void * (*column_decltype16)(sqlite3_stmt*,int);
95140 double (*column_double)(sqlite3_stmt*,int iCol);
95141 int (*column_int)(sqlite3_stmt*,int iCol);
95142 sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
95143 const char * (*column_name)(sqlite3_stmt*,int);
95144 const void * (*column_name16)(sqlite3_stmt*,int);
95145 const char * (*column_origin_name)(sqlite3_stmt*,int);
95146 const void * (*column_origin_name16)(sqlite3_stmt*,int);
95147 const char * (*column_table_name)(sqlite3_stmt*,int);
95148 const void * (*column_table_name16)(sqlite3_stmt*,int);
95149 const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
95150 const void * (*column_text16)(sqlite3_stmt*,int iCol);
95151 int (*column_type)(sqlite3_stmt*,int iCol);
95152 sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
95153 void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
95154 int (*complete)(const char*sql);
95155 int (*complete16)(const void*sql);
95156 int (*create_collation)(sqlite3*,const char*,int,void*,
95157 int(*)(void*,int,const void*,int,const void*));
95158 int (*create_collation16)(sqlite3*,const void*,int,void*,
95159 int(*)(void*,int,const void*,int,const void*));
95160 int (*create_function)(sqlite3*,const char*,int,int,void*,
95161 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
95162 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
95163 void (*xFinal)(sqlite3_context*));
95164 int (*create_function16)(sqlite3*,const void*,int,int,void*,
95165 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
95166 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
95167 void (*xFinal)(sqlite3_context*));
95168 int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
95169 int (*data_count)(sqlite3_stmt*pStmt);
95170 sqlite3 * (*db_handle)(sqlite3_stmt*);
95171 int (*declare_vtab)(sqlite3*,const char*);
95172 int (*enable_shared_cache)(int);
95173 int (*errcode)(sqlite3*db);
95174 const char * (*errmsg)(sqlite3*);
95175 const void * (*errmsg16)(sqlite3*);
95176 int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
95177 int (*expired)(sqlite3_stmt*);
95178 int (*finalize)(sqlite3_stmt*pStmt);
95179 void (*free)(void*);
95180 void (*free_table)(char**result);
95181 int (*get_autocommit)(sqlite3*);
95182 void * (*get_auxdata)(sqlite3_context*,int);
95183 int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
95184 int (*global_recover)(void);
95185 void (*interruptx)(sqlite3*);
95186 sqlite_int64 (*last_insert_rowid)(sqlite3*);
95187 const char * (*libversion)(void);
95188 int (*libversion_number)(void);
95189 void *(*malloc)(int);
95190 char * (*mprintf)(const char*,...);
95191 int (*open)(const char*,sqlite3**);
95192 int (*open16)(const void*,sqlite3**);
95193 int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
95194 int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
95195 void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
95196 void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
95197 void *(*realloc)(void*,int);
95198 int (*reset)(sqlite3_stmt*pStmt);
95199 void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
95200 void (*result_double)(sqlite3_context*,double);
95201 void (*result_error)(sqlite3_context*,const char*,int);
95202 void (*result_error16)(sqlite3_context*,const void*,int);
95203 void (*result_int)(sqlite3_context*,int);
95204 void (*result_int64)(sqlite3_context*,sqlite_int64);
95205 void (*result_null)(sqlite3_context*);
95206 void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
95207 void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
95208 void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
95209 void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
95210 void (*result_value)(sqlite3_context*,sqlite3_value*);
95211 void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
95212 int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
95213 const char*,const char*),void*);
95214 void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
95215 char * (*snprintf)(int,char*,const char*,...);
95216 int (*step)(sqlite3_stmt*);
95217 int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
95218 char const**,char const**,int*,int*,int*);
95219 void (*thread_cleanup)(void);
95220 int (*total_changes)(sqlite3*);
95221 void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
95222 int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
95223 void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
95224 sqlite_int64),void*);
95225 void * (*user_data)(sqlite3_context*);
95226 const void * (*value_blob)(sqlite3_value*);
95227 int (*value_bytes)(sqlite3_value*);
95228 int (*value_bytes16)(sqlite3_value*);
95229 double (*value_double)(sqlite3_value*);
95230 int (*value_int)(sqlite3_value*);
95231 sqlite_int64 (*value_int64)(sqlite3_value*);
95232 int (*value_numeric_type)(sqlite3_value*);
95233 const unsigned char * (*value_text)(sqlite3_value*);
95234 const void * (*value_text16)(sqlite3_value*);
95235 const void * (*value_text16be)(sqlite3_value*);
95236 const void * (*value_text16le)(sqlite3_value*);
95237 int (*value_type)(sqlite3_value*);
95238 char *(*vmprintf)(const char*,va_list);
95239 /* Added ??? */
95240 int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
95241 /* Added by 3.3.13 */
95242 int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
95243 int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
95244 int (*clear_bindings)(sqlite3_stmt*);
95245 /* Added by 3.4.1 */
95246 int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
95247 void (*xDestroy)(void *));
95248 /* Added by 3.5.0 */
95249 int (*bind_zeroblob)(sqlite3_stmt*,int,int);
95250 int (*blob_bytes)(sqlite3_blob*);
95251 int (*blob_close)(sqlite3_blob*);
95252 int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
95253 int,sqlite3_blob**);
95254 int (*blob_read)(sqlite3_blob*,void*,int,int);
95255 int (*blob_write)(sqlite3_blob*,const void*,int,int);
95256 int (*create_collation_v2)(sqlite3*,const char*,int,void*,
95257 int(*)(void*,int,const void*,int,const void*),
95258 void(*)(void*));
95259 int (*file_control)(sqlite3*,const char*,int,void*);
95260 sqlite3_int64 (*memory_highwater)(int);
95261 sqlite3_int64 (*memory_used)(void);
95262 sqlite3_mutex *(*mutex_alloc)(int);
95263 void (*mutex_enter)(sqlite3_mutex*);
95264 void (*mutex_free)(sqlite3_mutex*);
95265 void (*mutex_leave)(sqlite3_mutex*);
95266 int (*mutex_try)(sqlite3_mutex*);
95267 int (*open_v2)(const char*,sqlite3**,int,const char*);
95268 int (*release_memory)(int);
95269 void (*result_error_nomem)(sqlite3_context*);
95270 void (*result_error_toobig)(sqlite3_context*);
95271 int (*sleep)(int);
95272 void (*soft_heap_limit)(int);
95273 sqlite3_vfs *(*vfs_find)(const char*);
95274 int (*vfs_register)(sqlite3_vfs*,int);
95275 int (*vfs_unregister)(sqlite3_vfs*);
95276 int (*xthreadsafe)(void);
95277 void (*result_zeroblob)(sqlite3_context*,int);
95278 void (*result_error_code)(sqlite3_context*,int);
95279 int (*test_control)(int, ...);
95280 void (*randomness)(int,void*);
95281 sqlite3 *(*context_db_handle)(sqlite3_context*);
95282 int (*extended_result_codes)(sqlite3*,int);
95283 int (*limit)(sqlite3*,int,int);
95284 sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
95285 const char *(*sql)(sqlite3_stmt*);
95286 int (*status)(int,int*,int*,int);
95287 int (*backup_finish)(sqlite3_backup*);
95288 sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
95289 int (*backup_pagecount)(sqlite3_backup*);
95290 int (*backup_remaining)(sqlite3_backup*);
95291 int (*backup_step)(sqlite3_backup*,int);
95292 const char *(*compileoption_get)(int);
95293 int (*compileoption_used)(const char*);
95294 int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
95295 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
95296 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
95297 void (*xFinal)(sqlite3_context*),
95298 void(*xDestroy)(void*));
95299 int (*db_config)(sqlite3*,int,...);
95300 sqlite3_mutex *(*db_mutex)(sqlite3*);
95301 int (*db_status)(sqlite3*,int,int*,int*,int);
95302 int (*extended_errcode)(sqlite3*);
95303 void (*log)(int,const char*,...);
95304 sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
95305 const char *(*sourceid)(void);
95306 int (*stmt_status)(sqlite3_stmt*,int,int);
95307 int (*strnicmp)(const char*,const char*,int);
95308 int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
95309 int (*wal_autocheckpoint)(sqlite3*,int);
95310 int (*wal_checkpoint)(sqlite3*,const char*);
95311 void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
95312 int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
95313 int (*vtab_config)(sqlite3*,int op,...);
95314 int (*vtab_on_conflict)(sqlite3*);
95315 /* Version 3.7.16 and later */
95316 int (*close_v2)(sqlite3*);
95317 const char *(*db_filename)(sqlite3*,const char*);
95318 int (*db_readonly)(sqlite3*,const char*);
95319 int (*db_release_memory)(sqlite3*);
95320 const char *(*errstr)(int);
95321 int (*stmt_busy)(sqlite3_stmt*);
95322 int (*stmt_readonly)(sqlite3_stmt*);
95323 int (*stricmp)(const char*,const char*);
95324 int (*uri_boolean)(const char*,const char*,int);
95325 sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
95326 const char *(*uri_parameter)(const char*,const char*);
95327 char *(*vsnprintf)(int,char*,const char*,va_list);
95328 int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
95332 ** The following macros redefine the API routines so that they are
95333 ** redirected throught the global sqlite3_api structure.
95335 ** This header file is also used by the loadext.c source file
95336 ** (part of the main SQLite library - not an extension) so that
95337 ** it can get access to the sqlite3_api_routines structure
95338 ** definition. But the main library does not want to redefine
95339 ** the API. So the redefinition macros are only valid if the
95340 ** SQLITE_CORE macros is undefined.
95342 #ifndef SQLITE_CORE
95343 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
95344 #ifndef SQLITE_OMIT_DEPRECATED
95345 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
95346 #endif
95347 #define sqlite3_bind_blob sqlite3_api->bind_blob
95348 #define sqlite3_bind_double sqlite3_api->bind_double
95349 #define sqlite3_bind_int sqlite3_api->bind_int
95350 #define sqlite3_bind_int64 sqlite3_api->bind_int64
95351 #define sqlite3_bind_null sqlite3_api->bind_null
95352 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
95353 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
95354 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
95355 #define sqlite3_bind_text sqlite3_api->bind_text
95356 #define sqlite3_bind_text16 sqlite3_api->bind_text16
95357 #define sqlite3_bind_value sqlite3_api->bind_value
95358 #define sqlite3_busy_handler sqlite3_api->busy_handler
95359 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
95360 #define sqlite3_changes sqlite3_api->changes
95361 #define sqlite3_close sqlite3_api->close
95362 #define sqlite3_collation_needed sqlite3_api->collation_needed
95363 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
95364 #define sqlite3_column_blob sqlite3_api->column_blob
95365 #define sqlite3_column_bytes sqlite3_api->column_bytes
95366 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
95367 #define sqlite3_column_count sqlite3_api->column_count
95368 #define sqlite3_column_database_name sqlite3_api->column_database_name
95369 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
95370 #define sqlite3_column_decltype sqlite3_api->column_decltype
95371 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
95372 #define sqlite3_column_double sqlite3_api->column_double
95373 #define sqlite3_column_int sqlite3_api->column_int
95374 #define sqlite3_column_int64 sqlite3_api->column_int64
95375 #define sqlite3_column_name sqlite3_api->column_name
95376 #define sqlite3_column_name16 sqlite3_api->column_name16
95377 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
95378 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
95379 #define sqlite3_column_table_name sqlite3_api->column_table_name
95380 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
95381 #define sqlite3_column_text sqlite3_api->column_text
95382 #define sqlite3_column_text16 sqlite3_api->column_text16
95383 #define sqlite3_column_type sqlite3_api->column_type
95384 #define sqlite3_column_value sqlite3_api->column_value
95385 #define sqlite3_commit_hook sqlite3_api->commit_hook
95386 #define sqlite3_complete sqlite3_api->complete
95387 #define sqlite3_complete16 sqlite3_api->complete16
95388 #define sqlite3_create_collation sqlite3_api->create_collation
95389 #define sqlite3_create_collation16 sqlite3_api->create_collation16
95390 #define sqlite3_create_function sqlite3_api->create_function
95391 #define sqlite3_create_function16 sqlite3_api->create_function16
95392 #define sqlite3_create_module sqlite3_api->create_module
95393 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
95394 #define sqlite3_data_count sqlite3_api->data_count
95395 #define sqlite3_db_handle sqlite3_api->db_handle
95396 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
95397 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
95398 #define sqlite3_errcode sqlite3_api->errcode
95399 #define sqlite3_errmsg sqlite3_api->errmsg
95400 #define sqlite3_errmsg16 sqlite3_api->errmsg16
95401 #define sqlite3_exec sqlite3_api->exec
95402 #ifndef SQLITE_OMIT_DEPRECATED
95403 #define sqlite3_expired sqlite3_api->expired
95404 #endif
95405 #define sqlite3_finalize sqlite3_api->finalize
95406 #define sqlite3_free sqlite3_api->free
95407 #define sqlite3_free_table sqlite3_api->free_table
95408 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
95409 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
95410 #define sqlite3_get_table sqlite3_api->get_table
95411 #ifndef SQLITE_OMIT_DEPRECATED
95412 #define sqlite3_global_recover sqlite3_api->global_recover
95413 #endif
95414 #define sqlite3_interrupt sqlite3_api->interruptx
95415 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
95416 #define sqlite3_libversion sqlite3_api->libversion
95417 #define sqlite3_libversion_number sqlite3_api->libversion_number
95418 #define sqlite3_malloc sqlite3_api->malloc
95419 #define sqlite3_mprintf sqlite3_api->mprintf
95420 #define sqlite3_open sqlite3_api->open
95421 #define sqlite3_open16 sqlite3_api->open16
95422 #define sqlite3_prepare sqlite3_api->prepare
95423 #define sqlite3_prepare16 sqlite3_api->prepare16
95424 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
95425 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
95426 #define sqlite3_profile sqlite3_api->profile
95427 #define sqlite3_progress_handler sqlite3_api->progress_handler
95428 #define sqlite3_realloc sqlite3_api->realloc
95429 #define sqlite3_reset sqlite3_api->reset
95430 #define sqlite3_result_blob sqlite3_api->result_blob
95431 #define sqlite3_result_double sqlite3_api->result_double
95432 #define sqlite3_result_error sqlite3_api->result_error
95433 #define sqlite3_result_error16 sqlite3_api->result_error16
95434 #define sqlite3_result_int sqlite3_api->result_int
95435 #define sqlite3_result_int64 sqlite3_api->result_int64
95436 #define sqlite3_result_null sqlite3_api->result_null
95437 #define sqlite3_result_text sqlite3_api->result_text
95438 #define sqlite3_result_text16 sqlite3_api->result_text16
95439 #define sqlite3_result_text16be sqlite3_api->result_text16be
95440 #define sqlite3_result_text16le sqlite3_api->result_text16le
95441 #define sqlite3_result_value sqlite3_api->result_value
95442 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
95443 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
95444 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
95445 #define sqlite3_snprintf sqlite3_api->snprintf
95446 #define sqlite3_step sqlite3_api->step
95447 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
95448 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
95449 #define sqlite3_total_changes sqlite3_api->total_changes
95450 #define sqlite3_trace sqlite3_api->trace
95451 #ifndef SQLITE_OMIT_DEPRECATED
95452 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
95453 #endif
95454 #define sqlite3_update_hook sqlite3_api->update_hook
95455 #define sqlite3_user_data sqlite3_api->user_data
95456 #define sqlite3_value_blob sqlite3_api->value_blob
95457 #define sqlite3_value_bytes sqlite3_api->value_bytes
95458 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
95459 #define sqlite3_value_double sqlite3_api->value_double
95460 #define sqlite3_value_int sqlite3_api->value_int
95461 #define sqlite3_value_int64 sqlite3_api->value_int64
95462 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
95463 #define sqlite3_value_text sqlite3_api->value_text
95464 #define sqlite3_value_text16 sqlite3_api->value_text16
95465 #define sqlite3_value_text16be sqlite3_api->value_text16be
95466 #define sqlite3_value_text16le sqlite3_api->value_text16le
95467 #define sqlite3_value_type sqlite3_api->value_type
95468 #define sqlite3_vmprintf sqlite3_api->vmprintf
95469 #define sqlite3_overload_function sqlite3_api->overload_function
95470 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
95471 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
95472 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
95473 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
95474 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
95475 #define sqlite3_blob_close sqlite3_api->blob_close
95476 #define sqlite3_blob_open sqlite3_api->blob_open
95477 #define sqlite3_blob_read sqlite3_api->blob_read
95478 #define sqlite3_blob_write sqlite3_api->blob_write
95479 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
95480 #define sqlite3_file_control sqlite3_api->file_control
95481 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
95482 #define sqlite3_memory_used sqlite3_api->memory_used
95483 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
95484 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
95485 #define sqlite3_mutex_free sqlite3_api->mutex_free
95486 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
95487 #define sqlite3_mutex_try sqlite3_api->mutex_try
95488 #define sqlite3_open_v2 sqlite3_api->open_v2
95489 #define sqlite3_release_memory sqlite3_api->release_memory
95490 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
95491 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
95492 #define sqlite3_sleep sqlite3_api->sleep
95493 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
95494 #define sqlite3_vfs_find sqlite3_api->vfs_find
95495 #define sqlite3_vfs_register sqlite3_api->vfs_register
95496 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
95497 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
95498 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
95499 #define sqlite3_result_error_code sqlite3_api->result_error_code
95500 #define sqlite3_test_control sqlite3_api->test_control
95501 #define sqlite3_randomness sqlite3_api->randomness
95502 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
95503 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
95504 #define sqlite3_limit sqlite3_api->limit
95505 #define sqlite3_next_stmt sqlite3_api->next_stmt
95506 #define sqlite3_sql sqlite3_api->sql
95507 #define sqlite3_status sqlite3_api->status
95508 #define sqlite3_backup_finish sqlite3_api->backup_finish
95509 #define sqlite3_backup_init sqlite3_api->backup_init
95510 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
95511 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
95512 #define sqlite3_backup_step sqlite3_api->backup_step
95513 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
95514 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
95515 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
95516 #define sqlite3_db_config sqlite3_api->db_config
95517 #define sqlite3_db_mutex sqlite3_api->db_mutex
95518 #define sqlite3_db_status sqlite3_api->db_status
95519 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
95520 #define sqlite3_log sqlite3_api->log
95521 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
95522 #define sqlite3_sourceid sqlite3_api->sourceid
95523 #define sqlite3_stmt_status sqlite3_api->stmt_status
95524 #define sqlite3_strnicmp sqlite3_api->strnicmp
95525 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
95526 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
95527 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
95528 #define sqlite3_wal_hook sqlite3_api->wal_hook
95529 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
95530 #define sqlite3_vtab_config sqlite3_api->vtab_config
95531 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
95532 /* Version 3.7.16 and later */
95533 #define sqlite3_close_v2 sqlite3_api->close_v2
95534 #define sqlite3_db_filename sqlite3_api->db_filename
95535 #define sqlite3_db_readonly sqlite3_api->db_readonly
95536 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
95537 #define sqlite3_errstr sqlite3_api->errstr
95538 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
95539 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
95540 #define sqlite3_stricmp sqlite3_api->stricmp
95541 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
95542 #define sqlite3_uri_int64 sqlite3_api->uri_int64
95543 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
95544 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
95545 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
95546 #endif /* SQLITE_CORE */
95548 #ifndef SQLITE_CORE
95549 /* This case when the file really is being compiled as a loadable
95550 ** extension */
95551 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
95552 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
95553 # define SQLITE_EXTENSION_INIT3 \
95554 extern const sqlite3_api_routines *sqlite3_api;
95555 #else
95556 /* This case when the file is being statically linked into the
95557 ** application */
95558 # define SQLITE_EXTENSION_INIT1 /*no-op*/
95559 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
95560 # define SQLITE_EXTENSION_INIT3 /*no-op*/
95561 #endif
95563 #endif /* _SQLITE3EXT_H_ */
95565 /************** End of sqlite3ext.h ******************************************/
95566 /************** Continuing where we left off in loadext.c ********************/
95567 /* #include <string.h> */
95569 #ifndef SQLITE_OMIT_LOAD_EXTENSION
95572 ** Some API routines are omitted when various features are
95573 ** excluded from a build of SQLite. Substitute a NULL pointer
95574 ** for any missing APIs.
95576 #ifndef SQLITE_ENABLE_COLUMN_METADATA
95577 # define sqlite3_column_database_name 0
95578 # define sqlite3_column_database_name16 0
95579 # define sqlite3_column_table_name 0
95580 # define sqlite3_column_table_name16 0
95581 # define sqlite3_column_origin_name 0
95582 # define sqlite3_column_origin_name16 0
95583 # define sqlite3_table_column_metadata 0
95584 #endif
95586 #ifdef SQLITE_OMIT_AUTHORIZATION
95587 # define sqlite3_set_authorizer 0
95588 #endif
95590 #ifdef SQLITE_OMIT_UTF16
95591 # define sqlite3_bind_text16 0
95592 # define sqlite3_collation_needed16 0
95593 # define sqlite3_column_decltype16 0
95594 # define sqlite3_column_name16 0
95595 # define sqlite3_column_text16 0
95596 # define sqlite3_complete16 0
95597 # define sqlite3_create_collation16 0
95598 # define sqlite3_create_function16 0
95599 # define sqlite3_errmsg16 0
95600 # define sqlite3_open16 0
95601 # define sqlite3_prepare16 0
95602 # define sqlite3_prepare16_v2 0
95603 # define sqlite3_result_error16 0
95604 # define sqlite3_result_text16 0
95605 # define sqlite3_result_text16be 0
95606 # define sqlite3_result_text16le 0
95607 # define sqlite3_value_text16 0
95608 # define sqlite3_value_text16be 0
95609 # define sqlite3_value_text16le 0
95610 # define sqlite3_column_database_name16 0
95611 # define sqlite3_column_table_name16 0
95612 # define sqlite3_column_origin_name16 0
95613 #endif
95615 #ifdef SQLITE_OMIT_COMPLETE
95616 # define sqlite3_complete 0
95617 # define sqlite3_complete16 0
95618 #endif
95620 #ifdef SQLITE_OMIT_DECLTYPE
95621 # define sqlite3_column_decltype16 0
95622 # define sqlite3_column_decltype 0
95623 #endif
95625 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
95626 # define sqlite3_progress_handler 0
95627 #endif
95629 #ifdef SQLITE_OMIT_VIRTUALTABLE
95630 # define sqlite3_create_module 0
95631 # define sqlite3_create_module_v2 0
95632 # define sqlite3_declare_vtab 0
95633 # define sqlite3_vtab_config 0
95634 # define sqlite3_vtab_on_conflict 0
95635 #endif
95637 #ifdef SQLITE_OMIT_SHARED_CACHE
95638 # define sqlite3_enable_shared_cache 0
95639 #endif
95641 #ifdef SQLITE_OMIT_TRACE
95642 # define sqlite3_profile 0
95643 # define sqlite3_trace 0
95644 #endif
95646 #ifdef SQLITE_OMIT_GET_TABLE
95647 # define sqlite3_free_table 0
95648 # define sqlite3_get_table 0
95649 #endif
95651 #ifdef SQLITE_OMIT_INCRBLOB
95652 #define sqlite3_bind_zeroblob 0
95653 #define sqlite3_blob_bytes 0
95654 #define sqlite3_blob_close 0
95655 #define sqlite3_blob_open 0
95656 #define sqlite3_blob_read 0
95657 #define sqlite3_blob_write 0
95658 #define sqlite3_blob_reopen 0
95659 #endif
95662 ** The following structure contains pointers to all SQLite API routines.
95663 ** A pointer to this structure is passed into extensions when they are
95664 ** loaded so that the extension can make calls back into the SQLite
95665 ** library.
95667 ** When adding new APIs, add them to the bottom of this structure
95668 ** in order to preserve backwards compatibility.
95670 ** Extensions that use newer APIs should first call the
95671 ** sqlite3_libversion_number() to make sure that the API they
95672 ** intend to use is supported by the library. Extensions should
95673 ** also check to make sure that the pointer to the function is
95674 ** not NULL before calling it.
95676 static const sqlite3_api_routines sqlite3Apis = {
95677 sqlite3_aggregate_context,
95678 #ifndef SQLITE_OMIT_DEPRECATED
95679 sqlite3_aggregate_count,
95680 #else
95682 #endif
95683 sqlite3_bind_blob,
95684 sqlite3_bind_double,
95685 sqlite3_bind_int,
95686 sqlite3_bind_int64,
95687 sqlite3_bind_null,
95688 sqlite3_bind_parameter_count,
95689 sqlite3_bind_parameter_index,
95690 sqlite3_bind_parameter_name,
95691 sqlite3_bind_text,
95692 sqlite3_bind_text16,
95693 sqlite3_bind_value,
95694 sqlite3_busy_handler,
95695 sqlite3_busy_timeout,
95696 sqlite3_changes,
95697 sqlite3_close,
95698 sqlite3_collation_needed,
95699 sqlite3_collation_needed16,
95700 sqlite3_column_blob,
95701 sqlite3_column_bytes,
95702 sqlite3_column_bytes16,
95703 sqlite3_column_count,
95704 sqlite3_column_database_name,
95705 sqlite3_column_database_name16,
95706 sqlite3_column_decltype,
95707 sqlite3_column_decltype16,
95708 sqlite3_column_double,
95709 sqlite3_column_int,
95710 sqlite3_column_int64,
95711 sqlite3_column_name,
95712 sqlite3_column_name16,
95713 sqlite3_column_origin_name,
95714 sqlite3_column_origin_name16,
95715 sqlite3_column_table_name,
95716 sqlite3_column_table_name16,
95717 sqlite3_column_text,
95718 sqlite3_column_text16,
95719 sqlite3_column_type,
95720 sqlite3_column_value,
95721 sqlite3_commit_hook,
95722 sqlite3_complete,
95723 sqlite3_complete16,
95724 sqlite3_create_collation,
95725 sqlite3_create_collation16,
95726 sqlite3_create_function,
95727 sqlite3_create_function16,
95728 sqlite3_create_module,
95729 sqlite3_data_count,
95730 sqlite3_db_handle,
95731 sqlite3_declare_vtab,
95732 sqlite3_enable_shared_cache,
95733 sqlite3_errcode,
95734 sqlite3_errmsg,
95735 sqlite3_errmsg16,
95736 sqlite3_exec,
95737 #ifndef SQLITE_OMIT_DEPRECATED
95738 sqlite3_expired,
95739 #else
95741 #endif
95742 sqlite3_finalize,
95743 sqlite3_free,
95744 sqlite3_free_table,
95745 sqlite3_get_autocommit,
95746 sqlite3_get_auxdata,
95747 sqlite3_get_table,
95748 0, /* Was sqlite3_global_recover(), but that function is deprecated */
95749 sqlite3_interrupt,
95750 sqlite3_last_insert_rowid,
95751 sqlite3_libversion,
95752 sqlite3_libversion_number,
95753 sqlite3_malloc,
95754 sqlite3_mprintf,
95755 sqlite3_open,
95756 sqlite3_open16,
95757 sqlite3_prepare,
95758 sqlite3_prepare16,
95759 sqlite3_profile,
95760 sqlite3_progress_handler,
95761 sqlite3_realloc,
95762 sqlite3_reset,
95763 sqlite3_result_blob,
95764 sqlite3_result_double,
95765 sqlite3_result_error,
95766 sqlite3_result_error16,
95767 sqlite3_result_int,
95768 sqlite3_result_int64,
95769 sqlite3_result_null,
95770 sqlite3_result_text,
95771 sqlite3_result_text16,
95772 sqlite3_result_text16be,
95773 sqlite3_result_text16le,
95774 sqlite3_result_value,
95775 sqlite3_rollback_hook,
95776 sqlite3_set_authorizer,
95777 sqlite3_set_auxdata,
95778 sqlite3_snprintf,
95779 sqlite3_step,
95780 sqlite3_table_column_metadata,
95781 #ifndef SQLITE_OMIT_DEPRECATED
95782 sqlite3_thread_cleanup,
95783 #else
95785 #endif
95786 sqlite3_total_changes,
95787 sqlite3_trace,
95788 #ifndef SQLITE_OMIT_DEPRECATED
95789 sqlite3_transfer_bindings,
95790 #else
95792 #endif
95793 sqlite3_update_hook,
95794 sqlite3_user_data,
95795 sqlite3_value_blob,
95796 sqlite3_value_bytes,
95797 sqlite3_value_bytes16,
95798 sqlite3_value_double,
95799 sqlite3_value_int,
95800 sqlite3_value_int64,
95801 sqlite3_value_numeric_type,
95802 sqlite3_value_text,
95803 sqlite3_value_text16,
95804 sqlite3_value_text16be,
95805 sqlite3_value_text16le,
95806 sqlite3_value_type,
95807 sqlite3_vmprintf,
95809 ** The original API set ends here. All extensions can call any
95810 ** of the APIs above provided that the pointer is not NULL. But
95811 ** before calling APIs that follow, extension should check the
95812 ** sqlite3_libversion_number() to make sure they are dealing with
95813 ** a library that is new enough to support that API.
95814 *************************************************************************
95816 sqlite3_overload_function,
95819 ** Added after 3.3.13
95821 sqlite3_prepare_v2,
95822 sqlite3_prepare16_v2,
95823 sqlite3_clear_bindings,
95826 ** Added for 3.4.1
95828 sqlite3_create_module_v2,
95831 ** Added for 3.5.0
95833 sqlite3_bind_zeroblob,
95834 sqlite3_blob_bytes,
95835 sqlite3_blob_close,
95836 sqlite3_blob_open,
95837 sqlite3_blob_read,
95838 sqlite3_blob_write,
95839 sqlite3_create_collation_v2,
95840 sqlite3_file_control,
95841 sqlite3_memory_highwater,
95842 sqlite3_memory_used,
95843 #ifdef SQLITE_MUTEX_OMIT
95849 #else
95850 sqlite3_mutex_alloc,
95851 sqlite3_mutex_enter,
95852 sqlite3_mutex_free,
95853 sqlite3_mutex_leave,
95854 sqlite3_mutex_try,
95855 #endif
95856 sqlite3_open_v2,
95857 sqlite3_release_memory,
95858 sqlite3_result_error_nomem,
95859 sqlite3_result_error_toobig,
95860 sqlite3_sleep,
95861 sqlite3_soft_heap_limit,
95862 sqlite3_vfs_find,
95863 sqlite3_vfs_register,
95864 sqlite3_vfs_unregister,
95867 ** Added for 3.5.8
95869 sqlite3_threadsafe,
95870 sqlite3_result_zeroblob,
95871 sqlite3_result_error_code,
95872 sqlite3_test_control,
95873 sqlite3_randomness,
95874 sqlite3_context_db_handle,
95877 ** Added for 3.6.0
95879 sqlite3_extended_result_codes,
95880 sqlite3_limit,
95881 sqlite3_next_stmt,
95882 sqlite3_sql,
95883 sqlite3_status,
95886 ** Added for 3.7.4
95888 sqlite3_backup_finish,
95889 sqlite3_backup_init,
95890 sqlite3_backup_pagecount,
95891 sqlite3_backup_remaining,
95892 sqlite3_backup_step,
95893 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95894 sqlite3_compileoption_get,
95895 sqlite3_compileoption_used,
95896 #else
95899 #endif
95900 sqlite3_create_function_v2,
95901 sqlite3_db_config,
95902 sqlite3_db_mutex,
95903 sqlite3_db_status,
95904 sqlite3_extended_errcode,
95905 sqlite3_log,
95906 sqlite3_soft_heap_limit64,
95907 sqlite3_sourceid,
95908 sqlite3_stmt_status,
95909 sqlite3_strnicmp,
95910 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
95911 sqlite3_unlock_notify,
95912 #else
95914 #endif
95915 #ifndef SQLITE_OMIT_WAL
95916 sqlite3_wal_autocheckpoint,
95917 sqlite3_wal_checkpoint,
95918 sqlite3_wal_hook,
95919 #else
95923 #endif
95924 sqlite3_blob_reopen,
95925 sqlite3_vtab_config,
95926 sqlite3_vtab_on_conflict,
95927 sqlite3_close_v2,
95928 sqlite3_db_filename,
95929 sqlite3_db_readonly,
95930 sqlite3_db_release_memory,
95931 sqlite3_errstr,
95932 sqlite3_stmt_busy,
95933 sqlite3_stmt_readonly,
95934 sqlite3_stricmp,
95935 sqlite3_uri_boolean,
95936 sqlite3_uri_int64,
95937 sqlite3_uri_parameter,
95938 sqlite3_vsnprintf,
95939 sqlite3_wal_checkpoint_v2
95943 ** Attempt to load an SQLite extension library contained in the file
95944 ** zFile. The entry point is zProc. zProc may be 0 in which case a
95945 ** default entry point name (sqlite3_extension_init) is used. Use
95946 ** of the default name is recommended.
95948 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
95950 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
95951 ** error message text. The calling function should free this memory
95952 ** by calling sqlite3DbFree(db, ).
95954 static int sqlite3LoadExtension(
95955 sqlite3 *db, /* Load the extension into this database connection */
95956 const char *zFile, /* Name of the shared library containing extension */
95957 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
95958 char **pzErrMsg /* Put error message here if not 0 */
95960 sqlite3_vfs *pVfs = db->pVfs;
95961 void *handle;
95962 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
95963 char *zErrmsg = 0;
95964 const char *zEntry;
95965 char *zAltEntry = 0;
95966 void **aHandle;
95967 int nMsg = 300 + sqlite3Strlen30(zFile);
95968 int ii;
95970 /* Shared library endings to try if zFile cannot be loaded as written */
95971 static const char *azEndings[] = {
95972 #if SQLITE_OS_WIN
95973 "dll"
95974 #elif defined(__APPLE__)
95975 "dylib"
95976 #else
95977 "so"
95978 #endif
95982 if( pzErrMsg ) *pzErrMsg = 0;
95984 /* Ticket #1863. To avoid a creating security problems for older
95985 ** applications that relink against newer versions of SQLite, the
95986 ** ability to run load_extension is turned off by default. One
95987 ** must call sqlite3_enable_load_extension() to turn on extension
95988 ** loading. Otherwise you get the following error.
95990 if( (db->flags & SQLITE_LoadExtension)==0 ){
95991 if( pzErrMsg ){
95992 *pzErrMsg = sqlite3_mprintf("not authorized");
95994 return SQLITE_ERROR;
95997 zEntry = zProc ? zProc : "sqlite3_extension_init";
95999 handle = sqlite3OsDlOpen(pVfs, zFile);
96000 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
96001 for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
96002 char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
96003 if( zAltFile==0 ) return SQLITE_NOMEM;
96004 handle = sqlite3OsDlOpen(pVfs, zAltFile);
96005 sqlite3_free(zAltFile);
96007 #endif
96008 if( handle==0 ){
96009 if( pzErrMsg ){
96010 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
96011 if( zErrmsg ){
96012 sqlite3_snprintf(nMsg, zErrmsg,
96013 "unable to open shared library [%s]", zFile);
96014 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
96017 return SQLITE_ERROR;
96019 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
96020 sqlite3OsDlSym(pVfs, handle, zEntry);
96022 /* If no entry point was specified and the default legacy
96023 ** entry point name "sqlite3_extension_init" was not found, then
96024 ** construct an entry point name "sqlite3_X_init" where the X is
96025 ** replaced by the lowercase value of every ASCII alphabetic
96026 ** character in the filename after the last "/" upto the first ".",
96027 ** and eliding the first three characters if they are "lib".
96028 ** Examples:
96030 ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
96031 ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
96033 if( xInit==0 && zProc==0 ){
96034 int iFile, iEntry, c;
96035 int ncFile = sqlite3Strlen30(zFile);
96036 zAltEntry = sqlite3_malloc(ncFile+30);
96037 if( zAltEntry==0 ){
96038 sqlite3OsDlClose(pVfs, handle);
96039 return SQLITE_NOMEM;
96041 memcpy(zAltEntry, "sqlite3_", 8);
96042 for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
96043 iFile++;
96044 if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
96045 for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
96046 if( sqlite3Isalpha(c) ){
96047 zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
96050 memcpy(zAltEntry+iEntry, "_init", 6);
96051 zEntry = zAltEntry;
96052 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
96053 sqlite3OsDlSym(pVfs, handle, zEntry);
96055 if( xInit==0 ){
96056 if( pzErrMsg ){
96057 nMsg += sqlite3Strlen30(zEntry);
96058 *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
96059 if( zErrmsg ){
96060 sqlite3_snprintf(nMsg, zErrmsg,
96061 "no entry point [%s] in shared library [%s]", zEntry, zFile);
96062 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
96065 sqlite3OsDlClose(pVfs, handle);
96066 sqlite3_free(zAltEntry);
96067 return SQLITE_ERROR;
96069 sqlite3_free(zAltEntry);
96070 if( xInit(db, &zErrmsg, &sqlite3Apis) ){
96071 if( pzErrMsg ){
96072 *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
96074 sqlite3_free(zErrmsg);
96075 sqlite3OsDlClose(pVfs, handle);
96076 return SQLITE_ERROR;
96079 /* Append the new shared library handle to the db->aExtension array. */
96080 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
96081 if( aHandle==0 ){
96082 return SQLITE_NOMEM;
96084 if( db->nExtension>0 ){
96085 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
96087 sqlite3DbFree(db, db->aExtension);
96088 db->aExtension = aHandle;
96090 db->aExtension[db->nExtension++] = handle;
96091 return SQLITE_OK;
96093 SQLITE_API int sqlite3_load_extension(
96094 sqlite3 *db, /* Load the extension into this database connection */
96095 const char *zFile, /* Name of the shared library containing extension */
96096 const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
96097 char **pzErrMsg /* Put error message here if not 0 */
96099 int rc;
96100 sqlite3_mutex_enter(db->mutex);
96101 rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
96102 rc = sqlite3ApiExit(db, rc);
96103 sqlite3_mutex_leave(db->mutex);
96104 return rc;
96108 ** Call this routine when the database connection is closing in order
96109 ** to clean up loaded extensions
96111 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
96112 int i;
96113 assert( sqlite3_mutex_held(db->mutex) );
96114 for(i=0; i<db->nExtension; i++){
96115 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
96117 sqlite3DbFree(db, db->aExtension);
96121 ** Enable or disable extension loading. Extension loading is disabled by
96122 ** default so as not to open security holes in older applications.
96124 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
96125 sqlite3_mutex_enter(db->mutex);
96126 if( onoff ){
96127 db->flags |= SQLITE_LoadExtension;
96128 }else{
96129 db->flags &= ~SQLITE_LoadExtension;
96131 sqlite3_mutex_leave(db->mutex);
96132 return SQLITE_OK;
96135 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
96138 ** The auto-extension code added regardless of whether or not extension
96139 ** loading is supported. We need a dummy sqlite3Apis pointer for that
96140 ** code if regular extension loading is not available. This is that
96141 ** dummy pointer.
96143 #ifdef SQLITE_OMIT_LOAD_EXTENSION
96144 static const sqlite3_api_routines sqlite3Apis = { 0 };
96145 #endif
96149 ** The following object holds the list of automatically loaded
96150 ** extensions.
96152 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
96153 ** mutex must be held while accessing this list.
96155 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
96156 static SQLITE_WSD struct sqlite3AutoExtList {
96157 int nExt; /* Number of entries in aExt[] */
96158 void (**aExt)(void); /* Pointers to the extension init functions */
96159 } sqlite3Autoext = { 0, 0 };
96161 /* The "wsdAutoext" macro will resolve to the autoextension
96162 ** state vector. If writable static data is unsupported on the target,
96163 ** we have to locate the state vector at run-time. In the more common
96164 ** case where writable static data is supported, wsdStat can refer directly
96165 ** to the "sqlite3Autoext" state vector declared above.
96167 #ifdef SQLITE_OMIT_WSD
96168 # define wsdAutoextInit \
96169 sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
96170 # define wsdAutoext x[0]
96171 #else
96172 # define wsdAutoextInit
96173 # define wsdAutoext sqlite3Autoext
96174 #endif
96178 ** Register a statically linked extension that is automatically
96179 ** loaded by every new database connection.
96181 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
96182 int rc = SQLITE_OK;
96183 #ifndef SQLITE_OMIT_AUTOINIT
96184 rc = sqlite3_initialize();
96185 if( rc ){
96186 return rc;
96187 }else
96188 #endif
96190 int i;
96191 #if SQLITE_THREADSAFE
96192 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
96193 #endif
96194 wsdAutoextInit;
96195 sqlite3_mutex_enter(mutex);
96196 for(i=0; i<wsdAutoext.nExt; i++){
96197 if( wsdAutoext.aExt[i]==xInit ) break;
96199 if( i==wsdAutoext.nExt ){
96200 int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
96201 void (**aNew)(void);
96202 aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
96203 if( aNew==0 ){
96204 rc = SQLITE_NOMEM;
96205 }else{
96206 wsdAutoext.aExt = aNew;
96207 wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
96208 wsdAutoext.nExt++;
96211 sqlite3_mutex_leave(mutex);
96212 assert( (rc&0xff)==rc );
96213 return rc;
96218 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
96219 ** set of routines that is invoked for each new database connection, if it
96220 ** is currently on the list. If xInit is not on the list, then this
96221 ** routine is a no-op.
96223 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
96224 ** was not on the list.
96226 SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
96227 #if SQLITE_THREADSAFE
96228 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
96229 #endif
96230 int i;
96231 int n = 0;
96232 wsdAutoextInit;
96233 sqlite3_mutex_enter(mutex);
96234 for(i=wsdAutoext.nExt-1; i>=0; i--){
96235 if( wsdAutoext.aExt[i]==xInit ){
96236 wsdAutoext.nExt--;
96237 wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
96238 n++;
96239 break;
96242 sqlite3_mutex_leave(mutex);
96243 return n;
96247 ** Reset the automatic extension loading mechanism.
96249 SQLITE_API void sqlite3_reset_auto_extension(void){
96250 #ifndef SQLITE_OMIT_AUTOINIT
96251 if( sqlite3_initialize()==SQLITE_OK )
96252 #endif
96254 #if SQLITE_THREADSAFE
96255 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
96256 #endif
96257 wsdAutoextInit;
96258 sqlite3_mutex_enter(mutex);
96259 sqlite3_free(wsdAutoext.aExt);
96260 wsdAutoext.aExt = 0;
96261 wsdAutoext.nExt = 0;
96262 sqlite3_mutex_leave(mutex);
96267 ** Load all automatic extensions.
96269 ** If anything goes wrong, set an error in the database connection.
96271 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
96272 int i;
96273 int go = 1;
96274 int rc;
96275 int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
96277 wsdAutoextInit;
96278 if( wsdAutoext.nExt==0 ){
96279 /* Common case: early out without every having to acquire a mutex */
96280 return;
96282 for(i=0; go; i++){
96283 char *zErrmsg;
96284 #if SQLITE_THREADSAFE
96285 sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
96286 #endif
96287 sqlite3_mutex_enter(mutex);
96288 if( i>=wsdAutoext.nExt ){
96289 xInit = 0;
96290 go = 0;
96291 }else{
96292 xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
96293 wsdAutoext.aExt[i];
96295 sqlite3_mutex_leave(mutex);
96296 zErrmsg = 0;
96297 if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
96298 sqlite3Error(db, rc,
96299 "automatic extension loading failed: %s", zErrmsg);
96300 go = 0;
96302 sqlite3_free(zErrmsg);
96306 /************** End of loadext.c *********************************************/
96307 /************** Begin file pragma.c ******************************************/
96309 ** 2003 April 6
96311 ** The author disclaims copyright to this source code. In place of
96312 ** a legal notice, here is a blessing:
96314 ** May you do good and not evil.
96315 ** May you find forgiveness for yourself and forgive others.
96316 ** May you share freely, never taking more than you give.
96318 *************************************************************************
96319 ** This file contains code used to implement the PRAGMA command.
96322 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
96323 # if defined(__APPLE__)
96324 # define SQLITE_ENABLE_LOCKING_STYLE 1
96325 # else
96326 # define SQLITE_ENABLE_LOCKING_STYLE 0
96327 # endif
96328 #endif
96330 /***************************************************************************
96331 ** The next block of code, including the PragTyp_XXXX macro definitions and
96332 ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
96334 ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
96335 ** that script. Then copy/paste the output in place of the following:
96337 #define PragTyp_HEADER_VALUE 0
96338 #define PragTyp_AUTO_VACUUM 1
96339 #define PragTyp_FLAG 2
96340 #define PragTyp_BUSY_TIMEOUT 3
96341 #define PragTyp_CACHE_SIZE 4
96342 #define PragTyp_CASE_SENSITIVE_LIKE 5
96343 #define PragTyp_COLLATION_LIST 6
96344 #define PragTyp_COMPILE_OPTIONS 7
96345 #define PragTyp_DATA_STORE_DIRECTORY 8
96346 #define PragTyp_DATABASE_LIST 9
96347 #define PragTyp_DEFAULT_CACHE_SIZE 10
96348 #define PragTyp_ENCODING 11
96349 #define PragTyp_FOREIGN_KEY_CHECK 12
96350 #define PragTyp_FOREIGN_KEY_LIST 13
96351 #define PragTyp_INCREMENTAL_VACUUM 14
96352 #define PragTyp_INDEX_INFO 15
96353 #define PragTyp_INDEX_LIST 16
96354 #define PragTyp_INTEGRITY_CHECK 17
96355 #define PragTyp_JOURNAL_MODE 18
96356 #define PragTyp_JOURNAL_SIZE_LIMIT 19
96357 #define PragTyp_LOCK_PROXY_FILE 20
96358 #define PragTyp_LOCKING_MODE 21
96359 #define PragTyp_PAGE_COUNT 22
96360 #define PragTyp_MMAP_SIZE 23
96361 #define PragTyp_PAGE_SIZE 24
96362 #define PragTyp_SECURE_DELETE 25
96363 #define PragTyp_SHRINK_MEMORY 26
96364 #define PragTyp_SOFT_HEAP_LIMIT 27
96365 #define PragTyp_STATS 28
96366 #define PragTyp_SYNCHRONOUS 29
96367 #define PragTyp_TABLE_INFO 30
96368 #define PragTyp_TEMP_STORE 31
96369 #define PragTyp_TEMP_STORE_DIRECTORY 32
96370 #define PragTyp_WAL_AUTOCHECKPOINT 33
96371 #define PragTyp_WAL_CHECKPOINT 34
96372 #define PragTyp_ACTIVATE_EXTENSIONS 35
96373 #define PragTyp_HEXKEY 36
96374 #define PragTyp_KEY 37
96375 #define PragTyp_REKEY 38
96376 #define PragTyp_LOCK_STATUS 39
96377 #define PragTyp_PARSER_TRACE 40
96378 #define PragFlag_NeedSchema 0x01
96379 static const struct sPragmaNames {
96380 const char *const zName; /* Name of pragma */
96381 u8 ePragTyp; /* PragTyp_XXX value */
96382 u8 mPragFlag; /* Zero or more PragFlag_XXX values */
96383 u32 iArg; /* Extra argument */
96384 } aPragmaNames[] = {
96385 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
96386 { /* zName: */ "activate_extensions",
96387 /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
96388 /* ePragFlag: */ 0,
96389 /* iArg: */ 0 },
96390 #endif
96391 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
96392 { /* zName: */ "application_id",
96393 /* ePragTyp: */ PragTyp_HEADER_VALUE,
96394 /* ePragFlag: */ 0,
96395 /* iArg: */ 0 },
96396 #endif
96397 #if !defined(SQLITE_OMIT_AUTOVACUUM)
96398 { /* zName: */ "auto_vacuum",
96399 /* ePragTyp: */ PragTyp_AUTO_VACUUM,
96400 /* ePragFlag: */ PragFlag_NeedSchema,
96401 /* iArg: */ 0 },
96402 #endif
96403 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96404 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
96405 { /* zName: */ "automatic_index",
96406 /* ePragTyp: */ PragTyp_FLAG,
96407 /* ePragFlag: */ 0,
96408 /* iArg: */ SQLITE_AutoIndex },
96409 #endif
96410 #endif
96411 { /* zName: */ "busy_timeout",
96412 /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
96413 /* ePragFlag: */ 0,
96414 /* iArg: */ 0 },
96415 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
96416 { /* zName: */ "cache_size",
96417 /* ePragTyp: */ PragTyp_CACHE_SIZE,
96418 /* ePragFlag: */ PragFlag_NeedSchema,
96419 /* iArg: */ 0 },
96420 #endif
96421 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96422 { /* zName: */ "cache_spill",
96423 /* ePragTyp: */ PragTyp_FLAG,
96424 /* ePragFlag: */ 0,
96425 /* iArg: */ SQLITE_CacheSpill },
96426 #endif
96427 { /* zName: */ "case_sensitive_like",
96428 /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
96429 /* ePragFlag: */ 0,
96430 /* iArg: */ 0 },
96431 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96432 { /* zName: */ "checkpoint_fullfsync",
96433 /* ePragTyp: */ PragTyp_FLAG,
96434 /* ePragFlag: */ 0,
96435 /* iArg: */ SQLITE_CkptFullFSync },
96436 #endif
96437 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
96438 { /* zName: */ "collation_list",
96439 /* ePragTyp: */ PragTyp_COLLATION_LIST,
96440 /* ePragFlag: */ 0,
96441 /* iArg: */ 0 },
96442 #endif
96443 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
96444 { /* zName: */ "compile_options",
96445 /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
96446 /* ePragFlag: */ 0,
96447 /* iArg: */ 0 },
96448 #endif
96449 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96450 { /* zName: */ "count_changes",
96451 /* ePragTyp: */ PragTyp_FLAG,
96452 /* ePragFlag: */ 0,
96453 /* iArg: */ SQLITE_CountRows },
96454 #endif
96455 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
96456 { /* zName: */ "data_store_directory",
96457 /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
96458 /* ePragFlag: */ 0,
96459 /* iArg: */ 0 },
96460 #endif
96461 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
96462 { /* zName: */ "database_list",
96463 /* ePragTyp: */ PragTyp_DATABASE_LIST,
96464 /* ePragFlag: */ PragFlag_NeedSchema,
96465 /* iArg: */ 0 },
96466 #endif
96467 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
96468 { /* zName: */ "default_cache_size",
96469 /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
96470 /* ePragFlag: */ PragFlag_NeedSchema,
96471 /* iArg: */ 0 },
96472 #endif
96473 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96474 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
96475 { /* zName: */ "defer_foreign_keys",
96476 /* ePragTyp: */ PragTyp_FLAG,
96477 /* ePragFlag: */ 0,
96478 /* iArg: */ SQLITE_DeferFKs },
96479 #endif
96480 #endif
96481 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96482 { /* zName: */ "empty_result_callbacks",
96483 /* ePragTyp: */ PragTyp_FLAG,
96484 /* ePragFlag: */ 0,
96485 /* iArg: */ SQLITE_NullCallback },
96486 #endif
96487 #if !defined(SQLITE_OMIT_UTF16)
96488 { /* zName: */ "encoding",
96489 /* ePragTyp: */ PragTyp_ENCODING,
96490 /* ePragFlag: */ 0,
96491 /* iArg: */ 0 },
96492 #endif
96493 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
96494 { /* zName: */ "foreign_key_check",
96495 /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
96496 /* ePragFlag: */ PragFlag_NeedSchema,
96497 /* iArg: */ 0 },
96498 #endif
96499 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
96500 { /* zName: */ "foreign_key_list",
96501 /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
96502 /* ePragFlag: */ PragFlag_NeedSchema,
96503 /* iArg: */ 0 },
96504 #endif
96505 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96506 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
96507 { /* zName: */ "foreign_keys",
96508 /* ePragTyp: */ PragTyp_FLAG,
96509 /* ePragFlag: */ 0,
96510 /* iArg: */ SQLITE_ForeignKeys },
96511 #endif
96512 #endif
96513 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
96514 { /* zName: */ "freelist_count",
96515 /* ePragTyp: */ PragTyp_HEADER_VALUE,
96516 /* ePragFlag: */ 0,
96517 /* iArg: */ 0 },
96518 #endif
96519 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96520 { /* zName: */ "full_column_names",
96521 /* ePragTyp: */ PragTyp_FLAG,
96522 /* ePragFlag: */ 0,
96523 /* iArg: */ SQLITE_FullColNames },
96524 { /* zName: */ "fullfsync",
96525 /* ePragTyp: */ PragTyp_FLAG,
96526 /* ePragFlag: */ 0,
96527 /* iArg: */ SQLITE_FullFSync },
96528 #endif
96529 #if defined(SQLITE_HAS_CODEC)
96530 { /* zName: */ "hexkey",
96531 /* ePragTyp: */ PragTyp_HEXKEY,
96532 /* ePragFlag: */ 0,
96533 /* iArg: */ 0 },
96534 { /* zName: */ "hexrekey",
96535 /* ePragTyp: */ PragTyp_HEXKEY,
96536 /* ePragFlag: */ 0,
96537 /* iArg: */ 0 },
96538 #endif
96539 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96540 #if !defined(SQLITE_OMIT_CHECK)
96541 { /* zName: */ "ignore_check_constraints",
96542 /* ePragTyp: */ PragTyp_FLAG,
96543 /* ePragFlag: */ 0,
96544 /* iArg: */ SQLITE_IgnoreChecks },
96545 #endif
96546 #endif
96547 #if !defined(SQLITE_OMIT_AUTOVACUUM)
96548 { /* zName: */ "incremental_vacuum",
96549 /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
96550 /* ePragFlag: */ PragFlag_NeedSchema,
96551 /* iArg: */ 0 },
96552 #endif
96553 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
96554 { /* zName: */ "index_info",
96555 /* ePragTyp: */ PragTyp_INDEX_INFO,
96556 /* ePragFlag: */ PragFlag_NeedSchema,
96557 /* iArg: */ 0 },
96558 { /* zName: */ "index_list",
96559 /* ePragTyp: */ PragTyp_INDEX_LIST,
96560 /* ePragFlag: */ PragFlag_NeedSchema,
96561 /* iArg: */ 0 },
96562 #endif
96563 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
96564 { /* zName: */ "integrity_check",
96565 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
96566 /* ePragFlag: */ PragFlag_NeedSchema,
96567 /* iArg: */ 0 },
96568 #endif
96569 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
96570 { /* zName: */ "journal_mode",
96571 /* ePragTyp: */ PragTyp_JOURNAL_MODE,
96572 /* ePragFlag: */ PragFlag_NeedSchema,
96573 /* iArg: */ 0 },
96574 { /* zName: */ "journal_size_limit",
96575 /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
96576 /* ePragFlag: */ 0,
96577 /* iArg: */ 0 },
96578 #endif
96579 #if defined(SQLITE_HAS_CODEC)
96580 { /* zName: */ "key",
96581 /* ePragTyp: */ PragTyp_KEY,
96582 /* ePragFlag: */ 0,
96583 /* iArg: */ 0 },
96584 #endif
96585 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96586 { /* zName: */ "legacy_file_format",
96587 /* ePragTyp: */ PragTyp_FLAG,
96588 /* ePragFlag: */ 0,
96589 /* iArg: */ SQLITE_LegacyFileFmt },
96590 #endif
96591 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
96592 { /* zName: */ "lock_proxy_file",
96593 /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
96594 /* ePragFlag: */ 0,
96595 /* iArg: */ 0 },
96596 #endif
96597 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
96598 { /* zName: */ "lock_status",
96599 /* ePragTyp: */ PragTyp_LOCK_STATUS,
96600 /* ePragFlag: */ 0,
96601 /* iArg: */ 0 },
96602 #endif
96603 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
96604 { /* zName: */ "locking_mode",
96605 /* ePragTyp: */ PragTyp_LOCKING_MODE,
96606 /* ePragFlag: */ 0,
96607 /* iArg: */ 0 },
96608 { /* zName: */ "max_page_count",
96609 /* ePragTyp: */ PragTyp_PAGE_COUNT,
96610 /* ePragFlag: */ PragFlag_NeedSchema,
96611 /* iArg: */ 0 },
96612 { /* zName: */ "mmap_size",
96613 /* ePragTyp: */ PragTyp_MMAP_SIZE,
96614 /* ePragFlag: */ 0,
96615 /* iArg: */ 0 },
96616 { /* zName: */ "page_count",
96617 /* ePragTyp: */ PragTyp_PAGE_COUNT,
96618 /* ePragFlag: */ PragFlag_NeedSchema,
96619 /* iArg: */ 0 },
96620 { /* zName: */ "page_size",
96621 /* ePragTyp: */ PragTyp_PAGE_SIZE,
96622 /* ePragFlag: */ 0,
96623 /* iArg: */ 0 },
96624 #endif
96625 #if defined(SQLITE_DEBUG)
96626 { /* zName: */ "parser_trace",
96627 /* ePragTyp: */ PragTyp_PARSER_TRACE,
96628 /* ePragFlag: */ 0,
96629 /* iArg: */ 0 },
96630 #endif
96631 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96632 { /* zName: */ "query_only",
96633 /* ePragTyp: */ PragTyp_FLAG,
96634 /* ePragFlag: */ 0,
96635 /* iArg: */ SQLITE_QueryOnly },
96636 #endif
96637 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
96638 { /* zName: */ "quick_check",
96639 /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
96640 /* ePragFlag: */ PragFlag_NeedSchema,
96641 /* iArg: */ 0 },
96642 #endif
96643 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96644 { /* zName: */ "read_uncommitted",
96645 /* ePragTyp: */ PragTyp_FLAG,
96646 /* ePragFlag: */ 0,
96647 /* iArg: */ SQLITE_ReadUncommitted },
96648 { /* zName: */ "recursive_triggers",
96649 /* ePragTyp: */ PragTyp_FLAG,
96650 /* ePragFlag: */ 0,
96651 /* iArg: */ SQLITE_RecTriggers },
96652 #endif
96653 #if defined(SQLITE_HAS_CODEC)
96654 { /* zName: */ "rekey",
96655 /* ePragTyp: */ PragTyp_REKEY,
96656 /* ePragFlag: */ 0,
96657 /* iArg: */ 0 },
96658 #endif
96659 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96660 { /* zName: */ "reverse_unordered_selects",
96661 /* ePragTyp: */ PragTyp_FLAG,
96662 /* ePragFlag: */ 0,
96663 /* iArg: */ SQLITE_ReverseOrder },
96664 #endif
96665 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
96666 { /* zName: */ "schema_version",
96667 /* ePragTyp: */ PragTyp_HEADER_VALUE,
96668 /* ePragFlag: */ 0,
96669 /* iArg: */ 0 },
96670 #endif
96671 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
96672 { /* zName: */ "secure_delete",
96673 /* ePragTyp: */ PragTyp_SECURE_DELETE,
96674 /* ePragFlag: */ 0,
96675 /* iArg: */ 0 },
96676 #endif
96677 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96678 { /* zName: */ "short_column_names",
96679 /* ePragTyp: */ PragTyp_FLAG,
96680 /* ePragFlag: */ 0,
96681 /* iArg: */ SQLITE_ShortColNames },
96682 #endif
96683 { /* zName: */ "shrink_memory",
96684 /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
96685 /* ePragFlag: */ 0,
96686 /* iArg: */ 0 },
96687 { /* zName: */ "soft_heap_limit",
96688 /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
96689 /* ePragFlag: */ 0,
96690 /* iArg: */ 0 },
96691 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96692 #if defined(SQLITE_DEBUG)
96693 { /* zName: */ "sql_trace",
96694 /* ePragTyp: */ PragTyp_FLAG,
96695 /* ePragFlag: */ 0,
96696 /* iArg: */ SQLITE_SqlTrace },
96697 #endif
96698 #endif
96699 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
96700 { /* zName: */ "stats",
96701 /* ePragTyp: */ PragTyp_STATS,
96702 /* ePragFlag: */ PragFlag_NeedSchema,
96703 /* iArg: */ 0 },
96704 #endif
96705 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
96706 { /* zName: */ "synchronous",
96707 /* ePragTyp: */ PragTyp_SYNCHRONOUS,
96708 /* ePragFlag: */ PragFlag_NeedSchema,
96709 /* iArg: */ 0 },
96710 #endif
96711 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
96712 { /* zName: */ "table_info",
96713 /* ePragTyp: */ PragTyp_TABLE_INFO,
96714 /* ePragFlag: */ PragFlag_NeedSchema,
96715 /* iArg: */ 0 },
96716 #endif
96717 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
96718 { /* zName: */ "temp_store",
96719 /* ePragTyp: */ PragTyp_TEMP_STORE,
96720 /* ePragFlag: */ 0,
96721 /* iArg: */ 0 },
96722 { /* zName: */ "temp_store_directory",
96723 /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
96724 /* ePragFlag: */ 0,
96725 /* iArg: */ 0 },
96726 #endif
96727 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
96728 { /* zName: */ "user_version",
96729 /* ePragTyp: */ PragTyp_HEADER_VALUE,
96730 /* ePragFlag: */ 0,
96731 /* iArg: */ 0 },
96732 #endif
96733 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96734 #if defined(SQLITE_DEBUG)
96735 { /* zName: */ "vdbe_addoptrace",
96736 /* ePragTyp: */ PragTyp_FLAG,
96737 /* ePragFlag: */ 0,
96738 /* iArg: */ SQLITE_VdbeAddopTrace },
96739 { /* zName: */ "vdbe_debug",
96740 /* ePragTyp: */ PragTyp_FLAG,
96741 /* ePragFlag: */ 0,
96742 /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
96743 { /* zName: */ "vdbe_eqp",
96744 /* ePragTyp: */ PragTyp_FLAG,
96745 /* ePragFlag: */ 0,
96746 /* iArg: */ SQLITE_VdbeEQP },
96747 { /* zName: */ "vdbe_listing",
96748 /* ePragTyp: */ PragTyp_FLAG,
96749 /* ePragFlag: */ 0,
96750 /* iArg: */ SQLITE_VdbeListing },
96751 { /* zName: */ "vdbe_trace",
96752 /* ePragTyp: */ PragTyp_FLAG,
96753 /* ePragFlag: */ 0,
96754 /* iArg: */ SQLITE_VdbeTrace },
96755 #endif
96756 #endif
96757 #if !defined(SQLITE_OMIT_WAL)
96758 { /* zName: */ "wal_autocheckpoint",
96759 /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
96760 /* ePragFlag: */ 0,
96761 /* iArg: */ 0 },
96762 { /* zName: */ "wal_checkpoint",
96763 /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
96764 /* ePragFlag: */ PragFlag_NeedSchema,
96765 /* iArg: */ 0 },
96766 #endif
96767 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
96768 { /* zName: */ "writable_schema",
96769 /* ePragTyp: */ PragTyp_FLAG,
96770 /* ePragFlag: */ 0,
96771 /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
96772 #endif
96774 /* Number of pragmas: 56 on by default, 69 total. */
96775 /* End of the automatically generated pragma table.
96776 ***************************************************************************/
96779 ** Interpret the given string as a safety level. Return 0 for OFF,
96780 ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
96781 ** unrecognized string argument. The FULL option is disallowed
96782 ** if the omitFull parameter it 1.
96784 ** Note that the values returned are one less that the values that
96785 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
96786 ** to support legacy SQL code. The safety level used to be boolean
96787 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
96789 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
96790 /* 123456789 123456789 */
96791 static const char zText[] = "onoffalseyestruefull";
96792 static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
96793 static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
96794 static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
96795 int i, n;
96796 if( sqlite3Isdigit(*z) ){
96797 return (u8)sqlite3Atoi(z);
96799 n = sqlite3Strlen30(z);
96800 for(i=0; i<ArraySize(iLength)-omitFull; i++){
96801 if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
96802 return iValue[i];
96805 return dflt;
96809 ** Interpret the given string as a boolean value.
96811 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
96812 return getSafetyLevel(z,1,dflt)!=0;
96815 /* The sqlite3GetBoolean() function is used by other modules but the
96816 ** remainder of this file is specific to PRAGMA processing. So omit
96817 ** the rest of the file if PRAGMAs are omitted from the build.
96819 #if !defined(SQLITE_OMIT_PRAGMA)
96822 ** Interpret the given string as a locking mode value.
96824 static int getLockingMode(const char *z){
96825 if( z ){
96826 if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
96827 if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
96829 return PAGER_LOCKINGMODE_QUERY;
96832 #ifndef SQLITE_OMIT_AUTOVACUUM
96834 ** Interpret the given string as an auto-vacuum mode value.
96836 ** The following strings, "none", "full" and "incremental" are
96837 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
96839 static int getAutoVacuum(const char *z){
96840 int i;
96841 if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
96842 if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
96843 if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
96844 i = sqlite3Atoi(z);
96845 return (u8)((i>=0&&i<=2)?i:0);
96847 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
96849 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
96851 ** Interpret the given string as a temp db location. Return 1 for file
96852 ** backed temporary databases, 2 for the Red-Black tree in memory database
96853 ** and 0 to use the compile-time default.
96855 static int getTempStore(const char *z){
96856 if( z[0]>='0' && z[0]<='2' ){
96857 return z[0] - '0';
96858 }else if( sqlite3StrICmp(z, "file")==0 ){
96859 return 1;
96860 }else if( sqlite3StrICmp(z, "memory")==0 ){
96861 return 2;
96862 }else{
96863 return 0;
96866 #endif /* SQLITE_PAGER_PRAGMAS */
96868 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
96870 ** Invalidate temp storage, either when the temp storage is changed
96871 ** from default, or when 'file' and the temp_store_directory has changed
96873 static int invalidateTempStorage(Parse *pParse){
96874 sqlite3 *db = pParse->db;
96875 if( db->aDb[1].pBt!=0 ){
96876 if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
96877 sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
96878 "from within a transaction");
96879 return SQLITE_ERROR;
96881 sqlite3BtreeClose(db->aDb[1].pBt);
96882 db->aDb[1].pBt = 0;
96883 sqlite3ResetAllSchemasOfConnection(db);
96885 return SQLITE_OK;
96887 #endif /* SQLITE_PAGER_PRAGMAS */
96889 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
96891 ** If the TEMP database is open, close it and mark the database schema
96892 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
96893 ** or DEFAULT_TEMP_STORE pragmas.
96895 static int changeTempStorage(Parse *pParse, const char *zStorageType){
96896 int ts = getTempStore(zStorageType);
96897 sqlite3 *db = pParse->db;
96898 if( db->temp_store==ts ) return SQLITE_OK;
96899 if( invalidateTempStorage( pParse ) != SQLITE_OK ){
96900 return SQLITE_ERROR;
96902 db->temp_store = (u8)ts;
96903 return SQLITE_OK;
96905 #endif /* SQLITE_PAGER_PRAGMAS */
96908 ** Generate code to return a single integer value.
96910 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
96911 Vdbe *v = sqlite3GetVdbe(pParse);
96912 int mem = ++pParse->nMem;
96913 i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
96914 if( pI64 ){
96915 memcpy(pI64, &value, sizeof(value));
96917 sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
96918 sqlite3VdbeSetNumCols(v, 1);
96919 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
96920 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
96925 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
96926 ** set these values for all pagers.
96928 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
96929 static void setAllPagerFlags(sqlite3 *db){
96930 if( db->autoCommit ){
96931 Db *pDb = db->aDb;
96932 int n = db->nDb;
96933 assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
96934 assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
96935 assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
96936 assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
96937 == PAGER_FLAGS_MASK );
96938 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
96939 while( (n--) > 0 ){
96940 if( pDb->pBt ){
96941 sqlite3BtreeSetPagerFlags(pDb->pBt,
96942 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
96944 pDb++;
96948 #else
96949 # define setAllPagerFlags(X) /* no-op */
96950 #endif
96954 ** Return a human-readable name for a constraint resolution action.
96956 #ifndef SQLITE_OMIT_FOREIGN_KEY
96957 static const char *actionName(u8 action){
96958 const char *zName;
96959 switch( action ){
96960 case OE_SetNull: zName = "SET NULL"; break;
96961 case OE_SetDflt: zName = "SET DEFAULT"; break;
96962 case OE_Cascade: zName = "CASCADE"; break;
96963 case OE_Restrict: zName = "RESTRICT"; break;
96964 default: zName = "NO ACTION";
96965 assert( action==OE_None ); break;
96967 return zName;
96969 #endif
96973 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
96974 ** defined in pager.h. This function returns the associated lowercase
96975 ** journal-mode name.
96977 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
96978 static char * const azModeName[] = {
96979 "delete", "persist", "off", "truncate", "memory"
96980 #ifndef SQLITE_OMIT_WAL
96981 , "wal"
96982 #endif
96984 assert( PAGER_JOURNALMODE_DELETE==0 );
96985 assert( PAGER_JOURNALMODE_PERSIST==1 );
96986 assert( PAGER_JOURNALMODE_OFF==2 );
96987 assert( PAGER_JOURNALMODE_TRUNCATE==3 );
96988 assert( PAGER_JOURNALMODE_MEMORY==4 );
96989 assert( PAGER_JOURNALMODE_WAL==5 );
96990 assert( eMode>=0 && eMode<=ArraySize(azModeName) );
96992 if( eMode==ArraySize(azModeName) ) return 0;
96993 return azModeName[eMode];
96997 ** Process a pragma statement.
96999 ** Pragmas are of this form:
97001 ** PRAGMA [database.]id [= value]
97003 ** The identifier might also be a string. The value is a string, and
97004 ** identifier, or a number. If minusFlag is true, then the value is
97005 ** a number that was preceded by a minus sign.
97007 ** If the left side is "database.id" then pId1 is the database name
97008 ** and pId2 is the id. If the left side is just "id" then pId1 is the
97009 ** id and pId2 is any empty string.
97011 SQLITE_PRIVATE void sqlite3Pragma(
97012 Parse *pParse,
97013 Token *pId1, /* First part of [database.]id field */
97014 Token *pId2, /* Second part of [database.]id field, or NULL */
97015 Token *pValue, /* Token for <value>, or NULL */
97016 int minusFlag /* True if a '-' sign preceded <value> */
97018 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
97019 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
97020 const char *zDb = 0; /* The database name */
97021 Token *pId; /* Pointer to <id> token */
97022 char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
97023 int iDb; /* Database index for <database> */
97024 int lwr, upr, mid; /* Binary search bounds */
97025 int rc; /* return value form SQLITE_FCNTL_PRAGMA */
97026 sqlite3 *db = pParse->db; /* The database connection */
97027 Db *pDb; /* The specific database being pragmaed */
97028 Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
97030 if( v==0 ) return;
97031 sqlite3VdbeRunOnlyOnce(v);
97032 pParse->nMem = 2;
97034 /* Interpret the [database.] part of the pragma statement. iDb is the
97035 ** index of the database this pragma is being applied to in db.aDb[]. */
97036 iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
97037 if( iDb<0 ) return;
97038 pDb = &db->aDb[iDb];
97040 /* If the temp database has been explicitly named as part of the
97041 ** pragma, make sure it is open.
97043 if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
97044 return;
97047 zLeft = sqlite3NameFromToken(db, pId);
97048 if( !zLeft ) return;
97049 if( minusFlag ){
97050 zRight = sqlite3MPrintf(db, "-%T", pValue);
97051 }else{
97052 zRight = sqlite3NameFromToken(db, pValue);
97055 assert( pId2 );
97056 zDb = pId2->n>0 ? pDb->zName : 0;
97057 if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
97058 goto pragma_out;
97061 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
97062 ** connection. If it returns SQLITE_OK, then assume that the VFS
97063 ** handled the pragma and generate a no-op prepared statement.
97065 aFcntl[0] = 0;
97066 aFcntl[1] = zLeft;
97067 aFcntl[2] = zRight;
97068 aFcntl[3] = 0;
97069 db->busyHandler.nBusy = 0;
97070 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
97071 if( rc==SQLITE_OK ){
97072 if( aFcntl[0] ){
97073 int mem = ++pParse->nMem;
97074 sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
97075 sqlite3VdbeSetNumCols(v, 1);
97076 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
97077 sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
97078 sqlite3_free(aFcntl[0]);
97080 goto pragma_out;
97082 if( rc!=SQLITE_NOTFOUND ){
97083 if( aFcntl[0] ){
97084 sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
97085 sqlite3_free(aFcntl[0]);
97087 pParse->nErr++;
97088 pParse->rc = rc;
97089 goto pragma_out;
97092 /* Locate the pragma in the lookup table */
97093 lwr = 0;
97094 upr = ArraySize(aPragmaNames)-1;
97095 while( lwr<=upr ){
97096 mid = (lwr+upr)/2;
97097 rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
97098 if( rc==0 ) break;
97099 if( rc<0 ){
97100 upr = mid - 1;
97101 }else{
97102 lwr = mid + 1;
97105 if( lwr>upr ) goto pragma_out;
97107 /* Make sure the database schema is loaded if the pragma requires that */
97108 if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
97109 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
97112 /* Jump to the appropriate pragma handler */
97113 switch( aPragmaNames[mid].ePragTyp ){
97115 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
97117 ** PRAGMA [database.]default_cache_size
97118 ** PRAGMA [database.]default_cache_size=N
97120 ** The first form reports the current persistent setting for the
97121 ** page cache size. The value returned is the maximum number of
97122 ** pages in the page cache. The second form sets both the current
97123 ** page cache size value and the persistent page cache size value
97124 ** stored in the database file.
97126 ** Older versions of SQLite would set the default cache size to a
97127 ** negative number to indicate synchronous=OFF. These days, synchronous
97128 ** is always on by default regardless of the sign of the default cache
97129 ** size. But continue to take the absolute value of the default cache
97130 ** size of historical compatibility.
97132 case PragTyp_DEFAULT_CACHE_SIZE: {
97133 static const VdbeOpList getCacheSize[] = {
97134 { OP_Transaction, 0, 0, 0}, /* 0 */
97135 { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
97136 { OP_IfPos, 1, 8, 0},
97137 { OP_Integer, 0, 2, 0},
97138 { OP_Subtract, 1, 2, 1},
97139 { OP_IfPos, 1, 8, 0},
97140 { OP_Integer, 0, 1, 0}, /* 6 */
97141 { OP_Noop, 0, 0, 0},
97142 { OP_ResultRow, 1, 1, 0},
97144 int addr;
97145 sqlite3VdbeUsesBtree(v, iDb);
97146 if( !zRight ){
97147 sqlite3VdbeSetNumCols(v, 1);
97148 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
97149 pParse->nMem += 2;
97150 addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
97151 sqlite3VdbeChangeP1(v, addr, iDb);
97152 sqlite3VdbeChangeP1(v, addr+1, iDb);
97153 sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
97154 }else{
97155 int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
97156 sqlite3BeginWriteOperation(pParse, 0, iDb);
97157 sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
97158 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
97159 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97160 pDb->pSchema->cache_size = size;
97161 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
97163 break;
97165 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
97167 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
97169 ** PRAGMA [database.]page_size
97170 ** PRAGMA [database.]page_size=N
97172 ** The first form reports the current setting for the
97173 ** database page size in bytes. The second form sets the
97174 ** database page size value. The value can only be set if
97175 ** the database has not yet been created.
97177 case PragTyp_PAGE_SIZE: {
97178 Btree *pBt = pDb->pBt;
97179 assert( pBt!=0 );
97180 if( !zRight ){
97181 int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
97182 returnSingleInt(pParse, "page_size", size);
97183 }else{
97184 /* Malloc may fail when setting the page-size, as there is an internal
97185 ** buffer that the pager module resizes using sqlite3_realloc().
97187 db->nextPagesize = sqlite3Atoi(zRight);
97188 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
97189 db->mallocFailed = 1;
97192 break;
97196 ** PRAGMA [database.]secure_delete
97197 ** PRAGMA [database.]secure_delete=ON/OFF
97199 ** The first form reports the current setting for the
97200 ** secure_delete flag. The second form changes the secure_delete
97201 ** flag setting and reports thenew value.
97203 case PragTyp_SECURE_DELETE: {
97204 Btree *pBt = pDb->pBt;
97205 int b = -1;
97206 assert( pBt!=0 );
97207 if( zRight ){
97208 b = sqlite3GetBoolean(zRight, 0);
97210 if( pId2->n==0 && b>=0 ){
97211 int ii;
97212 for(ii=0; ii<db->nDb; ii++){
97213 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
97216 b = sqlite3BtreeSecureDelete(pBt, b);
97217 returnSingleInt(pParse, "secure_delete", b);
97218 break;
97222 ** PRAGMA [database.]max_page_count
97223 ** PRAGMA [database.]max_page_count=N
97225 ** The first form reports the current setting for the
97226 ** maximum number of pages in the database file. The
97227 ** second form attempts to change this setting. Both
97228 ** forms return the current setting.
97230 ** The absolute value of N is used. This is undocumented and might
97231 ** change. The only purpose is to provide an easy way to test
97232 ** the sqlite3AbsInt32() function.
97234 ** PRAGMA [database.]page_count
97236 ** Return the number of pages in the specified database.
97238 case PragTyp_PAGE_COUNT: {
97239 int iReg;
97240 sqlite3CodeVerifySchema(pParse, iDb);
97241 iReg = ++pParse->nMem;
97242 if( sqlite3Tolower(zLeft[0])=='p' ){
97243 sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
97244 }else{
97245 sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
97246 sqlite3AbsInt32(sqlite3Atoi(zRight)));
97248 sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
97249 sqlite3VdbeSetNumCols(v, 1);
97250 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
97251 break;
97255 ** PRAGMA [database.]locking_mode
97256 ** PRAGMA [database.]locking_mode = (normal|exclusive)
97258 case PragTyp_LOCKING_MODE: {
97259 const char *zRet = "normal";
97260 int eMode = getLockingMode(zRight);
97262 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
97263 /* Simple "PRAGMA locking_mode;" statement. This is a query for
97264 ** the current default locking mode (which may be different to
97265 ** the locking-mode of the main database).
97267 eMode = db->dfltLockMode;
97268 }else{
97269 Pager *pPager;
97270 if( pId2->n==0 ){
97271 /* This indicates that no database name was specified as part
97272 ** of the PRAGMA command. In this case the locking-mode must be
97273 ** set on all attached databases, as well as the main db file.
97275 ** Also, the sqlite3.dfltLockMode variable is set so that
97276 ** any subsequently attached databases also use the specified
97277 ** locking mode.
97279 int ii;
97280 assert(pDb==&db->aDb[0]);
97281 for(ii=2; ii<db->nDb; ii++){
97282 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
97283 sqlite3PagerLockingMode(pPager, eMode);
97285 db->dfltLockMode = (u8)eMode;
97287 pPager = sqlite3BtreePager(pDb->pBt);
97288 eMode = sqlite3PagerLockingMode(pPager, eMode);
97291 assert( eMode==PAGER_LOCKINGMODE_NORMAL
97292 || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
97293 if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
97294 zRet = "exclusive";
97296 sqlite3VdbeSetNumCols(v, 1);
97297 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
97298 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
97299 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
97300 break;
97304 ** PRAGMA [database.]journal_mode
97305 ** PRAGMA [database.]journal_mode =
97306 ** (delete|persist|off|truncate|memory|wal|off)
97308 case PragTyp_JOURNAL_MODE: {
97309 int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
97310 int ii; /* Loop counter */
97312 sqlite3VdbeSetNumCols(v, 1);
97313 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
97315 if( zRight==0 ){
97316 /* If there is no "=MODE" part of the pragma, do a query for the
97317 ** current mode */
97318 eMode = PAGER_JOURNALMODE_QUERY;
97319 }else{
97320 const char *zMode;
97321 int n = sqlite3Strlen30(zRight);
97322 for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
97323 if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
97325 if( !zMode ){
97326 /* If the "=MODE" part does not match any known journal mode,
97327 ** then do a query */
97328 eMode = PAGER_JOURNALMODE_QUERY;
97331 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
97332 /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
97333 iDb = 0;
97334 pId2->n = 1;
97336 for(ii=db->nDb-1; ii>=0; ii--){
97337 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
97338 sqlite3VdbeUsesBtree(v, ii);
97339 sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
97342 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
97343 break;
97347 ** PRAGMA [database.]journal_size_limit
97348 ** PRAGMA [database.]journal_size_limit=N
97350 ** Get or set the size limit on rollback journal files.
97352 case PragTyp_JOURNAL_SIZE_LIMIT: {
97353 Pager *pPager = sqlite3BtreePager(pDb->pBt);
97354 i64 iLimit = -2;
97355 if( zRight ){
97356 sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
97357 if( iLimit<-1 ) iLimit = -1;
97359 iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
97360 returnSingleInt(pParse, "journal_size_limit", iLimit);
97361 break;
97364 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
97367 ** PRAGMA [database.]auto_vacuum
97368 ** PRAGMA [database.]auto_vacuum=N
97370 ** Get or set the value of the database 'auto-vacuum' parameter.
97371 ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
97373 #ifndef SQLITE_OMIT_AUTOVACUUM
97374 case PragTyp_AUTO_VACUUM: {
97375 Btree *pBt = pDb->pBt;
97376 assert( pBt!=0 );
97377 if( !zRight ){
97378 returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
97379 }else{
97380 int eAuto = getAutoVacuum(zRight);
97381 assert( eAuto>=0 && eAuto<=2 );
97382 db->nextAutovac = (u8)eAuto;
97383 /* Call SetAutoVacuum() to set initialize the internal auto and
97384 ** incr-vacuum flags. This is required in case this connection
97385 ** creates the database file. It is important that it is created
97386 ** as an auto-vacuum capable db.
97388 rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
97389 if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
97390 /* When setting the auto_vacuum mode to either "full" or
97391 ** "incremental", write the value of meta[6] in the database
97392 ** file. Before writing to meta[6], check that meta[3] indicates
97393 ** that this really is an auto-vacuum capable database.
97395 static const VdbeOpList setMeta6[] = {
97396 { OP_Transaction, 0, 1, 0}, /* 0 */
97397 { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
97398 { OP_If, 1, 0, 0}, /* 2 */
97399 { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
97400 { OP_Integer, 0, 1, 0}, /* 4 */
97401 { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
97403 int iAddr;
97404 iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
97405 sqlite3VdbeChangeP1(v, iAddr, iDb);
97406 sqlite3VdbeChangeP1(v, iAddr+1, iDb);
97407 sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
97408 sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
97409 sqlite3VdbeChangeP1(v, iAddr+5, iDb);
97410 sqlite3VdbeUsesBtree(v, iDb);
97413 break;
97415 #endif
97418 ** PRAGMA [database.]incremental_vacuum(N)
97420 ** Do N steps of incremental vacuuming on a database.
97422 #ifndef SQLITE_OMIT_AUTOVACUUM
97423 case PragTyp_INCREMENTAL_VACUUM: {
97424 int iLimit, addr;
97425 if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
97426 iLimit = 0x7fffffff;
97428 sqlite3BeginWriteOperation(pParse, 0, iDb);
97429 sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
97430 addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
97431 sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
97432 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
97433 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
97434 sqlite3VdbeJumpHere(v, addr);
97435 break;
97437 #endif
97439 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
97441 ** PRAGMA [database.]cache_size
97442 ** PRAGMA [database.]cache_size=N
97444 ** The first form reports the current local setting for the
97445 ** page cache size. The second form sets the local
97446 ** page cache size value. If N is positive then that is the
97447 ** number of pages in the cache. If N is negative, then the
97448 ** number of pages is adjusted so that the cache uses -N kibibytes
97449 ** of memory.
97451 case PragTyp_CACHE_SIZE: {
97452 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97453 if( !zRight ){
97454 returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
97455 }else{
97456 int size = sqlite3Atoi(zRight);
97457 pDb->pSchema->cache_size = size;
97458 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
97460 break;
97464 ** PRAGMA [database.]mmap_size(N)
97466 ** Used to set mapping size limit. The mapping size limit is
97467 ** used to limit the aggregate size of all memory mapped regions of the
97468 ** database file. If this parameter is set to zero, then memory mapping
97469 ** is not used at all. If N is negative, then the default memory map
97470 ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
97471 ** The parameter N is measured in bytes.
97473 ** This value is advisory. The underlying VFS is free to memory map
97474 ** as little or as much as it wants. Except, if N is set to 0 then the
97475 ** upper layers will never invoke the xFetch interfaces to the VFS.
97477 case PragTyp_MMAP_SIZE: {
97478 sqlite3_int64 sz;
97479 #if SQLITE_MAX_MMAP_SIZE>0
97480 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97481 if( zRight ){
97482 int ii;
97483 sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
97484 if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
97485 if( pId2->n==0 ) db->szMmap = sz;
97486 for(ii=db->nDb-1; ii>=0; ii--){
97487 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
97488 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
97492 sz = -1;
97493 rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
97494 #else
97495 sz = 0;
97496 rc = SQLITE_OK;
97497 #endif
97498 if( rc==SQLITE_OK ){
97499 returnSingleInt(pParse, "mmap_size", sz);
97500 }else if( rc!=SQLITE_NOTFOUND ){
97501 pParse->nErr++;
97502 pParse->rc = rc;
97504 break;
97508 ** PRAGMA temp_store
97509 ** PRAGMA temp_store = "default"|"memory"|"file"
97511 ** Return or set the local value of the temp_store flag. Changing
97512 ** the local value does not make changes to the disk file and the default
97513 ** value will be restored the next time the database is opened.
97515 ** Note that it is possible for the library compile-time options to
97516 ** override this setting
97518 case PragTyp_TEMP_STORE: {
97519 if( !zRight ){
97520 returnSingleInt(pParse, "temp_store", db->temp_store);
97521 }else{
97522 changeTempStorage(pParse, zRight);
97524 break;
97528 ** PRAGMA temp_store_directory
97529 ** PRAGMA temp_store_directory = ""|"directory_name"
97531 ** Return or set the local value of the temp_store_directory flag. Changing
97532 ** the value sets a specific directory to be used for temporary files.
97533 ** Setting to a null string reverts to the default temporary directory search.
97534 ** If temporary directory is changed, then invalidateTempStorage.
97537 case PragTyp_TEMP_STORE_DIRECTORY: {
97538 if( !zRight ){
97539 if( sqlite3_temp_directory ){
97540 sqlite3VdbeSetNumCols(v, 1);
97541 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
97542 "temp_store_directory", SQLITE_STATIC);
97543 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
97544 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
97546 }else{
97547 #ifndef SQLITE_OMIT_WSD
97548 if( zRight[0] ){
97549 int res;
97550 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
97551 if( rc!=SQLITE_OK || res==0 ){
97552 sqlite3ErrorMsg(pParse, "not a writable directory");
97553 goto pragma_out;
97556 if( SQLITE_TEMP_STORE==0
97557 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
97558 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
97560 invalidateTempStorage(pParse);
97562 sqlite3_free(sqlite3_temp_directory);
97563 if( zRight[0] ){
97564 sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
97565 }else{
97566 sqlite3_temp_directory = 0;
97568 #endif /* SQLITE_OMIT_WSD */
97570 break;
97573 #if SQLITE_OS_WIN
97575 ** PRAGMA data_store_directory
97576 ** PRAGMA data_store_directory = ""|"directory_name"
97578 ** Return or set the local value of the data_store_directory flag. Changing
97579 ** the value sets a specific directory to be used for database files that
97580 ** were specified with a relative pathname. Setting to a null string reverts
97581 ** to the default database directory, which for database files specified with
97582 ** a relative path will probably be based on the current directory for the
97583 ** process. Database file specified with an absolute path are not impacted
97584 ** by this setting, regardless of its value.
97587 case PragTyp_DATA_STORE_DIRECTORY: {
97588 if( !zRight ){
97589 if( sqlite3_data_directory ){
97590 sqlite3VdbeSetNumCols(v, 1);
97591 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
97592 "data_store_directory", SQLITE_STATIC);
97593 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
97594 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
97596 }else{
97597 #ifndef SQLITE_OMIT_WSD
97598 if( zRight[0] ){
97599 int res;
97600 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
97601 if( rc!=SQLITE_OK || res==0 ){
97602 sqlite3ErrorMsg(pParse, "not a writable directory");
97603 goto pragma_out;
97606 sqlite3_free(sqlite3_data_directory);
97607 if( zRight[0] ){
97608 sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
97609 }else{
97610 sqlite3_data_directory = 0;
97612 #endif /* SQLITE_OMIT_WSD */
97614 break;
97616 #endif
97618 #if SQLITE_ENABLE_LOCKING_STYLE
97620 ** PRAGMA [database.]lock_proxy_file
97621 ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
97623 ** Return or set the value of the lock_proxy_file flag. Changing
97624 ** the value sets a specific file to be used for database access locks.
97627 case PragTyp_LOCK_PROXY_FILE: {
97628 if( !zRight ){
97629 Pager *pPager = sqlite3BtreePager(pDb->pBt);
97630 char *proxy_file_path = NULL;
97631 sqlite3_file *pFile = sqlite3PagerFile(pPager);
97632 sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
97633 &proxy_file_path);
97635 if( proxy_file_path ){
97636 sqlite3VdbeSetNumCols(v, 1);
97637 sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
97638 "lock_proxy_file", SQLITE_STATIC);
97639 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
97640 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
97642 }else{
97643 Pager *pPager = sqlite3BtreePager(pDb->pBt);
97644 sqlite3_file *pFile = sqlite3PagerFile(pPager);
97645 int res;
97646 if( zRight[0] ){
97647 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
97648 zRight);
97649 } else {
97650 res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
97651 NULL);
97653 if( res!=SQLITE_OK ){
97654 sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
97655 goto pragma_out;
97658 break;
97660 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
97663 ** PRAGMA [database.]synchronous
97664 ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
97666 ** Return or set the local value of the synchronous flag. Changing
97667 ** the local value does not make changes to the disk file and the
97668 ** default value will be restored the next time the database is
97669 ** opened.
97671 case PragTyp_SYNCHRONOUS: {
97672 if( !zRight ){
97673 returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
97674 }else{
97675 if( !db->autoCommit ){
97676 sqlite3ErrorMsg(pParse,
97677 "Safety level may not be changed inside a transaction");
97678 }else{
97679 pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
97680 setAllPagerFlags(db);
97683 break;
97685 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
97687 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
97688 case PragTyp_FLAG: {
97689 if( zRight==0 ){
97690 returnSingleInt(pParse, aPragmaNames[mid].zName,
97691 (db->flags & aPragmaNames[mid].iArg)!=0 );
97692 }else{
97693 int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
97694 if( db->autoCommit==0 ){
97695 /* Foreign key support may not be enabled or disabled while not
97696 ** in auto-commit mode. */
97697 mask &= ~(SQLITE_ForeignKeys);
97700 if( sqlite3GetBoolean(zRight, 0) ){
97701 db->flags |= mask;
97702 }else{
97703 db->flags &= ~mask;
97704 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
97707 /* Many of the flag-pragmas modify the code generated by the SQL
97708 ** compiler (eg. count_changes). So add an opcode to expire all
97709 ** compiled SQL statements after modifying a pragma value.
97711 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
97712 setAllPagerFlags(db);
97714 break;
97716 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
97718 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
97720 ** PRAGMA table_info(<table>)
97722 ** Return a single row for each column of the named table. The columns of
97723 ** the returned data set are:
97725 ** cid: Column id (numbered from left to right, starting at 0)
97726 ** name: Column name
97727 ** type: Column declaration type.
97728 ** notnull: True if 'NOT NULL' is part of column declaration
97729 ** dflt_value: The default value for the column, if any.
97731 case PragTyp_TABLE_INFO: if( zRight ){
97732 Table *pTab;
97733 pTab = sqlite3FindTable(db, zRight, zDb);
97734 if( pTab ){
97735 int i, k;
97736 int nHidden = 0;
97737 Column *pCol;
97738 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
97739 sqlite3VdbeSetNumCols(v, 6);
97740 pParse->nMem = 6;
97741 sqlite3CodeVerifySchema(pParse, iDb);
97742 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
97743 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
97744 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
97745 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
97746 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
97747 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
97748 sqlite3ViewGetColumnNames(pParse, pTab);
97749 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
97750 if( IsHiddenColumn(pCol) ){
97751 nHidden++;
97752 continue;
97754 sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
97755 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
97756 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
97757 pCol->zType ? pCol->zType : "", 0);
97758 sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
97759 if( pCol->zDflt ){
97760 sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
97761 }else{
97762 sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
97764 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
97765 k = 0;
97766 }else if( pPk==0 ){
97767 k = 1;
97768 }else{
97769 for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
97771 sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
97772 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
97776 break;
97778 case PragTyp_STATS: {
97779 Index *pIdx;
97780 HashElem *i;
97781 v = sqlite3GetVdbe(pParse);
97782 sqlite3VdbeSetNumCols(v, 4);
97783 pParse->nMem = 4;
97784 sqlite3CodeVerifySchema(pParse, iDb);
97785 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
97786 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
97787 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
97788 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
97789 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
97790 Table *pTab = sqliteHashData(i);
97791 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
97792 sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
97793 sqlite3VdbeAddOp2(v, OP_Integer,
97794 (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
97795 sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
97796 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
97797 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
97798 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
97799 sqlite3VdbeAddOp2(v, OP_Integer,
97800 (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
97801 sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
97802 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
97806 break;
97808 case PragTyp_INDEX_INFO: if( zRight ){
97809 Index *pIdx;
97810 Table *pTab;
97811 pIdx = sqlite3FindIndex(db, zRight, zDb);
97812 if( pIdx ){
97813 int i;
97814 pTab = pIdx->pTable;
97815 sqlite3VdbeSetNumCols(v, 3);
97816 pParse->nMem = 3;
97817 sqlite3CodeVerifySchema(pParse, iDb);
97818 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
97819 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
97820 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
97821 for(i=0; i<pIdx->nKeyCol; i++){
97822 i16 cnum = pIdx->aiColumn[i];
97823 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
97824 sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
97825 assert( pTab->nCol>cnum );
97826 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
97827 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
97831 break;
97833 case PragTyp_INDEX_LIST: if( zRight ){
97834 Index *pIdx;
97835 Table *pTab;
97836 int i;
97837 pTab = sqlite3FindTable(db, zRight, zDb);
97838 if( pTab ){
97839 v = sqlite3GetVdbe(pParse);
97840 sqlite3VdbeSetNumCols(v, 3);
97841 pParse->nMem = 3;
97842 sqlite3CodeVerifySchema(pParse, iDb);
97843 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
97844 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
97845 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
97846 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
97847 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
97848 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
97849 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
97850 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
97854 break;
97856 case PragTyp_DATABASE_LIST: {
97857 int i;
97858 sqlite3VdbeSetNumCols(v, 3);
97859 pParse->nMem = 3;
97860 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
97861 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
97862 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
97863 for(i=0; i<db->nDb; i++){
97864 if( db->aDb[i].pBt==0 ) continue;
97865 assert( db->aDb[i].zName!=0 );
97866 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
97867 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
97868 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
97869 sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
97870 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
97873 break;
97875 case PragTyp_COLLATION_LIST: {
97876 int i = 0;
97877 HashElem *p;
97878 sqlite3VdbeSetNumCols(v, 2);
97879 pParse->nMem = 2;
97880 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
97881 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
97882 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
97883 CollSeq *pColl = (CollSeq *)sqliteHashData(p);
97884 sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
97885 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
97886 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
97889 break;
97890 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
97892 #ifndef SQLITE_OMIT_FOREIGN_KEY
97893 case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
97894 FKey *pFK;
97895 Table *pTab;
97896 pTab = sqlite3FindTable(db, zRight, zDb);
97897 if( pTab ){
97898 v = sqlite3GetVdbe(pParse);
97899 pFK = pTab->pFKey;
97900 if( pFK ){
97901 int i = 0;
97902 sqlite3VdbeSetNumCols(v, 8);
97903 pParse->nMem = 8;
97904 sqlite3CodeVerifySchema(pParse, iDb);
97905 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
97906 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
97907 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
97908 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
97909 sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
97910 sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
97911 sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
97912 sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
97913 while(pFK){
97914 int j;
97915 for(j=0; j<pFK->nCol; j++){
97916 char *zCol = pFK->aCol[j].zCol;
97917 char *zOnDelete = (char *)actionName(pFK->aAction[0]);
97918 char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
97919 sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
97920 sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
97921 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
97922 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
97923 pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
97924 sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
97925 sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
97926 sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
97927 sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
97928 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
97930 ++i;
97931 pFK = pFK->pNextFrom;
97936 break;
97937 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
97939 #ifndef SQLITE_OMIT_FOREIGN_KEY
97940 #ifndef SQLITE_OMIT_TRIGGER
97941 case PragTyp_FOREIGN_KEY_CHECK: {
97942 FKey *pFK; /* A foreign key constraint */
97943 Table *pTab; /* Child table contain "REFERENCES" keyword */
97944 Table *pParent; /* Parent table that child points to */
97945 Index *pIdx; /* Index in the parent table */
97946 int i; /* Loop counter: Foreign key number for pTab */
97947 int j; /* Loop counter: Field of the foreign key */
97948 HashElem *k; /* Loop counter: Next table in schema */
97949 int x; /* result variable */
97950 int regResult; /* 3 registers to hold a result row */
97951 int regKey; /* Register to hold key for checking the FK */
97952 int regRow; /* Registers to hold a row from pTab */
97953 int addrTop; /* Top of a loop checking foreign keys */
97954 int addrOk; /* Jump here if the key is OK */
97955 int *aiCols; /* child to parent column mapping */
97957 regResult = pParse->nMem+1;
97958 pParse->nMem += 4;
97959 regKey = ++pParse->nMem;
97960 regRow = ++pParse->nMem;
97961 v = sqlite3GetVdbe(pParse);
97962 sqlite3VdbeSetNumCols(v, 4);
97963 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
97964 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
97965 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
97966 sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
97967 sqlite3CodeVerifySchema(pParse, iDb);
97968 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
97969 while( k ){
97970 if( zRight ){
97971 pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
97972 k = 0;
97973 }else{
97974 pTab = (Table*)sqliteHashData(k);
97975 k = sqliteHashNext(k);
97977 if( pTab==0 || pTab->pFKey==0 ) continue;
97978 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
97979 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
97980 sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
97981 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
97982 P4_TRANSIENT);
97983 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
97984 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
97985 if( pParent==0 ) continue;
97986 pIdx = 0;
97987 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
97988 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
97989 if( x==0 ){
97990 if( pIdx==0 ){
97991 sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
97992 }else{
97993 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
97994 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
97996 }else{
97997 k = 0;
97998 break;
98001 assert( pParse->nErr>0 || pFK==0 );
98002 if( pFK ) break;
98003 if( pParse->nTab<i ) pParse->nTab = i;
98004 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
98005 for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
98006 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
98007 pIdx = 0;
98008 aiCols = 0;
98009 if( pParent ){
98010 x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
98011 assert( x==0 );
98013 addrOk = sqlite3VdbeMakeLabel(v);
98014 if( pParent && pIdx==0 ){
98015 int iKey = pFK->aCol[0].iFrom;
98016 assert( iKey>=0 && iKey<pTab->nCol );
98017 if( iKey!=pTab->iPKey ){
98018 sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
98019 sqlite3ColumnDefault(v, pTab, iKey, regRow);
98020 sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
98021 sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
98022 sqlite3VdbeCurrentAddr(v)+3);
98023 }else{
98024 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
98026 sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
98027 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
98028 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
98029 }else{
98030 for(j=0; j<pFK->nCol; j++){
98031 sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
98032 aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
98033 sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
98035 if( pParent ){
98036 sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
98037 sqlite3VdbeChangeP4(v, -1,
98038 sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
98039 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
98042 sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
98043 sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
98044 pFK->zTo, P4_TRANSIENT);
98045 sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
98046 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
98047 sqlite3VdbeResolveLabel(v, addrOk);
98048 sqlite3DbFree(db, aiCols);
98050 sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
98051 sqlite3VdbeJumpHere(v, addrTop);
98054 break;
98055 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
98056 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
98058 #ifndef NDEBUG
98059 case PragTyp_PARSER_TRACE: {
98060 if( zRight ){
98061 if( sqlite3GetBoolean(zRight, 0) ){
98062 sqlite3ParserTrace(stderr, "parser: ");
98063 }else{
98064 sqlite3ParserTrace(0, 0);
98068 break;
98069 #endif
98071 /* Reinstall the LIKE and GLOB functions. The variant of LIKE
98072 ** used will be case sensitive or not depending on the RHS.
98074 case PragTyp_CASE_SENSITIVE_LIKE: {
98075 if( zRight ){
98076 sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
98079 break;
98081 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
98082 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
98083 #endif
98085 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
98086 /* Pragma "quick_check" is reduced version of
98087 ** integrity_check designed to detect most database corruption
98088 ** without most of the overhead of a full integrity-check.
98090 case PragTyp_INTEGRITY_CHECK: {
98091 int i, j, addr, mxErr;
98093 /* Code that appears at the end of the integrity check. If no error
98094 ** messages have been generated, output OK. Otherwise output the
98095 ** error message
98097 static const VdbeOpList endCode[] = {
98098 { OP_AddImm, 1, 0, 0}, /* 0 */
98099 { OP_IfNeg, 1, 0, 0}, /* 1 */
98100 { OP_String8, 0, 3, 0}, /* 2 */
98101 { OP_ResultRow, 3, 1, 0},
98104 int isQuick = (sqlite3Tolower(zLeft[0])=='q');
98106 /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
98107 ** then iDb is set to the index of the database identified by <db>.
98108 ** In this case, the integrity of database iDb only is verified by
98109 ** the VDBE created below.
98111 ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
98112 ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
98113 ** to -1 here, to indicate that the VDBE should verify the integrity
98114 ** of all attached databases. */
98115 assert( iDb>=0 );
98116 assert( iDb==0 || pId2->z );
98117 if( pId2->z==0 ) iDb = -1;
98119 /* Initialize the VDBE program */
98120 pParse->nMem = 6;
98121 sqlite3VdbeSetNumCols(v, 1);
98122 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
98124 /* Set the maximum error count */
98125 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
98126 if( zRight ){
98127 sqlite3GetInt32(zRight, &mxErr);
98128 if( mxErr<=0 ){
98129 mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
98132 sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
98134 /* Do an integrity check on each database file */
98135 for(i=0; i<db->nDb; i++){
98136 HashElem *x;
98137 Hash *pTbls;
98138 int cnt = 0;
98140 if( OMIT_TEMPDB && i==1 ) continue;
98141 if( iDb>=0 && i!=iDb ) continue;
98143 sqlite3CodeVerifySchema(pParse, i);
98144 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
98145 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
98146 sqlite3VdbeJumpHere(v, addr);
98148 /* Do an integrity check of the B-Tree
98150 ** Begin by filling registers 2, 3, ... with the root pages numbers
98151 ** for all tables and indices in the database.
98153 assert( sqlite3SchemaMutexHeld(db, i, 0) );
98154 pTbls = &db->aDb[i].pSchema->tblHash;
98155 for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
98156 Table *pTab = sqliteHashData(x);
98157 Index *pIdx;
98158 if( HasRowid(pTab) ){
98159 sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
98160 VdbeComment((v, "%s", pTab->zName));
98161 cnt++;
98163 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98164 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
98165 VdbeComment((v, "%s", pIdx->zName));
98166 cnt++;
98170 /* Make sure sufficient number of registers have been allocated */
98171 pParse->nMem = MAX( pParse->nMem, cnt+8 );
98173 /* Do the b-tree integrity checks */
98174 sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
98175 sqlite3VdbeChangeP5(v, (u8)i);
98176 addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
98177 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
98178 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
98179 P4_DYNAMIC);
98180 sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
98181 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
98182 sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
98183 sqlite3VdbeJumpHere(v, addr);
98185 /* Make sure all the indices are constructed correctly.
98187 for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
98188 Table *pTab = sqliteHashData(x);
98189 Index *pIdx, *pPk;
98190 Index *pPrior = 0;
98191 int loopTop;
98192 int iDataCur, iIdxCur;
98193 int r1 = -1;
98195 if( pTab->pIndex==0 ) continue;
98196 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
98197 addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
98198 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
98199 sqlite3VdbeJumpHere(v, addr);
98200 sqlite3ExprCacheClear(pParse);
98201 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
98202 1, 0, &iDataCur, &iIdxCur);
98203 sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
98204 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
98205 sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
98207 pParse->nMem = MAX(pParse->nMem, 8+j);
98208 sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0);
98209 loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
98210 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
98211 int jmp2, jmp3, jmp4;
98212 if( pPk==pIdx ) continue;
98213 r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
98214 pPrior, r1);
98215 pPrior = pIdx;
98216 sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
98217 jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, 0, r1,
98218 pIdx->nColumn);
98219 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
98220 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
98221 sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
98222 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, " missing from index ",
98223 P4_STATIC);
98224 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
98225 sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, pIdx->zName, P4_TRANSIENT);
98226 sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
98227 sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
98228 jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
98229 sqlite3VdbeAddOp0(v, OP_Halt);
98230 sqlite3VdbeJumpHere(v, jmp4);
98231 sqlite3VdbeJumpHere(v, jmp2);
98232 sqlite3VdbeResolveLabel(v, jmp3);
98234 sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop);
98235 sqlite3VdbeJumpHere(v, loopTop-1);
98236 #ifndef SQLITE_OMIT_BTREECOUNT
98237 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
98238 "wrong # of entries in index ", P4_STATIC);
98239 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
98240 if( pPk==pIdx ) continue;
98241 addr = sqlite3VdbeCurrentAddr(v);
98242 sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
98243 sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
98244 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
98245 sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3);
98246 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
98247 sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
98248 sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
98249 sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
98251 #endif /* SQLITE_OMIT_BTREECOUNT */
98254 addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
98255 sqlite3VdbeChangeP2(v, addr, -mxErr);
98256 sqlite3VdbeJumpHere(v, addr+1);
98257 sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
98259 break;
98260 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
98262 #ifndef SQLITE_OMIT_UTF16
98264 ** PRAGMA encoding
98265 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
98267 ** In its first form, this pragma returns the encoding of the main
98268 ** database. If the database is not initialized, it is initialized now.
98270 ** The second form of this pragma is a no-op if the main database file
98271 ** has not already been initialized. In this case it sets the default
98272 ** encoding that will be used for the main database file if a new file
98273 ** is created. If an existing main database file is opened, then the
98274 ** default text encoding for the existing database is used.
98276 ** In all cases new databases created using the ATTACH command are
98277 ** created to use the same default text encoding as the main database. If
98278 ** the main database has not been initialized and/or created when ATTACH
98279 ** is executed, this is done before the ATTACH operation.
98281 ** In the second form this pragma sets the text encoding to be used in
98282 ** new database files created using this database handle. It is only
98283 ** useful if invoked immediately after the main database i
98285 case PragTyp_ENCODING: {
98286 static const struct EncName {
98287 char *zName;
98288 u8 enc;
98289 } encnames[] = {
98290 { "UTF8", SQLITE_UTF8 },
98291 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
98292 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
98293 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
98294 { "UTF16le", SQLITE_UTF16LE },
98295 { "UTF16be", SQLITE_UTF16BE },
98296 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
98297 { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
98298 { 0, 0 }
98300 const struct EncName *pEnc;
98301 if( !zRight ){ /* "PRAGMA encoding" */
98302 if( sqlite3ReadSchema(pParse) ) goto pragma_out;
98303 sqlite3VdbeSetNumCols(v, 1);
98304 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
98305 sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
98306 assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
98307 assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
98308 assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
98309 sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
98310 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98311 }else{ /* "PRAGMA encoding = XXX" */
98312 /* Only change the value of sqlite.enc if the database handle is not
98313 ** initialized. If the main database exists, the new sqlite.enc value
98314 ** will be overwritten when the schema is next loaded. If it does not
98315 ** already exists, it will be created to use the new encoding value.
98317 if(
98318 !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
98319 DbHasProperty(db, 0, DB_Empty)
98321 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
98322 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
98323 ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
98324 break;
98327 if( !pEnc->zName ){
98328 sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
98333 break;
98334 #endif /* SQLITE_OMIT_UTF16 */
98336 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
98338 ** PRAGMA [database.]schema_version
98339 ** PRAGMA [database.]schema_version = <integer>
98341 ** PRAGMA [database.]user_version
98342 ** PRAGMA [database.]user_version = <integer>
98344 ** PRAGMA [database.]freelist_count = <integer>
98346 ** PRAGMA [database.]application_id
98347 ** PRAGMA [database.]application_id = <integer>
98349 ** The pragma's schema_version and user_version are used to set or get
98350 ** the value of the schema-version and user-version, respectively. Both
98351 ** the schema-version and the user-version are 32-bit signed integers
98352 ** stored in the database header.
98354 ** The schema-cookie is usually only manipulated internally by SQLite. It
98355 ** is incremented by SQLite whenever the database schema is modified (by
98356 ** creating or dropping a table or index). The schema version is used by
98357 ** SQLite each time a query is executed to ensure that the internal cache
98358 ** of the schema used when compiling the SQL query matches the schema of
98359 ** the database against which the compiled query is actually executed.
98360 ** Subverting this mechanism by using "PRAGMA schema_version" to modify
98361 ** the schema-version is potentially dangerous and may lead to program
98362 ** crashes or database corruption. Use with caution!
98364 ** The user-version is not used internally by SQLite. It may be used by
98365 ** applications for any purpose.
98367 case PragTyp_HEADER_VALUE: {
98368 int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
98369 sqlite3VdbeUsesBtree(v, iDb);
98370 switch( zLeft[0] ){
98371 case 'a': case 'A':
98372 iCookie = BTREE_APPLICATION_ID;
98373 break;
98374 case 'f': case 'F':
98375 iCookie = BTREE_FREE_PAGE_COUNT;
98376 break;
98377 case 's': case 'S':
98378 iCookie = BTREE_SCHEMA_VERSION;
98379 break;
98380 default:
98381 iCookie = BTREE_USER_VERSION;
98382 break;
98385 if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
98386 /* Write the specified cookie value */
98387 static const VdbeOpList setCookie[] = {
98388 { OP_Transaction, 0, 1, 0}, /* 0 */
98389 { OP_Integer, 0, 1, 0}, /* 1 */
98390 { OP_SetCookie, 0, 0, 1}, /* 2 */
98392 int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
98393 sqlite3VdbeChangeP1(v, addr, iDb);
98394 sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
98395 sqlite3VdbeChangeP1(v, addr+2, iDb);
98396 sqlite3VdbeChangeP2(v, addr+2, iCookie);
98397 }else{
98398 /* Read the specified cookie value */
98399 static const VdbeOpList readCookie[] = {
98400 { OP_Transaction, 0, 0, 0}, /* 0 */
98401 { OP_ReadCookie, 0, 1, 0}, /* 1 */
98402 { OP_ResultRow, 1, 1, 0}
98404 int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
98405 sqlite3VdbeChangeP1(v, addr, iDb);
98406 sqlite3VdbeChangeP1(v, addr+1, iDb);
98407 sqlite3VdbeChangeP3(v, addr+1, iCookie);
98408 sqlite3VdbeSetNumCols(v, 1);
98409 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
98412 break;
98413 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
98415 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
98417 ** PRAGMA compile_options
98419 ** Return the names of all compile-time options used in this build,
98420 ** one option per row.
98422 case PragTyp_COMPILE_OPTIONS: {
98423 int i = 0;
98424 const char *zOpt;
98425 sqlite3VdbeSetNumCols(v, 1);
98426 pParse->nMem = 1;
98427 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
98428 while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
98429 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
98430 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
98433 break;
98434 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
98436 #ifndef SQLITE_OMIT_WAL
98438 ** PRAGMA [database.]wal_checkpoint = passive|full|restart
98440 ** Checkpoint the database.
98442 case PragTyp_WAL_CHECKPOINT: {
98443 int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
98444 int eMode = SQLITE_CHECKPOINT_PASSIVE;
98445 if( zRight ){
98446 if( sqlite3StrICmp(zRight, "full")==0 ){
98447 eMode = SQLITE_CHECKPOINT_FULL;
98448 }else if( sqlite3StrICmp(zRight, "restart")==0 ){
98449 eMode = SQLITE_CHECKPOINT_RESTART;
98452 sqlite3VdbeSetNumCols(v, 3);
98453 pParse->nMem = 3;
98454 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
98455 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
98456 sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
98458 sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
98459 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
98461 break;
98464 ** PRAGMA wal_autocheckpoint
98465 ** PRAGMA wal_autocheckpoint = N
98467 ** Configure a database connection to automatically checkpoint a database
98468 ** after accumulating N frames in the log. Or query for the current value
98469 ** of N.
98471 case PragTyp_WAL_AUTOCHECKPOINT: {
98472 if( zRight ){
98473 sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
98475 returnSingleInt(pParse, "wal_autocheckpoint",
98476 db->xWalCallback==sqlite3WalDefaultHook ?
98477 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
98479 break;
98480 #endif
98483 ** PRAGMA shrink_memory
98485 ** This pragma attempts to free as much memory as possible from the
98486 ** current database connection.
98488 case PragTyp_SHRINK_MEMORY: {
98489 sqlite3_db_release_memory(db);
98490 break;
98494 ** PRAGMA busy_timeout
98495 ** PRAGMA busy_timeout = N
98497 ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
98498 ** if one is set. If no busy handler or a different busy handler is set
98499 ** then 0 is returned. Setting the busy_timeout to 0 or negative
98500 ** disables the timeout.
98502 /*case PragTyp_BUSY_TIMEOUT*/ default: {
98503 assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
98504 if( zRight ){
98505 sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
98507 returnSingleInt(pParse, "timeout", db->busyTimeout);
98508 break;
98512 ** PRAGMA soft_heap_limit
98513 ** PRAGMA soft_heap_limit = N
98515 ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
98516 ** use -1.
98518 case PragTyp_SOFT_HEAP_LIMIT: {
98519 sqlite3_int64 N;
98520 if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
98521 sqlite3_soft_heap_limit64(N);
98523 returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
98524 break;
98527 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
98529 ** Report the current state of file logs for all databases
98531 case PragTyp_LOCK_STATUS: {
98532 static const char *const azLockName[] = {
98533 "unlocked", "shared", "reserved", "pending", "exclusive"
98535 int i;
98536 sqlite3VdbeSetNumCols(v, 2);
98537 pParse->nMem = 2;
98538 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
98539 sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
98540 for(i=0; i<db->nDb; i++){
98541 Btree *pBt;
98542 const char *zState = "unknown";
98543 int j;
98544 if( db->aDb[i].zName==0 ) continue;
98545 sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
98546 pBt = db->aDb[i].pBt;
98547 if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
98548 zState = "closed";
98549 }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
98550 SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
98551 zState = azLockName[j];
98553 sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
98554 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
98556 break;
98558 #endif
98560 #ifdef SQLITE_HAS_CODEC
98561 case PragTyp_KEY: {
98562 if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
98563 break;
98565 case PragTyp_REKEY: {
98566 if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
98567 break;
98569 case PragTyp_HEXKEY: {
98570 if( zRight ){
98571 u8 iByte;
98572 int i;
98573 char zKey[40];
98574 for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
98575 iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
98576 if( (i&1)!=0 ) zKey[i/2] = iByte;
98578 if( (zLeft[3] & 0xf)==0xb ){
98579 sqlite3_key_v2(db, zDb, zKey, i/2);
98580 }else{
98581 sqlite3_rekey_v2(db, zDb, zKey, i/2);
98584 break;
98586 #endif
98587 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
98588 case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
98589 #ifdef SQLITE_HAS_CODEC
98590 if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
98591 sqlite3_activate_see(&zRight[4]);
98593 #endif
98594 #ifdef SQLITE_ENABLE_CEROD
98595 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
98596 sqlite3_activate_cerod(&zRight[6]);
98598 #endif
98600 break;
98601 #endif
98603 } /* End of the PRAGMA switch */
98605 pragma_out:
98606 sqlite3DbFree(db, zLeft);
98607 sqlite3DbFree(db, zRight);
98610 #endif /* SQLITE_OMIT_PRAGMA */
98612 /************** End of pragma.c **********************************************/
98613 /************** Begin file prepare.c *****************************************/
98615 ** 2005 May 25
98617 ** The author disclaims copyright to this source code. In place of
98618 ** a legal notice, here is a blessing:
98620 ** May you do good and not evil.
98621 ** May you find forgiveness for yourself and forgive others.
98622 ** May you share freely, never taking more than you give.
98624 *************************************************************************
98625 ** This file contains the implementation of the sqlite3_prepare()
98626 ** interface, and routines that contribute to loading the database schema
98627 ** from disk.
98631 ** Fill the InitData structure with an error message that indicates
98632 ** that the database is corrupt.
98634 static void corruptSchema(
98635 InitData *pData, /* Initialization context */
98636 const char *zObj, /* Object being parsed at the point of error */
98637 const char *zExtra /* Error information */
98639 sqlite3 *db = pData->db;
98640 if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
98641 if( zObj==0 ) zObj = "?";
98642 sqlite3SetString(pData->pzErrMsg, db,
98643 "malformed database schema (%s)", zObj);
98644 if( zExtra ){
98645 *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
98646 "%s - %s", *pData->pzErrMsg, zExtra);
98649 pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
98653 ** This is the callback routine for the code that initializes the
98654 ** database. See sqlite3Init() below for additional information.
98655 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
98657 ** Each callback contains the following information:
98659 ** argv[0] = name of thing being created
98660 ** argv[1] = root page number for table or index. 0 for trigger or view.
98661 ** argv[2] = SQL text for the CREATE statement.
98664 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
98665 InitData *pData = (InitData*)pInit;
98666 sqlite3 *db = pData->db;
98667 int iDb = pData->iDb;
98669 assert( argc==3 );
98670 UNUSED_PARAMETER2(NotUsed, argc);
98671 assert( sqlite3_mutex_held(db->mutex) );
98672 DbClearProperty(db, iDb, DB_Empty);
98673 if( db->mallocFailed ){
98674 corruptSchema(pData, argv[0], 0);
98675 return 1;
98678 assert( iDb>=0 && iDb<db->nDb );
98679 if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
98680 if( argv[1]==0 ){
98681 corruptSchema(pData, argv[0], 0);
98682 }else if( argv[2] && argv[2][0] ){
98683 /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
98684 ** But because db->init.busy is set to 1, no VDBE code is generated
98685 ** or executed. All the parser does is build the internal data
98686 ** structures that describe the table, index, or view.
98688 int rc;
98689 sqlite3_stmt *pStmt;
98690 TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
98692 assert( db->init.busy );
98693 db->init.iDb = iDb;
98694 db->init.newTnum = sqlite3Atoi(argv[1]);
98695 db->init.orphanTrigger = 0;
98696 TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
98697 rc = db->errCode;
98698 assert( (rc&0xFF)==(rcp&0xFF) );
98699 db->init.iDb = 0;
98700 if( SQLITE_OK!=rc ){
98701 if( db->init.orphanTrigger ){
98702 assert( iDb==1 );
98703 }else{
98704 pData->rc = rc;
98705 if( rc==SQLITE_NOMEM ){
98706 db->mallocFailed = 1;
98707 }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
98708 corruptSchema(pData, argv[0], sqlite3_errmsg(db));
98712 sqlite3_finalize(pStmt);
98713 }else if( argv[0]==0 ){
98714 corruptSchema(pData, 0, 0);
98715 }else{
98716 /* If the SQL column is blank it means this is an index that
98717 ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
98718 ** constraint for a CREATE TABLE. The index should have already
98719 ** been created when we processed the CREATE TABLE. All we have
98720 ** to do here is record the root page number for that index.
98722 Index *pIndex;
98723 pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
98724 if( pIndex==0 ){
98725 /* This can occur if there exists an index on a TEMP table which
98726 ** has the same name as another index on a permanent index. Since
98727 ** the permanent table is hidden by the TEMP table, we can also
98728 ** safely ignore the index on the permanent table.
98730 /* Do Nothing */;
98731 }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
98732 corruptSchema(pData, argv[0], "invalid rootpage");
98735 return 0;
98739 ** Attempt to read the database schema and initialize internal
98740 ** data structures for a single database file. The index of the
98741 ** database file is given by iDb. iDb==0 is used for the main
98742 ** database. iDb==1 should never be used. iDb>=2 is used for
98743 ** auxiliary databases. Return one of the SQLITE_ error codes to
98744 ** indicate success or failure.
98746 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
98747 int rc;
98748 int i;
98749 #ifndef SQLITE_OMIT_DEPRECATED
98750 int size;
98751 #endif
98752 Table *pTab;
98753 Db *pDb;
98754 char const *azArg[4];
98755 int meta[5];
98756 InitData initData;
98757 char const *zMasterSchema;
98758 char const *zMasterName;
98759 int openedTransaction = 0;
98762 ** The master database table has a structure like this
98764 static const char master_schema[] =
98765 "CREATE TABLE sqlite_master(\n"
98766 " type text,\n"
98767 " name text,\n"
98768 " tbl_name text,\n"
98769 " rootpage integer,\n"
98770 " sql text\n"
98773 #ifndef SQLITE_OMIT_TEMPDB
98774 static const char temp_master_schema[] =
98775 "CREATE TEMP TABLE sqlite_temp_master(\n"
98776 " type text,\n"
98777 " name text,\n"
98778 " tbl_name text,\n"
98779 " rootpage integer,\n"
98780 " sql text\n"
98783 #else
98784 #define temp_master_schema 0
98785 #endif
98787 assert( iDb>=0 && iDb<db->nDb );
98788 assert( db->aDb[iDb].pSchema );
98789 assert( sqlite3_mutex_held(db->mutex) );
98790 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
98792 /* zMasterSchema and zInitScript are set to point at the master schema
98793 ** and initialisation script appropriate for the database being
98794 ** initialized. zMasterName is the name of the master table.
98796 if( !OMIT_TEMPDB && iDb==1 ){
98797 zMasterSchema = temp_master_schema;
98798 }else{
98799 zMasterSchema = master_schema;
98801 zMasterName = SCHEMA_TABLE(iDb);
98803 /* Construct the schema tables. */
98804 azArg[0] = zMasterName;
98805 azArg[1] = "1";
98806 azArg[2] = zMasterSchema;
98807 azArg[3] = 0;
98808 initData.db = db;
98809 initData.iDb = iDb;
98810 initData.rc = SQLITE_OK;
98811 initData.pzErrMsg = pzErrMsg;
98812 sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
98813 if( initData.rc ){
98814 rc = initData.rc;
98815 goto error_out;
98817 pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
98818 if( ALWAYS(pTab) ){
98819 pTab->tabFlags |= TF_Readonly;
98822 /* Create a cursor to hold the database open
98824 pDb = &db->aDb[iDb];
98825 if( pDb->pBt==0 ){
98826 if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
98827 DbSetProperty(db, 1, DB_SchemaLoaded);
98829 return SQLITE_OK;
98832 /* If there is not already a read-only (or read-write) transaction opened
98833 ** on the b-tree database, open one now. If a transaction is opened, it
98834 ** will be closed before this function returns. */
98835 sqlite3BtreeEnter(pDb->pBt);
98836 if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
98837 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
98838 if( rc!=SQLITE_OK ){
98839 sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
98840 goto initone_error_out;
98842 openedTransaction = 1;
98845 /* Get the database meta information.
98847 ** Meta values are as follows:
98848 ** meta[0] Schema cookie. Changes with each schema change.
98849 ** meta[1] File format of schema layer.
98850 ** meta[2] Size of the page cache.
98851 ** meta[3] Largest rootpage (auto/incr_vacuum mode)
98852 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
98853 ** meta[5] User version
98854 ** meta[6] Incremental vacuum mode
98855 ** meta[7] unused
98856 ** meta[8] unused
98857 ** meta[9] unused
98859 ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
98860 ** the possible values of meta[4].
98862 for(i=0; i<ArraySize(meta); i++){
98863 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
98865 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
98867 /* If opening a non-empty database, check the text encoding. For the
98868 ** main database, set sqlite3.enc to the encoding of the main database.
98869 ** For an attached db, it is an error if the encoding is not the same
98870 ** as sqlite3.enc.
98872 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
98873 if( iDb==0 ){
98874 #ifndef SQLITE_OMIT_UTF16
98875 u8 encoding;
98876 /* If opening the main database, set ENC(db). */
98877 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
98878 if( encoding==0 ) encoding = SQLITE_UTF8;
98879 ENC(db) = encoding;
98880 #else
98881 ENC(db) = SQLITE_UTF8;
98882 #endif
98883 }else{
98884 /* If opening an attached database, the encoding much match ENC(db) */
98885 if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
98886 sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
98887 " text encoding as main database");
98888 rc = SQLITE_ERROR;
98889 goto initone_error_out;
98892 }else{
98893 DbSetProperty(db, iDb, DB_Empty);
98895 pDb->pSchema->enc = ENC(db);
98897 if( pDb->pSchema->cache_size==0 ){
98898 #ifndef SQLITE_OMIT_DEPRECATED
98899 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
98900 if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
98901 pDb->pSchema->cache_size = size;
98902 #else
98903 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
98904 #endif
98905 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
98909 ** file_format==1 Version 3.0.0.
98910 ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
98911 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
98912 ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
98914 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
98915 if( pDb->pSchema->file_format==0 ){
98916 pDb->pSchema->file_format = 1;
98918 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
98919 sqlite3SetString(pzErrMsg, db, "unsupported file format");
98920 rc = SQLITE_ERROR;
98921 goto initone_error_out;
98924 /* Ticket #2804: When we open a database in the newer file format,
98925 ** clear the legacy_file_format pragma flag so that a VACUUM will
98926 ** not downgrade the database and thus invalidate any descending
98927 ** indices that the user might have created.
98929 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
98930 db->flags &= ~SQLITE_LegacyFileFmt;
98933 /* Read the schema information out of the schema tables
98935 assert( db->init.busy );
98937 char *zSql;
98938 zSql = sqlite3MPrintf(db,
98939 "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
98940 db->aDb[iDb].zName, zMasterName);
98941 #ifndef SQLITE_OMIT_AUTHORIZATION
98943 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
98944 xAuth = db->xAuth;
98945 db->xAuth = 0;
98946 #endif
98947 rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
98948 #ifndef SQLITE_OMIT_AUTHORIZATION
98949 db->xAuth = xAuth;
98951 #endif
98952 if( rc==SQLITE_OK ) rc = initData.rc;
98953 sqlite3DbFree(db, zSql);
98954 #ifndef SQLITE_OMIT_ANALYZE
98955 if( rc==SQLITE_OK ){
98956 sqlite3AnalysisLoad(db, iDb);
98958 #endif
98960 if( db->mallocFailed ){
98961 rc = SQLITE_NOMEM;
98962 sqlite3ResetAllSchemasOfConnection(db);
98964 if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
98965 /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
98966 ** the schema loaded, even if errors occurred. In this situation the
98967 ** current sqlite3_prepare() operation will fail, but the following one
98968 ** will attempt to compile the supplied statement against whatever subset
98969 ** of the schema was loaded before the error occurred. The primary
98970 ** purpose of this is to allow access to the sqlite_master table
98971 ** even when its contents have been corrupted.
98973 DbSetProperty(db, iDb, DB_SchemaLoaded);
98974 rc = SQLITE_OK;
98977 /* Jump here for an error that occurs after successfully allocating
98978 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
98979 ** before that point, jump to error_out.
98981 initone_error_out:
98982 if( openedTransaction ){
98983 sqlite3BtreeCommit(pDb->pBt);
98985 sqlite3BtreeLeave(pDb->pBt);
98987 error_out:
98988 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
98989 db->mallocFailed = 1;
98991 return rc;
98995 ** Initialize all database files - the main database file, the file
98996 ** used to store temporary tables, and any additional database files
98997 ** created using ATTACH statements. Return a success code. If an
98998 ** error occurs, write an error message into *pzErrMsg.
99000 ** After a database is initialized, the DB_SchemaLoaded bit is set
99001 ** bit is set in the flags field of the Db structure. If the database
99002 ** file was of zero-length, then the DB_Empty flag is also set.
99004 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
99005 int i, rc;
99006 int commit_internal = !(db->flags&SQLITE_InternChanges);
99008 assert( sqlite3_mutex_held(db->mutex) );
99009 rc = SQLITE_OK;
99010 db->init.busy = 1;
99011 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
99012 if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
99013 rc = sqlite3InitOne(db, i, pzErrMsg);
99014 if( rc ){
99015 sqlite3ResetOneSchema(db, i);
99019 /* Once all the other databases have been initialized, load the schema
99020 ** for the TEMP database. This is loaded last, as the TEMP database
99021 ** schema may contain references to objects in other databases.
99023 #ifndef SQLITE_OMIT_TEMPDB
99024 if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
99025 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
99026 rc = sqlite3InitOne(db, 1, pzErrMsg);
99027 if( rc ){
99028 sqlite3ResetOneSchema(db, 1);
99031 #endif
99033 db->init.busy = 0;
99034 if( rc==SQLITE_OK && commit_internal ){
99035 sqlite3CommitInternalChanges(db);
99038 return rc;
99042 ** This routine is a no-op if the database schema is already initialized.
99043 ** Otherwise, the schema is loaded. An error code is returned.
99045 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
99046 int rc = SQLITE_OK;
99047 sqlite3 *db = pParse->db;
99048 assert( sqlite3_mutex_held(db->mutex) );
99049 if( !db->init.busy ){
99050 rc = sqlite3Init(db, &pParse->zErrMsg);
99052 if( rc!=SQLITE_OK ){
99053 pParse->rc = rc;
99054 pParse->nErr++;
99056 return rc;
99061 ** Check schema cookies in all databases. If any cookie is out
99062 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
99063 ** make no changes to pParse->rc.
99065 static void schemaIsValid(Parse *pParse){
99066 sqlite3 *db = pParse->db;
99067 int iDb;
99068 int rc;
99069 int cookie;
99071 assert( pParse->checkSchema );
99072 assert( sqlite3_mutex_held(db->mutex) );
99073 for(iDb=0; iDb<db->nDb; iDb++){
99074 int openedTransaction = 0; /* True if a transaction is opened */
99075 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
99076 if( pBt==0 ) continue;
99078 /* If there is not already a read-only (or read-write) transaction opened
99079 ** on the b-tree database, open one now. If a transaction is opened, it
99080 ** will be closed immediately after reading the meta-value. */
99081 if( !sqlite3BtreeIsInReadTrans(pBt) ){
99082 rc = sqlite3BtreeBeginTrans(pBt, 0);
99083 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
99084 db->mallocFailed = 1;
99086 if( rc!=SQLITE_OK ) return;
99087 openedTransaction = 1;
99090 /* Read the schema cookie from the database. If it does not match the
99091 ** value stored as part of the in-memory schema representation,
99092 ** set Parse.rc to SQLITE_SCHEMA. */
99093 sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
99094 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99095 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
99096 sqlite3ResetOneSchema(db, iDb);
99097 pParse->rc = SQLITE_SCHEMA;
99100 /* Close the transaction, if one was opened. */
99101 if( openedTransaction ){
99102 sqlite3BtreeCommit(pBt);
99108 ** Convert a schema pointer into the iDb index that indicates
99109 ** which database file in db->aDb[] the schema refers to.
99111 ** If the same database is attached more than once, the first
99112 ** attached database is returned.
99114 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
99115 int i = -1000000;
99117 /* If pSchema is NULL, then return -1000000. This happens when code in
99118 ** expr.c is trying to resolve a reference to a transient table (i.e. one
99119 ** created by a sub-select). In this case the return value of this
99120 ** function should never be used.
99122 ** We return -1000000 instead of the more usual -1 simply because using
99123 ** -1000000 as the incorrect index into db->aDb[] is much
99124 ** more likely to cause a segfault than -1 (of course there are assert()
99125 ** statements too, but it never hurts to play the odds).
99127 assert( sqlite3_mutex_held(db->mutex) );
99128 if( pSchema ){
99129 for(i=0; ALWAYS(i<db->nDb); i++){
99130 if( db->aDb[i].pSchema==pSchema ){
99131 break;
99134 assert( i>=0 && i<db->nDb );
99136 return i;
99140 ** Free all memory allocations in the pParse object
99142 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
99143 if( pParse ){
99144 sqlite3 *db = pParse->db;
99145 sqlite3DbFree(db, pParse->aLabel);
99146 sqlite3ExprListDelete(db, pParse->pConstExpr);
99151 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
99153 static int sqlite3Prepare(
99154 sqlite3 *db, /* Database handle. */
99155 const char *zSql, /* UTF-8 encoded SQL statement. */
99156 int nBytes, /* Length of zSql in bytes. */
99157 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
99158 Vdbe *pReprepare, /* VM being reprepared */
99159 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99160 const char **pzTail /* OUT: End of parsed string */
99162 Parse *pParse; /* Parsing context */
99163 char *zErrMsg = 0; /* Error message */
99164 int rc = SQLITE_OK; /* Result code */
99165 int i; /* Loop counter */
99167 /* Allocate the parsing context */
99168 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
99169 if( pParse==0 ){
99170 rc = SQLITE_NOMEM;
99171 goto end_prepare;
99173 pParse->pReprepare = pReprepare;
99174 assert( ppStmt && *ppStmt==0 );
99175 assert( !db->mallocFailed );
99176 assert( sqlite3_mutex_held(db->mutex) );
99178 /* Check to verify that it is possible to get a read lock on all
99179 ** database schemas. The inability to get a read lock indicates that
99180 ** some other database connection is holding a write-lock, which in
99181 ** turn means that the other connection has made uncommitted changes
99182 ** to the schema.
99184 ** Were we to proceed and prepare the statement against the uncommitted
99185 ** schema changes and if those schema changes are subsequently rolled
99186 ** back and different changes are made in their place, then when this
99187 ** prepared statement goes to run the schema cookie would fail to detect
99188 ** the schema change. Disaster would follow.
99190 ** This thread is currently holding mutexes on all Btrees (because
99191 ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
99192 ** is not possible for another thread to start a new schema change
99193 ** while this routine is running. Hence, we do not need to hold
99194 ** locks on the schema, we just need to make sure nobody else is
99195 ** holding them.
99197 ** Note that setting READ_UNCOMMITTED overrides most lock detection,
99198 ** but it does *not* override schema lock detection, so this all still
99199 ** works even if READ_UNCOMMITTED is set.
99201 for(i=0; i<db->nDb; i++) {
99202 Btree *pBt = db->aDb[i].pBt;
99203 if( pBt ){
99204 assert( sqlite3BtreeHoldsMutex(pBt) );
99205 rc = sqlite3BtreeSchemaLocked(pBt);
99206 if( rc ){
99207 const char *zDb = db->aDb[i].zName;
99208 sqlite3Error(db, rc, "database schema is locked: %s", zDb);
99209 testcase( db->flags & SQLITE_ReadUncommitted );
99210 goto end_prepare;
99215 sqlite3VtabUnlockList(db);
99217 pParse->db = db;
99218 pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
99219 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
99220 char *zSqlCopy;
99221 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
99222 testcase( nBytes==mxLen );
99223 testcase( nBytes==mxLen+1 );
99224 if( nBytes>mxLen ){
99225 sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
99226 rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
99227 goto end_prepare;
99229 zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
99230 if( zSqlCopy ){
99231 sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
99232 sqlite3DbFree(db, zSqlCopy);
99233 pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
99234 }else{
99235 pParse->zTail = &zSql[nBytes];
99237 }else{
99238 sqlite3RunParser(pParse, zSql, &zErrMsg);
99240 assert( 0==pParse->nQueryLoop );
99242 if( db->mallocFailed ){
99243 pParse->rc = SQLITE_NOMEM;
99245 if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
99246 if( pParse->checkSchema ){
99247 schemaIsValid(pParse);
99249 if( db->mallocFailed ){
99250 pParse->rc = SQLITE_NOMEM;
99252 if( pzTail ){
99253 *pzTail = pParse->zTail;
99255 rc = pParse->rc;
99257 #ifndef SQLITE_OMIT_EXPLAIN
99258 if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
99259 static const char * const azColName[] = {
99260 "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
99261 "selectid", "order", "from", "detail"
99263 int iFirst, mx;
99264 if( pParse->explain==2 ){
99265 sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
99266 iFirst = 8;
99267 mx = 12;
99268 }else{
99269 sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
99270 iFirst = 0;
99271 mx = 8;
99273 for(i=iFirst; i<mx; i++){
99274 sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
99275 azColName[i], SQLITE_STATIC);
99278 #endif
99280 if( db->init.busy==0 ){
99281 Vdbe *pVdbe = pParse->pVdbe;
99282 sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
99284 if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
99285 sqlite3VdbeFinalize(pParse->pVdbe);
99286 assert(!(*ppStmt));
99287 }else{
99288 *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
99291 if( zErrMsg ){
99292 sqlite3Error(db, rc, "%s", zErrMsg);
99293 sqlite3DbFree(db, zErrMsg);
99294 }else{
99295 sqlite3Error(db, rc, 0);
99298 /* Delete any TriggerPrg structures allocated while parsing this statement. */
99299 while( pParse->pTriggerPrg ){
99300 TriggerPrg *pT = pParse->pTriggerPrg;
99301 pParse->pTriggerPrg = pT->pNext;
99302 sqlite3DbFree(db, pT);
99305 end_prepare:
99307 sqlite3ParserReset(pParse);
99308 sqlite3StackFree(db, pParse);
99309 rc = sqlite3ApiExit(db, rc);
99310 assert( (rc&db->errMask)==rc );
99311 return rc;
99313 static int sqlite3LockAndPrepare(
99314 sqlite3 *db, /* Database handle. */
99315 const char *zSql, /* UTF-8 encoded SQL statement. */
99316 int nBytes, /* Length of zSql in bytes. */
99317 int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
99318 Vdbe *pOld, /* VM being reprepared */
99319 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99320 const char **pzTail /* OUT: End of parsed string */
99322 int rc;
99323 assert( ppStmt!=0 );
99324 *ppStmt = 0;
99325 if( !sqlite3SafetyCheckOk(db) ){
99326 return SQLITE_MISUSE_BKPT;
99328 sqlite3_mutex_enter(db->mutex);
99329 sqlite3BtreeEnterAll(db);
99330 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
99331 if( rc==SQLITE_SCHEMA ){
99332 sqlite3_finalize(*ppStmt);
99333 rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
99335 sqlite3BtreeLeaveAll(db);
99336 sqlite3_mutex_leave(db->mutex);
99337 assert( rc==SQLITE_OK || *ppStmt==0 );
99338 return rc;
99342 ** Rerun the compilation of a statement after a schema change.
99344 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
99345 ** if the statement cannot be recompiled because another connection has
99346 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
99347 ** occurs, return SQLITE_SCHEMA.
99349 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
99350 int rc;
99351 sqlite3_stmt *pNew;
99352 const char *zSql;
99353 sqlite3 *db;
99355 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
99356 zSql = sqlite3_sql((sqlite3_stmt *)p);
99357 assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
99358 db = sqlite3VdbeDb(p);
99359 assert( sqlite3_mutex_held(db->mutex) );
99360 rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
99361 if( rc ){
99362 if( rc==SQLITE_NOMEM ){
99363 db->mallocFailed = 1;
99365 assert( pNew==0 );
99366 return rc;
99367 }else{
99368 assert( pNew!=0 );
99370 sqlite3VdbeSwap((Vdbe*)pNew, p);
99371 sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
99372 sqlite3VdbeResetStepResult((Vdbe*)pNew);
99373 sqlite3VdbeFinalize((Vdbe*)pNew);
99374 return SQLITE_OK;
99379 ** Two versions of the official API. Legacy and new use. In the legacy
99380 ** version, the original SQL text is not saved in the prepared statement
99381 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
99382 ** sqlite3_step(). In the new version, the original SQL text is retained
99383 ** and the statement is automatically recompiled if an schema change
99384 ** occurs.
99386 SQLITE_API int sqlite3_prepare(
99387 sqlite3 *db, /* Database handle. */
99388 const char *zSql, /* UTF-8 encoded SQL statement. */
99389 int nBytes, /* Length of zSql in bytes. */
99390 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99391 const char **pzTail /* OUT: End of parsed string */
99393 int rc;
99394 rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
99395 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
99396 return rc;
99398 SQLITE_API int sqlite3_prepare_v2(
99399 sqlite3 *db, /* Database handle. */
99400 const char *zSql, /* UTF-8 encoded SQL statement. */
99401 int nBytes, /* Length of zSql in bytes. */
99402 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99403 const char **pzTail /* OUT: End of parsed string */
99405 int rc;
99406 rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
99407 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
99408 return rc;
99412 #ifndef SQLITE_OMIT_UTF16
99414 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
99416 static int sqlite3Prepare16(
99417 sqlite3 *db, /* Database handle. */
99418 const void *zSql, /* UTF-16 encoded SQL statement. */
99419 int nBytes, /* Length of zSql in bytes. */
99420 int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
99421 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99422 const void **pzTail /* OUT: End of parsed string */
99424 /* This function currently works by first transforming the UTF-16
99425 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
99426 ** tricky bit is figuring out the pointer to return in *pzTail.
99428 char *zSql8;
99429 const char *zTail8 = 0;
99430 int rc = SQLITE_OK;
99432 assert( ppStmt );
99433 *ppStmt = 0;
99434 if( !sqlite3SafetyCheckOk(db) ){
99435 return SQLITE_MISUSE_BKPT;
99437 if( nBytes>=0 ){
99438 int sz;
99439 const char *z = (const char*)zSql;
99440 for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
99441 nBytes = sz;
99443 sqlite3_mutex_enter(db->mutex);
99444 zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
99445 if( zSql8 ){
99446 rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
99449 if( zTail8 && pzTail ){
99450 /* If sqlite3_prepare returns a tail pointer, we calculate the
99451 ** equivalent pointer into the UTF-16 string by counting the unicode
99452 ** characters between zSql8 and zTail8, and then returning a pointer
99453 ** the same number of characters into the UTF-16 string.
99455 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
99456 *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
99458 sqlite3DbFree(db, zSql8);
99459 rc = sqlite3ApiExit(db, rc);
99460 sqlite3_mutex_leave(db->mutex);
99461 return rc;
99465 ** Two versions of the official API. Legacy and new use. In the legacy
99466 ** version, the original SQL text is not saved in the prepared statement
99467 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
99468 ** sqlite3_step(). In the new version, the original SQL text is retained
99469 ** and the statement is automatically recompiled if an schema change
99470 ** occurs.
99472 SQLITE_API int sqlite3_prepare16(
99473 sqlite3 *db, /* Database handle. */
99474 const void *zSql, /* UTF-16 encoded SQL statement. */
99475 int nBytes, /* Length of zSql in bytes. */
99476 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99477 const void **pzTail /* OUT: End of parsed string */
99479 int rc;
99480 rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
99481 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
99482 return rc;
99484 SQLITE_API int sqlite3_prepare16_v2(
99485 sqlite3 *db, /* Database handle. */
99486 const void *zSql, /* UTF-16 encoded SQL statement. */
99487 int nBytes, /* Length of zSql in bytes. */
99488 sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
99489 const void **pzTail /* OUT: End of parsed string */
99491 int rc;
99492 rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
99493 assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
99494 return rc;
99497 #endif /* SQLITE_OMIT_UTF16 */
99499 /************** End of prepare.c *********************************************/
99500 /************** Begin file select.c ******************************************/
99502 ** 2001 September 15
99504 ** The author disclaims copyright to this source code. In place of
99505 ** a legal notice, here is a blessing:
99507 ** May you do good and not evil.
99508 ** May you find forgiveness for yourself and forgive others.
99509 ** May you share freely, never taking more than you give.
99511 *************************************************************************
99512 ** This file contains C code routines that are called by the parser
99513 ** to handle SELECT statements in SQLite.
99518 ** Delete all the content of a Select structure but do not deallocate
99519 ** the select structure itself.
99521 static void clearSelect(sqlite3 *db, Select *p){
99522 sqlite3ExprListDelete(db, p->pEList);
99523 sqlite3SrcListDelete(db, p->pSrc);
99524 sqlite3ExprDelete(db, p->pWhere);
99525 sqlite3ExprListDelete(db, p->pGroupBy);
99526 sqlite3ExprDelete(db, p->pHaving);
99527 sqlite3ExprListDelete(db, p->pOrderBy);
99528 sqlite3SelectDelete(db, p->pPrior);
99529 sqlite3ExprDelete(db, p->pLimit);
99530 sqlite3ExprDelete(db, p->pOffset);
99531 sqlite3WithDelete(db, p->pWith);
99535 ** Initialize a SelectDest structure.
99537 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
99538 pDest->eDest = (u8)eDest;
99539 pDest->iSDParm = iParm;
99540 pDest->affSdst = 0;
99541 pDest->iSdst = 0;
99542 pDest->nSdst = 0;
99547 ** Allocate a new Select structure and return a pointer to that
99548 ** structure.
99550 SQLITE_PRIVATE Select *sqlite3SelectNew(
99551 Parse *pParse, /* Parsing context */
99552 ExprList *pEList, /* which columns to include in the result */
99553 SrcList *pSrc, /* the FROM clause -- which tables to scan */
99554 Expr *pWhere, /* the WHERE clause */
99555 ExprList *pGroupBy, /* the GROUP BY clause */
99556 Expr *pHaving, /* the HAVING clause */
99557 ExprList *pOrderBy, /* the ORDER BY clause */
99558 u16 selFlags, /* Flag parameters, such as SF_Distinct */
99559 Expr *pLimit, /* LIMIT value. NULL means not used */
99560 Expr *pOffset /* OFFSET value. NULL means no offset */
99562 Select *pNew;
99563 Select standin;
99564 sqlite3 *db = pParse->db;
99565 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
99566 assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
99567 if( pNew==0 ){
99568 assert( db->mallocFailed );
99569 pNew = &standin;
99570 memset(pNew, 0, sizeof(*pNew));
99572 if( pEList==0 ){
99573 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
99575 pNew->pEList = pEList;
99576 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
99577 pNew->pSrc = pSrc;
99578 pNew->pWhere = pWhere;
99579 pNew->pGroupBy = pGroupBy;
99580 pNew->pHaving = pHaving;
99581 pNew->pOrderBy = pOrderBy;
99582 pNew->selFlags = selFlags;
99583 pNew->op = TK_SELECT;
99584 pNew->pLimit = pLimit;
99585 pNew->pOffset = pOffset;
99586 assert( pOffset==0 || pLimit!=0 );
99587 pNew->addrOpenEphm[0] = -1;
99588 pNew->addrOpenEphm[1] = -1;
99589 pNew->addrOpenEphm[2] = -1;
99590 if( db->mallocFailed ) {
99591 clearSelect(db, pNew);
99592 if( pNew!=&standin ) sqlite3DbFree(db, pNew);
99593 pNew = 0;
99594 }else{
99595 assert( pNew->pSrc!=0 || pParse->nErr>0 );
99597 assert( pNew!=&standin );
99598 return pNew;
99602 ** Delete the given Select structure and all of its substructures.
99604 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
99605 if( p ){
99606 clearSelect(db, p);
99607 sqlite3DbFree(db, p);
99612 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
99613 ** type of join. Return an integer constant that expresses that type
99614 ** in terms of the following bit values:
99616 ** JT_INNER
99617 ** JT_CROSS
99618 ** JT_OUTER
99619 ** JT_NATURAL
99620 ** JT_LEFT
99621 ** JT_RIGHT
99623 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
99625 ** If an illegal or unsupported join type is seen, then still return
99626 ** a join type, but put an error in the pParse structure.
99628 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
99629 int jointype = 0;
99630 Token *apAll[3];
99631 Token *p;
99632 /* 0123456789 123456789 123456789 123 */
99633 static const char zKeyText[] = "naturaleftouterightfullinnercross";
99634 static const struct {
99635 u8 i; /* Beginning of keyword text in zKeyText[] */
99636 u8 nChar; /* Length of the keyword in characters */
99637 u8 code; /* Join type mask */
99638 } aKeyword[] = {
99639 /* natural */ { 0, 7, JT_NATURAL },
99640 /* left */ { 6, 4, JT_LEFT|JT_OUTER },
99641 /* outer */ { 10, 5, JT_OUTER },
99642 /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
99643 /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
99644 /* inner */ { 23, 5, JT_INNER },
99645 /* cross */ { 28, 5, JT_INNER|JT_CROSS },
99647 int i, j;
99648 apAll[0] = pA;
99649 apAll[1] = pB;
99650 apAll[2] = pC;
99651 for(i=0; i<3 && apAll[i]; i++){
99652 p = apAll[i];
99653 for(j=0; j<ArraySize(aKeyword); j++){
99654 if( p->n==aKeyword[j].nChar
99655 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
99656 jointype |= aKeyword[j].code;
99657 break;
99660 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
99661 if( j>=ArraySize(aKeyword) ){
99662 jointype |= JT_ERROR;
99663 break;
99667 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
99668 (jointype & JT_ERROR)!=0
99670 const char *zSp = " ";
99671 assert( pB!=0 );
99672 if( pC==0 ){ zSp++; }
99673 sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
99674 "%T %T%s%T", pA, pB, zSp, pC);
99675 jointype = JT_INNER;
99676 }else if( (jointype & JT_OUTER)!=0
99677 && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
99678 sqlite3ErrorMsg(pParse,
99679 "RIGHT and FULL OUTER JOINs are not currently supported");
99680 jointype = JT_INNER;
99682 return jointype;
99686 ** Return the index of a column in a table. Return -1 if the column
99687 ** is not contained in the table.
99689 static int columnIndex(Table *pTab, const char *zCol){
99690 int i;
99691 for(i=0; i<pTab->nCol; i++){
99692 if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
99694 return -1;
99698 ** Search the first N tables in pSrc, from left to right, looking for a
99699 ** table that has a column named zCol.
99701 ** When found, set *piTab and *piCol to the table index and column index
99702 ** of the matching column and return TRUE.
99704 ** If not found, return FALSE.
99706 static int tableAndColumnIndex(
99707 SrcList *pSrc, /* Array of tables to search */
99708 int N, /* Number of tables in pSrc->a[] to search */
99709 const char *zCol, /* Name of the column we are looking for */
99710 int *piTab, /* Write index of pSrc->a[] here */
99711 int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
99713 int i; /* For looping over tables in pSrc */
99714 int iCol; /* Index of column matching zCol */
99716 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
99717 for(i=0; i<N; i++){
99718 iCol = columnIndex(pSrc->a[i].pTab, zCol);
99719 if( iCol>=0 ){
99720 if( piTab ){
99721 *piTab = i;
99722 *piCol = iCol;
99724 return 1;
99727 return 0;
99731 ** This function is used to add terms implied by JOIN syntax to the
99732 ** WHERE clause expression of a SELECT statement. The new term, which
99733 ** is ANDed with the existing WHERE clause, is of the form:
99735 ** (tab1.col1 = tab2.col2)
99737 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
99738 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
99739 ** column iColRight of tab2.
99741 static void addWhereTerm(
99742 Parse *pParse, /* Parsing context */
99743 SrcList *pSrc, /* List of tables in FROM clause */
99744 int iLeft, /* Index of first table to join in pSrc */
99745 int iColLeft, /* Index of column in first table */
99746 int iRight, /* Index of second table in pSrc */
99747 int iColRight, /* Index of column in second table */
99748 int isOuterJoin, /* True if this is an OUTER join */
99749 Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
99751 sqlite3 *db = pParse->db;
99752 Expr *pE1;
99753 Expr *pE2;
99754 Expr *pEq;
99756 assert( iLeft<iRight );
99757 assert( pSrc->nSrc>iRight );
99758 assert( pSrc->a[iLeft].pTab );
99759 assert( pSrc->a[iRight].pTab );
99761 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
99762 pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
99764 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
99765 if( pEq && isOuterJoin ){
99766 ExprSetProperty(pEq, EP_FromJoin);
99767 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
99768 ExprSetVVAProperty(pEq, EP_NoReduce);
99769 pEq->iRightJoinTable = (i16)pE2->iTable;
99771 *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
99775 ** Set the EP_FromJoin property on all terms of the given expression.
99776 ** And set the Expr.iRightJoinTable to iTable for every term in the
99777 ** expression.
99779 ** The EP_FromJoin property is used on terms of an expression to tell
99780 ** the LEFT OUTER JOIN processing logic that this term is part of the
99781 ** join restriction specified in the ON or USING clause and not a part
99782 ** of the more general WHERE clause. These terms are moved over to the
99783 ** WHERE clause during join processing but we need to remember that they
99784 ** originated in the ON or USING clause.
99786 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
99787 ** expression depends on table iRightJoinTable even if that table is not
99788 ** explicitly mentioned in the expression. That information is needed
99789 ** for cases like this:
99791 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
99793 ** The where clause needs to defer the handling of the t1.x=5
99794 ** term until after the t2 loop of the join. In that way, a
99795 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
99796 ** defer the handling of t1.x=5, it will be processed immediately
99797 ** after the t1 loop and rows with t1.x!=5 will never appear in
99798 ** the output, which is incorrect.
99800 static void setJoinExpr(Expr *p, int iTable){
99801 while( p ){
99802 ExprSetProperty(p, EP_FromJoin);
99803 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
99804 ExprSetVVAProperty(p, EP_NoReduce);
99805 p->iRightJoinTable = (i16)iTable;
99806 setJoinExpr(p->pLeft, iTable);
99807 p = p->pRight;
99812 ** This routine processes the join information for a SELECT statement.
99813 ** ON and USING clauses are converted into extra terms of the WHERE clause.
99814 ** NATURAL joins also create extra WHERE clause terms.
99816 ** The terms of a FROM clause are contained in the Select.pSrc structure.
99817 ** The left most table is the first entry in Select.pSrc. The right-most
99818 ** table is the last entry. The join operator is held in the entry to
99819 ** the left. Thus entry 0 contains the join operator for the join between
99820 ** entries 0 and 1. Any ON or USING clauses associated with the join are
99821 ** also attached to the left entry.
99823 ** This routine returns the number of errors encountered.
99825 static int sqliteProcessJoin(Parse *pParse, Select *p){
99826 SrcList *pSrc; /* All tables in the FROM clause */
99827 int i, j; /* Loop counters */
99828 struct SrcList_item *pLeft; /* Left table being joined */
99829 struct SrcList_item *pRight; /* Right table being joined */
99831 pSrc = p->pSrc;
99832 pLeft = &pSrc->a[0];
99833 pRight = &pLeft[1];
99834 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
99835 Table *pLeftTab = pLeft->pTab;
99836 Table *pRightTab = pRight->pTab;
99837 int isOuter;
99839 if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
99840 isOuter = (pRight->jointype & JT_OUTER)!=0;
99842 /* When the NATURAL keyword is present, add WHERE clause terms for
99843 ** every column that the two tables have in common.
99845 if( pRight->jointype & JT_NATURAL ){
99846 if( pRight->pOn || pRight->pUsing ){
99847 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
99848 "an ON or USING clause", 0);
99849 return 1;
99851 for(j=0; j<pRightTab->nCol; j++){
99852 char *zName; /* Name of column in the right table */
99853 int iLeft; /* Matching left table */
99854 int iLeftCol; /* Matching column in the left table */
99856 zName = pRightTab->aCol[j].zName;
99857 if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
99858 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
99859 isOuter, &p->pWhere);
99864 /* Disallow both ON and USING clauses in the same join
99866 if( pRight->pOn && pRight->pUsing ){
99867 sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
99868 "clauses in the same join");
99869 return 1;
99872 /* Add the ON clause to the end of the WHERE clause, connected by
99873 ** an AND operator.
99875 if( pRight->pOn ){
99876 if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
99877 p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
99878 pRight->pOn = 0;
99881 /* Create extra terms on the WHERE clause for each column named
99882 ** in the USING clause. Example: If the two tables to be joined are
99883 ** A and B and the USING clause names X, Y, and Z, then add this
99884 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
99885 ** Report an error if any column mentioned in the USING clause is
99886 ** not contained in both tables to be joined.
99888 if( pRight->pUsing ){
99889 IdList *pList = pRight->pUsing;
99890 for(j=0; j<pList->nId; j++){
99891 char *zName; /* Name of the term in the USING clause */
99892 int iLeft; /* Table on the left with matching column name */
99893 int iLeftCol; /* Column number of matching column on the left */
99894 int iRightCol; /* Column number of matching column on the right */
99896 zName = pList->a[j].zName;
99897 iRightCol = columnIndex(pRightTab, zName);
99898 if( iRightCol<0
99899 || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
99901 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
99902 "not present in both tables", zName);
99903 return 1;
99905 addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
99906 isOuter, &p->pWhere);
99910 return 0;
99914 ** Insert code into "v" that will push the record on the top of the
99915 ** stack into the sorter.
99917 static void pushOntoSorter(
99918 Parse *pParse, /* Parser context */
99919 ExprList *pOrderBy, /* The ORDER BY clause */
99920 Select *pSelect, /* The whole SELECT statement */
99921 int regData /* Register holding data to be sorted */
99923 Vdbe *v = pParse->pVdbe;
99924 int nExpr = pOrderBy->nExpr;
99925 int regBase = sqlite3GetTempRange(pParse, nExpr+2);
99926 int regRecord = sqlite3GetTempReg(pParse);
99927 int op;
99928 sqlite3ExprCacheClear(pParse);
99929 sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
99930 sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
99931 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
99932 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
99933 if( pSelect->selFlags & SF_UseSorter ){
99934 op = OP_SorterInsert;
99935 }else{
99936 op = OP_IdxInsert;
99938 sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
99939 sqlite3ReleaseTempReg(pParse, regRecord);
99940 sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
99941 if( pSelect->iLimit ){
99942 int addr1, addr2;
99943 int iLimit;
99944 if( pSelect->iOffset ){
99945 iLimit = pSelect->iOffset+1;
99946 }else{
99947 iLimit = pSelect->iLimit;
99949 addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
99950 sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
99951 addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
99952 sqlite3VdbeJumpHere(v, addr1);
99953 sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
99954 sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
99955 sqlite3VdbeJumpHere(v, addr2);
99960 ** Add code to implement the OFFSET
99962 static void codeOffset(
99963 Vdbe *v, /* Generate code into this VM */
99964 int iOffset, /* Register holding the offset counter */
99965 int iContinue /* Jump here to skip the current record */
99967 if( iOffset>0 && iContinue!=0 ){
99968 int addr;
99969 sqlite3VdbeAddOp2(v, OP_AddImm, iOffset, -1);
99970 addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset);
99971 sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
99972 VdbeComment((v, "skip OFFSET records"));
99973 sqlite3VdbeJumpHere(v, addr);
99978 ** Add code that will check to make sure the N registers starting at iMem
99979 ** form a distinct entry. iTab is a sorting index that holds previously
99980 ** seen combinations of the N values. A new entry is made in iTab
99981 ** if the current N values are new.
99983 ** A jump to addrRepeat is made and the N+1 values are popped from the
99984 ** stack if the top N elements are not distinct.
99986 static void codeDistinct(
99987 Parse *pParse, /* Parsing and code generating context */
99988 int iTab, /* A sorting index used to test for distinctness */
99989 int addrRepeat, /* Jump to here if not distinct */
99990 int N, /* Number of elements */
99991 int iMem /* First element */
99993 Vdbe *v;
99994 int r1;
99996 v = pParse->pVdbe;
99997 r1 = sqlite3GetTempReg(pParse);
99998 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
99999 sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
100000 sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
100001 sqlite3ReleaseTempReg(pParse, r1);
100004 #ifndef SQLITE_OMIT_SUBQUERY
100006 ** Generate an error message when a SELECT is used within a subexpression
100007 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
100008 ** column. We do this in a subroutine because the error used to occur
100009 ** in multiple places. (The error only occurs in one place now, but we
100010 ** retain the subroutine to minimize code disruption.)
100012 static int checkForMultiColumnSelectError(
100013 Parse *pParse, /* Parse context. */
100014 SelectDest *pDest, /* Destination of SELECT results */
100015 int nExpr /* Number of result columns returned by SELECT */
100017 int eDest = pDest->eDest;
100018 if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
100019 sqlite3ErrorMsg(pParse, "only a single result allowed for "
100020 "a SELECT that is part of an expression");
100021 return 1;
100022 }else{
100023 return 0;
100026 #endif
100029 ** An instance of the following object is used to record information about
100030 ** how to process the DISTINCT keyword, to simplify passing that information
100031 ** into the selectInnerLoop() routine.
100033 typedef struct DistinctCtx DistinctCtx;
100034 struct DistinctCtx {
100035 u8 isTnct; /* True if the DISTINCT keyword is present */
100036 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
100037 int tabTnct; /* Ephemeral table used for DISTINCT processing */
100038 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
100042 ** This routine generates the code for the inside of the inner loop
100043 ** of a SELECT.
100045 ** If srcTab is negative, then the pEList expressions
100046 ** are evaluated in order to get the data for this row. If srcTab is
100047 ** zero or more, then data is pulled from srcTab and pEList is used only
100048 ** to get number columns and the datatype for each column.
100050 static void selectInnerLoop(
100051 Parse *pParse, /* The parser context */
100052 Select *p, /* The complete select statement being coded */
100053 ExprList *pEList, /* List of values being extracted */
100054 int srcTab, /* Pull data from this table */
100055 ExprList *pOrderBy, /* If not NULL, sort results using this key */
100056 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
100057 SelectDest *pDest, /* How to dispose of the results */
100058 int iContinue, /* Jump here to continue with next row */
100059 int iBreak /* Jump here to break out of the inner loop */
100061 Vdbe *v = pParse->pVdbe;
100062 int i;
100063 int hasDistinct; /* True if the DISTINCT keyword is present */
100064 int regResult; /* Start of memory holding result set */
100065 int eDest = pDest->eDest; /* How to dispose of results */
100066 int iParm = pDest->iSDParm; /* First argument to disposal method */
100067 int nResultCol; /* Number of result columns */
100069 assert( v );
100070 assert( pEList!=0 );
100071 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
100072 if( pOrderBy==0 && !hasDistinct ){
100073 codeOffset(v, p->iOffset, iContinue);
100076 /* Pull the requested columns.
100078 nResultCol = pEList->nExpr;
100079 if( pDest->iSdst==0 ){
100080 pDest->iSdst = pParse->nMem+1;
100081 pDest->nSdst = nResultCol;
100082 pParse->nMem += nResultCol;
100083 }else{
100084 assert( pDest->nSdst==nResultCol );
100086 regResult = pDest->iSdst;
100087 if( srcTab>=0 ){
100088 for(i=0; i<nResultCol; i++){
100089 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
100090 VdbeComment((v, "%s", pEList->a[i].zName));
100092 }else if( eDest!=SRT_Exists ){
100093 /* If the destination is an EXISTS(...) expression, the actual
100094 ** values returned by the SELECT are not required.
100096 sqlite3ExprCodeExprList(pParse, pEList, regResult,
100097 (eDest==SRT_Output)?SQLITE_ECEL_DUP:0);
100100 /* If the DISTINCT keyword was present on the SELECT statement
100101 ** and this row has been seen before, then do not make this row
100102 ** part of the result.
100104 if( hasDistinct ){
100105 switch( pDistinct->eTnctType ){
100106 case WHERE_DISTINCT_ORDERED: {
100107 VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
100108 int iJump; /* Jump destination */
100109 int regPrev; /* Previous row content */
100111 /* Allocate space for the previous row */
100112 regPrev = pParse->nMem+1;
100113 pParse->nMem += nResultCol;
100115 /* Change the OP_OpenEphemeral coded earlier to an OP_Null
100116 ** sets the MEM_Cleared bit on the first register of the
100117 ** previous value. This will cause the OP_Ne below to always
100118 ** fail on the first iteration of the loop even if the first
100119 ** row is all NULLs.
100121 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
100122 pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
100123 pOp->opcode = OP_Null;
100124 pOp->p1 = 1;
100125 pOp->p2 = regPrev;
100127 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
100128 for(i=0; i<nResultCol; i++){
100129 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
100130 if( i<nResultCol-1 ){
100131 sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
100132 }else{
100133 sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
100135 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
100136 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
100138 assert( sqlite3VdbeCurrentAddr(v)==iJump );
100139 sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
100140 break;
100143 case WHERE_DISTINCT_UNIQUE: {
100144 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
100145 break;
100148 default: {
100149 assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
100150 codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
100151 break;
100154 if( pOrderBy==0 ){
100155 codeOffset(v, p->iOffset, iContinue);
100159 switch( eDest ){
100160 /* In this mode, write each query result to the key of the temporary
100161 ** table iParm.
100163 #ifndef SQLITE_OMIT_COMPOUND_SELECT
100164 case SRT_Union: {
100165 int r1;
100166 r1 = sqlite3GetTempReg(pParse);
100167 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
100168 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
100169 sqlite3ReleaseTempReg(pParse, r1);
100170 break;
100173 /* Construct a record from the query result, but instead of
100174 ** saving that record, use it as a key to delete elements from
100175 ** the temporary table iParm.
100177 case SRT_Except: {
100178 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
100179 break;
100181 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
100183 /* Store the result as data using a unique key.
100185 case SRT_DistTable:
100186 case SRT_Table:
100187 case SRT_EphemTab: {
100188 int r1 = sqlite3GetTempReg(pParse);
100189 testcase( eDest==SRT_Table );
100190 testcase( eDest==SRT_EphemTab );
100191 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
100192 #ifndef SQLITE_OMIT_CTE
100193 if( eDest==SRT_DistTable ){
100194 /* If the destination is DistTable, then cursor (iParm+1) is open
100195 ** on an ephemeral index. If the current row is already present
100196 ** in the index, do not write it to the output. If not, add the
100197 ** current row to the index and proceed with writing it to the
100198 ** output table as well. */
100199 int addr = sqlite3VdbeCurrentAddr(v) + 4;
100200 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
100201 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
100202 assert( pOrderBy==0 );
100204 #endif
100205 if( pOrderBy ){
100206 pushOntoSorter(pParse, pOrderBy, p, r1);
100207 }else{
100208 int r2 = sqlite3GetTempReg(pParse);
100209 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
100210 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
100211 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
100212 sqlite3ReleaseTempReg(pParse, r2);
100214 sqlite3ReleaseTempReg(pParse, r1);
100215 break;
100218 #ifndef SQLITE_OMIT_SUBQUERY
100219 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
100220 ** then there should be a single item on the stack. Write this
100221 ** item into the set table with bogus data.
100223 case SRT_Set: {
100224 assert( nResultCol==1 );
100225 pDest->affSdst =
100226 sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
100227 if( pOrderBy ){
100228 /* At first glance you would think we could optimize out the
100229 ** ORDER BY in this case since the order of entries in the set
100230 ** does not matter. But there might be a LIMIT clause, in which
100231 ** case the order does matter */
100232 pushOntoSorter(pParse, pOrderBy, p, regResult);
100233 }else{
100234 int r1 = sqlite3GetTempReg(pParse);
100235 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
100236 sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
100237 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
100238 sqlite3ReleaseTempReg(pParse, r1);
100240 break;
100243 /* If any row exist in the result set, record that fact and abort.
100245 case SRT_Exists: {
100246 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
100247 /* The LIMIT clause will terminate the loop for us */
100248 break;
100251 /* If this is a scalar select that is part of an expression, then
100252 ** store the results in the appropriate memory cell and break out
100253 ** of the scan loop.
100255 case SRT_Mem: {
100256 assert( nResultCol==1 );
100257 if( pOrderBy ){
100258 pushOntoSorter(pParse, pOrderBy, p, regResult);
100259 }else{
100260 sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
100261 /* The LIMIT clause will jump out of the loop for us */
100263 break;
100265 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
100267 /* Send the data to the callback function or to a subroutine. In the
100268 ** case of a subroutine, the subroutine itself is responsible for
100269 ** popping the data from the stack.
100271 case SRT_Coroutine:
100272 case SRT_Output: {
100273 testcase( eDest==SRT_Coroutine );
100274 testcase( eDest==SRT_Output );
100275 if( pOrderBy ){
100276 int r1 = sqlite3GetTempReg(pParse);
100277 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
100278 pushOntoSorter(pParse, pOrderBy, p, r1);
100279 sqlite3ReleaseTempReg(pParse, r1);
100280 }else if( eDest==SRT_Coroutine ){
100281 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
100282 }else{
100283 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
100284 sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
100286 break;
100289 #ifndef SQLITE_OMIT_CTE
100290 /* Write the results into a priority queue that is order according to
100291 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
100292 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
100293 ** pSO->nExpr columns, then make sure all keys are unique by adding a
100294 ** final OP_Sequence column. The last column is the record as a blob.
100296 case SRT_DistQueue:
100297 case SRT_Queue: {
100298 int nKey;
100299 int r1, r2, r3;
100300 int addrTest = 0;
100301 ExprList *pSO;
100302 pSO = pDest->pOrderBy;
100303 assert( pSO );
100304 nKey = pSO->nExpr;
100305 r1 = sqlite3GetTempReg(pParse);
100306 r2 = sqlite3GetTempRange(pParse, nKey+2);
100307 r3 = r2+nKey+1;
100308 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
100309 if( eDest==SRT_DistQueue ){
100310 /* If the destination is DistQueue, then cursor (iParm+1) is open
100311 ** on a second ephemeral index that holds all values every previously
100312 ** added to the queue. Only add this new value if it has never before
100313 ** been added */
100314 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, r3, 0);
100315 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
100316 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
100318 for(i=0; i<nKey; i++){
100319 sqlite3VdbeAddOp2(v, OP_SCopy,
100320 regResult + pSO->a[i].u.x.iOrderByCol - 1,
100321 r2+i);
100323 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
100324 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
100325 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
100326 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
100327 sqlite3ReleaseTempReg(pParse, r1);
100328 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
100329 break;
100331 #endif /* SQLITE_OMIT_CTE */
100335 #if !defined(SQLITE_OMIT_TRIGGER)
100336 /* Discard the results. This is used for SELECT statements inside
100337 ** the body of a TRIGGER. The purpose of such selects is to call
100338 ** user-defined functions that have side effects. We do not care
100339 ** about the actual results of the select.
100341 default: {
100342 assert( eDest==SRT_Discard );
100343 break;
100345 #endif
100348 /* Jump to the end of the loop if the LIMIT is reached. Except, if
100349 ** there is a sorter, in which case the sorter has already limited
100350 ** the output for us.
100352 if( pOrderBy==0 && p->iLimit ){
100353 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
100358 ** Allocate a KeyInfo object sufficient for an index of N key columns and
100359 ** X extra columns.
100361 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
100362 KeyInfo *p = sqlite3DbMallocZero(0,
100363 sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
100364 if( p ){
100365 p->aSortOrder = (u8*)&p->aColl[N+X];
100366 p->nField = (u16)N;
100367 p->nXField = (u16)X;
100368 p->enc = ENC(db);
100369 p->db = db;
100370 p->nRef = 1;
100371 }else{
100372 db->mallocFailed = 1;
100374 return p;
100378 ** Deallocate a KeyInfo object
100380 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
100381 if( p ){
100382 assert( p->nRef>0 );
100383 p->nRef--;
100384 if( p->nRef==0 ) sqlite3DbFree(0, p);
100389 ** Make a new pointer to a KeyInfo object
100391 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
100392 if( p ){
100393 assert( p->nRef>0 );
100394 p->nRef++;
100396 return p;
100399 #ifdef SQLITE_DEBUG
100401 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
100402 ** can only be changed if this is just a single reference to the object.
100404 ** This routine is used only inside of assert() statements.
100406 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
100407 #endif /* SQLITE_DEBUG */
100410 ** Given an expression list, generate a KeyInfo structure that records
100411 ** the collating sequence for each expression in that expression list.
100413 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
100414 ** KeyInfo structure is appropriate for initializing a virtual index to
100415 ** implement that clause. If the ExprList is the result set of a SELECT
100416 ** then the KeyInfo structure is appropriate for initializing a virtual
100417 ** index to implement a DISTINCT test.
100419 ** Space to hold the KeyInfo structure is obtain from malloc. The calling
100420 ** function is responsible for seeing that this structure is eventually
100421 ** freed.
100423 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList, int nExtra){
100424 int nExpr;
100425 KeyInfo *pInfo;
100426 struct ExprList_item *pItem;
100427 sqlite3 *db = pParse->db;
100428 int i;
100430 nExpr = pList->nExpr;
100431 pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra, 1);
100432 if( pInfo ){
100433 assert( sqlite3KeyInfoIsWriteable(pInfo) );
100434 for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
100435 CollSeq *pColl;
100436 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
100437 if( !pColl ) pColl = db->pDfltColl;
100438 pInfo->aColl[i] = pColl;
100439 pInfo->aSortOrder[i] = pItem->sortOrder;
100442 return pInfo;
100445 #ifndef SQLITE_OMIT_COMPOUND_SELECT
100447 ** Name of the connection operator, used for error messages.
100449 static const char *selectOpName(int id){
100450 char *z;
100451 switch( id ){
100452 case TK_ALL: z = "UNION ALL"; break;
100453 case TK_INTERSECT: z = "INTERSECT"; break;
100454 case TK_EXCEPT: z = "EXCEPT"; break;
100455 default: z = "UNION"; break;
100457 return z;
100459 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
100461 #ifndef SQLITE_OMIT_EXPLAIN
100463 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
100464 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
100465 ** where the caption is of the form:
100467 ** "USE TEMP B-TREE FOR xxx"
100469 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
100470 ** is determined by the zUsage argument.
100472 static void explainTempTable(Parse *pParse, const char *zUsage){
100473 if( pParse->explain==2 ){
100474 Vdbe *v = pParse->pVdbe;
100475 char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
100476 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
100481 ** Assign expression b to lvalue a. A second, no-op, version of this macro
100482 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
100483 ** in sqlite3Select() to assign values to structure member variables that
100484 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
100485 ** code with #ifndef directives.
100487 # define explainSetInteger(a, b) a = b
100489 #else
100490 /* No-op versions of the explainXXX() functions and macros. */
100491 # define explainTempTable(y,z)
100492 # define explainSetInteger(y,z)
100493 #endif
100495 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
100497 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
100498 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
100499 ** where the caption is of one of the two forms:
100501 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
100502 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
100504 ** where iSub1 and iSub2 are the integers passed as the corresponding
100505 ** function parameters, and op is the text representation of the parameter
100506 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
100507 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
100508 ** false, or the second form if it is true.
100510 static void explainComposite(
100511 Parse *pParse, /* Parse context */
100512 int op, /* One of TK_UNION, TK_EXCEPT etc. */
100513 int iSub1, /* Subquery id 1 */
100514 int iSub2, /* Subquery id 2 */
100515 int bUseTmp /* True if a temp table was used */
100517 assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
100518 if( pParse->explain==2 ){
100519 Vdbe *v = pParse->pVdbe;
100520 char *zMsg = sqlite3MPrintf(
100521 pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
100522 bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
100524 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
100527 #else
100528 /* No-op versions of the explainXXX() functions and macros. */
100529 # define explainComposite(v,w,x,y,z)
100530 #endif
100533 ** If the inner loop was generated using a non-null pOrderBy argument,
100534 ** then the results were placed in a sorter. After the loop is terminated
100535 ** we need to run the sorter and output the results. The following
100536 ** routine generates the code needed to do that.
100538 static void generateSortTail(
100539 Parse *pParse, /* Parsing context */
100540 Select *p, /* The SELECT statement */
100541 Vdbe *v, /* Generate code into this VDBE */
100542 int nColumn, /* Number of columns of data */
100543 SelectDest *pDest /* Write the sorted results here */
100545 int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
100546 int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
100547 int addr;
100548 int iTab;
100549 int pseudoTab = 0;
100550 ExprList *pOrderBy = p->pOrderBy;
100552 int eDest = pDest->eDest;
100553 int iParm = pDest->iSDParm;
100555 int regRow;
100556 int regRowid;
100558 iTab = pOrderBy->iECursor;
100559 regRow = sqlite3GetTempReg(pParse);
100560 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
100561 pseudoTab = pParse->nTab++;
100562 sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
100563 regRowid = 0;
100564 }else{
100565 regRowid = sqlite3GetTempReg(pParse);
100567 if( p->selFlags & SF_UseSorter ){
100568 int regSortOut = ++pParse->nMem;
100569 int ptab2 = pParse->nTab++;
100570 sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
100571 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
100572 codeOffset(v, p->iOffset, addrContinue);
100573 sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
100574 sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
100575 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
100576 }else{
100577 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
100578 codeOffset(v, p->iOffset, addrContinue);
100579 sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
100581 switch( eDest ){
100582 case SRT_Table:
100583 case SRT_EphemTab: {
100584 testcase( eDest==SRT_Table );
100585 testcase( eDest==SRT_EphemTab );
100586 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
100587 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
100588 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
100589 break;
100591 #ifndef SQLITE_OMIT_SUBQUERY
100592 case SRT_Set: {
100593 assert( nColumn==1 );
100594 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
100595 &pDest->affSdst, 1);
100596 sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
100597 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
100598 break;
100600 case SRT_Mem: {
100601 assert( nColumn==1 );
100602 sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
100603 /* The LIMIT clause will terminate the loop for us */
100604 break;
100606 #endif
100607 default: {
100608 int i;
100609 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
100610 testcase( eDest==SRT_Output );
100611 testcase( eDest==SRT_Coroutine );
100612 for(i=0; i<nColumn; i++){
100613 assert( regRow!=pDest->iSdst+i );
100614 sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
100615 if( i==0 ){
100616 sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
100619 if( eDest==SRT_Output ){
100620 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
100621 sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
100622 }else{
100623 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
100625 break;
100628 sqlite3ReleaseTempReg(pParse, regRow);
100629 sqlite3ReleaseTempReg(pParse, regRowid);
100631 /* The bottom of the loop
100633 sqlite3VdbeResolveLabel(v, addrContinue);
100634 if( p->selFlags & SF_UseSorter ){
100635 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
100636 }else{
100637 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
100639 sqlite3VdbeResolveLabel(v, addrBreak);
100640 if( eDest==SRT_Output || eDest==SRT_Coroutine ){
100641 sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
100646 ** Return a pointer to a string containing the 'declaration type' of the
100647 ** expression pExpr. The string may be treated as static by the caller.
100649 ** Also try to estimate the size of the returned value and return that
100650 ** result in *pEstWidth.
100652 ** The declaration type is the exact datatype definition extracted from the
100653 ** original CREATE TABLE statement if the expression is a column. The
100654 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
100655 ** is considered a column can be complex in the presence of subqueries. The
100656 ** result-set expression in all of the following SELECT statements is
100657 ** considered a column by this function.
100659 ** SELECT col FROM tbl;
100660 ** SELECT (SELECT col FROM tbl;
100661 ** SELECT (SELECT col FROM tbl);
100662 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
100664 ** The declaration type for any expression other than a column is NULL.
100666 ** This routine has either 3 or 6 parameters depending on whether or not
100667 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
100669 #ifdef SQLITE_ENABLE_COLUMN_METADATA
100670 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
100671 static const char *columnTypeImpl(
100672 NameContext *pNC,
100673 Expr *pExpr,
100674 const char **pzOrigDb,
100675 const char **pzOrigTab,
100676 const char **pzOrigCol,
100677 u8 *pEstWidth
100679 char const *zOrigDb = 0;
100680 char const *zOrigTab = 0;
100681 char const *zOrigCol = 0;
100682 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
100683 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
100684 static const char *columnTypeImpl(
100685 NameContext *pNC,
100686 Expr *pExpr,
100687 u8 *pEstWidth
100689 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
100690 char const *zType = 0;
100691 int j;
100692 u8 estWidth = 1;
100694 if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
100695 switch( pExpr->op ){
100696 case TK_AGG_COLUMN:
100697 case TK_COLUMN: {
100698 /* The expression is a column. Locate the table the column is being
100699 ** extracted from in NameContext.pSrcList. This table may be real
100700 ** database table or a subquery.
100702 Table *pTab = 0; /* Table structure column is extracted from */
100703 Select *pS = 0; /* Select the column is extracted from */
100704 int iCol = pExpr->iColumn; /* Index of column in pTab */
100705 testcase( pExpr->op==TK_AGG_COLUMN );
100706 testcase( pExpr->op==TK_COLUMN );
100707 while( pNC && !pTab ){
100708 SrcList *pTabList = pNC->pSrcList;
100709 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
100710 if( j<pTabList->nSrc ){
100711 pTab = pTabList->a[j].pTab;
100712 pS = pTabList->a[j].pSelect;
100713 }else{
100714 pNC = pNC->pNext;
100718 if( pTab==0 ){
100719 /* At one time, code such as "SELECT new.x" within a trigger would
100720 ** cause this condition to run. Since then, we have restructured how
100721 ** trigger code is generated and so this condition is no longer
100722 ** possible. However, it can still be true for statements like
100723 ** the following:
100725 ** CREATE TABLE t1(col INTEGER);
100726 ** SELECT (SELECT t1.col) FROM FROM t1;
100728 ** when columnType() is called on the expression "t1.col" in the
100729 ** sub-select. In this case, set the column type to NULL, even
100730 ** though it should really be "INTEGER".
100732 ** This is not a problem, as the column type of "t1.col" is never
100733 ** used. When columnType() is called on the expression
100734 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
100735 ** branch below. */
100736 break;
100739 assert( pTab && pExpr->pTab==pTab );
100740 if( pS ){
100741 /* The "table" is actually a sub-select or a view in the FROM clause
100742 ** of the SELECT statement. Return the declaration type and origin
100743 ** data for the result-set column of the sub-select.
100745 if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
100746 /* If iCol is less than zero, then the expression requests the
100747 ** rowid of the sub-select or view. This expression is legal (see
100748 ** test case misc2.2.2) - it always evaluates to NULL.
100750 NameContext sNC;
100751 Expr *p = pS->pEList->a[iCol].pExpr;
100752 sNC.pSrcList = pS->pSrc;
100753 sNC.pNext = pNC;
100754 sNC.pParse = pNC->pParse;
100755 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
100757 }else if( pTab->pSchema ){
100758 /* A real table */
100759 assert( !pS );
100760 if( iCol<0 ) iCol = pTab->iPKey;
100761 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
100762 #ifdef SQLITE_ENABLE_COLUMN_METADATA
100763 if( iCol<0 ){
100764 zType = "INTEGER";
100765 zOrigCol = "rowid";
100766 }else{
100767 zType = pTab->aCol[iCol].zType;
100768 zOrigCol = pTab->aCol[iCol].zName;
100769 estWidth = pTab->aCol[iCol].szEst;
100771 zOrigTab = pTab->zName;
100772 if( pNC->pParse ){
100773 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
100774 zOrigDb = pNC->pParse->db->aDb[iDb].zName;
100776 #else
100777 if( iCol<0 ){
100778 zType = "INTEGER";
100779 }else{
100780 zType = pTab->aCol[iCol].zType;
100781 estWidth = pTab->aCol[iCol].szEst;
100783 #endif
100785 break;
100787 #ifndef SQLITE_OMIT_SUBQUERY
100788 case TK_SELECT: {
100789 /* The expression is a sub-select. Return the declaration type and
100790 ** origin info for the single column in the result set of the SELECT
100791 ** statement.
100793 NameContext sNC;
100794 Select *pS = pExpr->x.pSelect;
100795 Expr *p = pS->pEList->a[0].pExpr;
100796 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
100797 sNC.pSrcList = pS->pSrc;
100798 sNC.pNext = pNC;
100799 sNC.pParse = pNC->pParse;
100800 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
100801 break;
100803 #endif
100806 #ifdef SQLITE_ENABLE_COLUMN_METADATA
100807 if( pzOrigDb ){
100808 assert( pzOrigTab && pzOrigCol );
100809 *pzOrigDb = zOrigDb;
100810 *pzOrigTab = zOrigTab;
100811 *pzOrigCol = zOrigCol;
100813 #endif
100814 if( pEstWidth ) *pEstWidth = estWidth;
100815 return zType;
100819 ** Generate code that will tell the VDBE the declaration types of columns
100820 ** in the result set.
100822 static void generateColumnTypes(
100823 Parse *pParse, /* Parser context */
100824 SrcList *pTabList, /* List of tables */
100825 ExprList *pEList /* Expressions defining the result set */
100827 #ifndef SQLITE_OMIT_DECLTYPE
100828 Vdbe *v = pParse->pVdbe;
100829 int i;
100830 NameContext sNC;
100831 sNC.pSrcList = pTabList;
100832 sNC.pParse = pParse;
100833 for(i=0; i<pEList->nExpr; i++){
100834 Expr *p = pEList->a[i].pExpr;
100835 const char *zType;
100836 #ifdef SQLITE_ENABLE_COLUMN_METADATA
100837 const char *zOrigDb = 0;
100838 const char *zOrigTab = 0;
100839 const char *zOrigCol = 0;
100840 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
100842 /* The vdbe must make its own copy of the column-type and other
100843 ** column specific strings, in case the schema is reset before this
100844 ** virtual machine is deleted.
100846 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
100847 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
100848 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
100849 #else
100850 zType = columnType(&sNC, p, 0, 0, 0, 0);
100851 #endif
100852 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
100854 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
100858 ** Generate code that will tell the VDBE the names of columns
100859 ** in the result set. This information is used to provide the
100860 ** azCol[] values in the callback.
100862 static void generateColumnNames(
100863 Parse *pParse, /* Parser context */
100864 SrcList *pTabList, /* List of tables */
100865 ExprList *pEList /* Expressions defining the result set */
100867 Vdbe *v = pParse->pVdbe;
100868 int i, j;
100869 sqlite3 *db = pParse->db;
100870 int fullNames, shortNames;
100872 #ifndef SQLITE_OMIT_EXPLAIN
100873 /* If this is an EXPLAIN, skip this step */
100874 if( pParse->explain ){
100875 return;
100877 #endif
100879 if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
100880 pParse->colNamesSet = 1;
100881 fullNames = (db->flags & SQLITE_FullColNames)!=0;
100882 shortNames = (db->flags & SQLITE_ShortColNames)!=0;
100883 sqlite3VdbeSetNumCols(v, pEList->nExpr);
100884 for(i=0; i<pEList->nExpr; i++){
100885 Expr *p;
100886 p = pEList->a[i].pExpr;
100887 if( NEVER(p==0) ) continue;
100888 if( pEList->a[i].zName ){
100889 char *zName = pEList->a[i].zName;
100890 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
100891 }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
100892 Table *pTab;
100893 char *zCol;
100894 int iCol = p->iColumn;
100895 for(j=0; ALWAYS(j<pTabList->nSrc); j++){
100896 if( pTabList->a[j].iCursor==p->iTable ) break;
100898 assert( j<pTabList->nSrc );
100899 pTab = pTabList->a[j].pTab;
100900 if( iCol<0 ) iCol = pTab->iPKey;
100901 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
100902 if( iCol<0 ){
100903 zCol = "rowid";
100904 }else{
100905 zCol = pTab->aCol[iCol].zName;
100907 if( !shortNames && !fullNames ){
100908 sqlite3VdbeSetColName(v, i, COLNAME_NAME,
100909 sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
100910 }else if( fullNames ){
100911 char *zName = 0;
100912 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
100913 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
100914 }else{
100915 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
100917 }else{
100918 const char *z = pEList->a[i].zSpan;
100919 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
100920 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
100923 generateColumnTypes(pParse, pTabList, pEList);
100927 ** Given a an expression list (which is really the list of expressions
100928 ** that form the result set of a SELECT statement) compute appropriate
100929 ** column names for a table that would hold the expression list.
100931 ** All column names will be unique.
100933 ** Only the column names are computed. Column.zType, Column.zColl,
100934 ** and other fields of Column are zeroed.
100936 ** Return SQLITE_OK on success. If a memory allocation error occurs,
100937 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
100939 static int selectColumnsFromExprList(
100940 Parse *pParse, /* Parsing context */
100941 ExprList *pEList, /* Expr list from which to derive column names */
100942 i16 *pnCol, /* Write the number of columns here */
100943 Column **paCol /* Write the new column list here */
100945 sqlite3 *db = pParse->db; /* Database connection */
100946 int i, j; /* Loop counters */
100947 int cnt; /* Index added to make the name unique */
100948 Column *aCol, *pCol; /* For looping over result columns */
100949 int nCol; /* Number of columns in the result set */
100950 Expr *p; /* Expression for a single result column */
100951 char *zName; /* Column name */
100952 int nName; /* Size of name in zName[] */
100954 if( pEList ){
100955 nCol = pEList->nExpr;
100956 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
100957 testcase( aCol==0 );
100958 }else{
100959 nCol = 0;
100960 aCol = 0;
100962 *pnCol = nCol;
100963 *paCol = aCol;
100965 for(i=0, pCol=aCol; i<nCol; i++, pCol++){
100966 /* Get an appropriate name for the column
100968 p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
100969 if( (zName = pEList->a[i].zName)!=0 ){
100970 /* If the column contains an "AS <name>" phrase, use <name> as the name */
100971 zName = sqlite3DbStrDup(db, zName);
100972 }else{
100973 Expr *pColExpr = p; /* The expression that is the result column name */
100974 Table *pTab; /* Table associated with this expression */
100975 while( pColExpr->op==TK_DOT ){
100976 pColExpr = pColExpr->pRight;
100977 assert( pColExpr!=0 );
100979 if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
100980 /* For columns use the column name name */
100981 int iCol = pColExpr->iColumn;
100982 pTab = pColExpr->pTab;
100983 if( iCol<0 ) iCol = pTab->iPKey;
100984 zName = sqlite3MPrintf(db, "%s",
100985 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
100986 }else if( pColExpr->op==TK_ID ){
100987 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
100988 zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
100989 }else{
100990 /* Use the original text of the column expression as its name */
100991 zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
100994 if( db->mallocFailed ){
100995 sqlite3DbFree(db, zName);
100996 break;
100999 /* Make sure the column name is unique. If the name is not unique,
101000 ** append a integer to the name so that it becomes unique.
101002 nName = sqlite3Strlen30(zName);
101003 for(j=cnt=0; j<i; j++){
101004 if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
101005 char *zNewName;
101006 int k;
101007 for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
101008 if( zName[k]==':' ) nName = k;
101009 zName[nName] = 0;
101010 zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
101011 sqlite3DbFree(db, zName);
101012 zName = zNewName;
101013 j = -1;
101014 if( zName==0 ) break;
101017 pCol->zName = zName;
101019 if( db->mallocFailed ){
101020 for(j=0; j<i; j++){
101021 sqlite3DbFree(db, aCol[j].zName);
101023 sqlite3DbFree(db, aCol);
101024 *paCol = 0;
101025 *pnCol = 0;
101026 return SQLITE_NOMEM;
101028 return SQLITE_OK;
101032 ** Add type and collation information to a column list based on
101033 ** a SELECT statement.
101035 ** The column list presumably came from selectColumnNamesFromExprList().
101036 ** The column list has only names, not types or collations. This
101037 ** routine goes through and adds the types and collations.
101039 ** This routine requires that all identifiers in the SELECT
101040 ** statement be resolved.
101042 static void selectAddColumnTypeAndCollation(
101043 Parse *pParse, /* Parsing contexts */
101044 Table *pTab, /* Add column type information to this table */
101045 Select *pSelect /* SELECT used to determine types and collations */
101047 sqlite3 *db = pParse->db;
101048 NameContext sNC;
101049 Column *pCol;
101050 CollSeq *pColl;
101051 int i;
101052 Expr *p;
101053 struct ExprList_item *a;
101054 u64 szAll = 0;
101056 assert( pSelect!=0 );
101057 assert( (pSelect->selFlags & SF_Resolved)!=0 );
101058 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
101059 if( db->mallocFailed ) return;
101060 memset(&sNC, 0, sizeof(sNC));
101061 sNC.pSrcList = pSelect->pSrc;
101062 a = pSelect->pEList->a;
101063 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
101064 p = a[i].pExpr;
101065 pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
101066 szAll += pCol->szEst;
101067 pCol->affinity = sqlite3ExprAffinity(p);
101068 if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
101069 pColl = sqlite3ExprCollSeq(pParse, p);
101070 if( pColl ){
101071 pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
101074 pTab->szTabRow = sqlite3LogEst(szAll*4);
101078 ** Given a SELECT statement, generate a Table structure that describes
101079 ** the result set of that SELECT.
101081 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
101082 Table *pTab;
101083 sqlite3 *db = pParse->db;
101084 int savedFlags;
101086 savedFlags = db->flags;
101087 db->flags &= ~SQLITE_FullColNames;
101088 db->flags |= SQLITE_ShortColNames;
101089 sqlite3SelectPrep(pParse, pSelect, 0);
101090 if( pParse->nErr ) return 0;
101091 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
101092 db->flags = savedFlags;
101093 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
101094 if( pTab==0 ){
101095 return 0;
101097 /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
101098 ** is disabled */
101099 assert( db->lookaside.bEnabled==0 );
101100 pTab->nRef = 1;
101101 pTab->zName = 0;
101102 pTab->nRowEst = 1048576;
101103 selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
101104 selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
101105 pTab->iPKey = -1;
101106 if( db->mallocFailed ){
101107 sqlite3DeleteTable(db, pTab);
101108 return 0;
101110 return pTab;
101114 ** Get a VDBE for the given parser context. Create a new one if necessary.
101115 ** If an error occurs, return NULL and leave a message in pParse.
101117 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
101118 Vdbe *v = pParse->pVdbe;
101119 if( v==0 ){
101120 v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
101121 #ifndef SQLITE_OMIT_TRACE
101122 if( v ){
101123 sqlite3VdbeAddOp0(v, OP_Trace);
101125 #endif
101127 return v;
101132 ** Compute the iLimit and iOffset fields of the SELECT based on the
101133 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
101134 ** that appear in the original SQL statement after the LIMIT and OFFSET
101135 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
101136 ** are the integer memory register numbers for counters used to compute
101137 ** the limit and offset. If there is no limit and/or offset, then
101138 ** iLimit and iOffset are negative.
101140 ** This routine changes the values of iLimit and iOffset only if
101141 ** a limit or offset is defined by pLimit and pOffset. iLimit and
101142 ** iOffset should have been preset to appropriate default values (zero)
101143 ** prior to calling this routine.
101145 ** The iOffset register (if it exists) is initialized to the value
101146 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
101147 ** iOffset+1 is initialized to LIMIT+OFFSET.
101149 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
101150 ** redefined. The UNION ALL operator uses this property to force
101151 ** the reuse of the same limit and offset registers across multiple
101152 ** SELECT statements.
101154 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
101155 Vdbe *v = 0;
101156 int iLimit = 0;
101157 int iOffset;
101158 int addr1, n;
101159 if( p->iLimit ) return;
101162 ** "LIMIT -1" always shows all rows. There is some
101163 ** controversy about what the correct behavior should be.
101164 ** The current implementation interprets "LIMIT 0" to mean
101165 ** no rows.
101167 sqlite3ExprCacheClear(pParse);
101168 assert( p->pOffset==0 || p->pLimit!=0 );
101169 if( p->pLimit ){
101170 p->iLimit = iLimit = ++pParse->nMem;
101171 v = sqlite3GetVdbe(pParse);
101172 assert( v!=0 );
101173 if( sqlite3ExprIsInteger(p->pLimit, &n) ){
101174 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
101175 VdbeComment((v, "LIMIT counter"));
101176 if( n==0 ){
101177 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
101178 }else if( n>=0 && p->nSelectRow>(u64)n ){
101179 p->nSelectRow = n;
101181 }else{
101182 sqlite3ExprCode(pParse, p->pLimit, iLimit);
101183 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
101184 VdbeComment((v, "LIMIT counter"));
101185 sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
101187 if( p->pOffset ){
101188 p->iOffset = iOffset = ++pParse->nMem;
101189 pParse->nMem++; /* Allocate an extra register for limit+offset */
101190 sqlite3ExprCode(pParse, p->pOffset, iOffset);
101191 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
101192 VdbeComment((v, "OFFSET counter"));
101193 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
101194 sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
101195 sqlite3VdbeJumpHere(v, addr1);
101196 sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
101197 VdbeComment((v, "LIMIT+OFFSET"));
101198 addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
101199 sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
101200 sqlite3VdbeJumpHere(v, addr1);
101205 #ifndef SQLITE_OMIT_COMPOUND_SELECT
101207 ** Return the appropriate collating sequence for the iCol-th column of
101208 ** the result set for the compound-select statement "p". Return NULL if
101209 ** the column has no default collating sequence.
101211 ** The collating sequence for the compound select is taken from the
101212 ** left-most term of the select that has a collating sequence.
101214 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
101215 CollSeq *pRet;
101216 if( p->pPrior ){
101217 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
101218 }else{
101219 pRet = 0;
101221 assert( iCol>=0 );
101222 if( pRet==0 && iCol<p->pEList->nExpr ){
101223 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
101225 return pRet;
101229 ** The select statement passed as the second parameter is a compound SELECT
101230 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
101231 ** structure suitable for implementing the ORDER BY.
101233 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
101234 ** function is responsible for ensuring that this structure is eventually
101235 ** freed.
101237 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
101238 ExprList *pOrderBy = p->pOrderBy;
101239 int nOrderBy = p->pOrderBy->nExpr;
101240 sqlite3 *db = pParse->db;
101241 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
101242 if( pRet ){
101243 int i;
101244 for(i=0; i<nOrderBy; i++){
101245 struct ExprList_item *pItem = &pOrderBy->a[i];
101246 Expr *pTerm = pItem->pExpr;
101247 CollSeq *pColl;
101249 if( pTerm->flags & EP_Collate ){
101250 pColl = sqlite3ExprCollSeq(pParse, pTerm);
101251 }else{
101252 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
101253 if( pColl==0 ) pColl = db->pDfltColl;
101254 pOrderBy->a[i].pExpr =
101255 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
101257 assert( sqlite3KeyInfoIsWriteable(pRet) );
101258 pRet->aColl[i] = pColl;
101259 pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
101263 return pRet;
101266 #ifndef SQLITE_OMIT_CTE
101268 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
101269 ** query of the form:
101271 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
101272 ** \___________/ \_______________/
101273 ** p->pPrior p
101276 ** There is exactly one reference to the recursive-table in the FROM clause
101277 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
101279 ** The setup-query runs once to generate an initial set of rows that go
101280 ** into a Queue table. Rows are extracted from the Queue table one by
101281 ** one. Each row extracted from Queue is output to pDest. Then the single
101282 ** extracted row (now in the iCurrent table) becomes the content of the
101283 ** recursive-table for a recursive-query run. The output of the recursive-query
101284 ** is added back into the Queue table. Then another row is extracted from Queue
101285 ** and the iteration continues until the Queue table is empty.
101287 ** If the compound query operator is UNION then no duplicate rows are ever
101288 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
101289 ** that have ever been inserted into Queue and causes duplicates to be
101290 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
101292 ** If the query has an ORDER BY, then entries in the Queue table are kept in
101293 ** ORDER BY order and the first entry is extracted for each cycle. Without
101294 ** an ORDER BY, the Queue table is just a FIFO.
101296 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
101297 ** have been output to pDest. A LIMIT of zero means to output no rows and a
101298 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
101299 ** with a positive value, then the first OFFSET outputs are discarded rather
101300 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
101301 ** rows have been skipped.
101303 static void generateWithRecursiveQuery(
101304 Parse *pParse, /* Parsing context */
101305 Select *p, /* The recursive SELECT to be coded */
101306 SelectDest *pDest /* What to do with query results */
101308 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
101309 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
101310 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
101311 Select *pSetup = p->pPrior; /* The setup query */
101312 int addrTop; /* Top of the loop */
101313 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
101314 int iCurrent = 0; /* The Current table */
101315 int regCurrent; /* Register holding Current table */
101316 int iQueue; /* The Queue table */
101317 int iDistinct = 0; /* To ensure unique results if UNION */
101318 int eDest = SRT_Table; /* How to write to Queue */
101319 SelectDest destQueue; /* SelectDest targetting the Queue table */
101320 int i; /* Loop counter */
101321 int rc; /* Result code */
101322 ExprList *pOrderBy; /* The ORDER BY clause */
101323 Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
101324 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
101326 /* Obtain authorization to do a recursive query */
101327 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
101329 /* Process the LIMIT and OFFSET clauses, if they exist */
101330 addrBreak = sqlite3VdbeMakeLabel(v);
101331 computeLimitRegisters(pParse, p, addrBreak);
101332 pLimit = p->pLimit;
101333 pOffset = p->pOffset;
101334 regLimit = p->iLimit;
101335 regOffset = p->iOffset;
101336 p->pLimit = p->pOffset = 0;
101337 p->iLimit = p->iOffset = 0;
101338 pOrderBy = p->pOrderBy;
101340 /* Locate the cursor number of the Current table */
101341 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
101342 if( pSrc->a[i].isRecursive ){
101343 iCurrent = pSrc->a[i].iCursor;
101344 break;
101348 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
101349 ** the Distinct table must be exactly one greater than Queue in order
101350 ** for the SRT_DistTable and SRT_DistQueue destinations to work. */
101351 iQueue = pParse->nTab++;
101352 if( p->op==TK_UNION ){
101353 eDest = pOrderBy ? SRT_DistQueue : SRT_DistTable;
101354 iDistinct = pParse->nTab++;
101355 }else{
101356 eDest = pOrderBy ? SRT_Queue : SRT_Table;
101358 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
101360 /* Allocate cursors for Current, Queue, and Distinct. */
101361 regCurrent = ++pParse->nMem;
101362 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
101363 if( pOrderBy ){
101364 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
101365 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
101366 (char*)pKeyInfo, P4_KEYINFO);
101367 destQueue.pOrderBy = pOrderBy;
101368 }else{
101369 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
101371 VdbeComment((v, "Queue table"));
101372 if( iDistinct ){
101373 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
101374 p->selFlags |= SF_UsesEphemeral;
101377 /* Detach the ORDER BY clause from the compound SELECT */
101378 p->pOrderBy = 0;
101380 /* Store the results of the setup-query in Queue. */
101381 rc = sqlite3Select(pParse, pSetup, &destQueue);
101382 if( rc ) goto end_of_recursive_query;
101384 /* Find the next row in the Queue and output that row */
101385 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak);
101387 /* Transfer the next row in Queue over to Current */
101388 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
101389 if( pOrderBy ){
101390 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
101391 }else{
101392 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
101394 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
101396 /* Output the single row in Current */
101397 addrCont = sqlite3VdbeMakeLabel(v);
101398 codeOffset(v, regOffset, addrCont);
101399 selectInnerLoop(pParse, p, p->pEList, iCurrent,
101400 0, 0, pDest, addrCont, addrBreak);
101401 if( regLimit ) sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
101402 sqlite3VdbeResolveLabel(v, addrCont);
101404 /* Execute the recursive SELECT taking the single row in Current as
101405 ** the value for the recursive-table. Store the results in the Queue.
101407 p->pPrior = 0;
101408 sqlite3Select(pParse, p, &destQueue);
101409 assert( p->pPrior==0 );
101410 p->pPrior = pSetup;
101412 /* Keep running the loop until the Queue is empty */
101413 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
101414 sqlite3VdbeResolveLabel(v, addrBreak);
101416 end_of_recursive_query:
101417 p->pOrderBy = pOrderBy;
101418 p->pLimit = pLimit;
101419 p->pOffset = pOffset;
101420 return;
101422 #endif /* SQLITE_OMIT_CTE */
101424 /* Forward references */
101425 static int multiSelectOrderBy(
101426 Parse *pParse, /* Parsing context */
101427 Select *p, /* The right-most of SELECTs to be coded */
101428 SelectDest *pDest /* What to do with query results */
101433 ** This routine is called to process a compound query form from
101434 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
101435 ** INTERSECT
101437 ** "p" points to the right-most of the two queries. the query on the
101438 ** left is p->pPrior. The left query could also be a compound query
101439 ** in which case this routine will be called recursively.
101441 ** The results of the total query are to be written into a destination
101442 ** of type eDest with parameter iParm.
101444 ** Example 1: Consider a three-way compound SQL statement.
101446 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
101448 ** This statement is parsed up as follows:
101450 ** SELECT c FROM t3
101452 ** `-----> SELECT b FROM t2
101454 ** `------> SELECT a FROM t1
101456 ** The arrows in the diagram above represent the Select.pPrior pointer.
101457 ** So if this routine is called with p equal to the t3 query, then
101458 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
101460 ** Notice that because of the way SQLite parses compound SELECTs, the
101461 ** individual selects always group from left to right.
101463 static int multiSelect(
101464 Parse *pParse, /* Parsing context */
101465 Select *p, /* The right-most of SELECTs to be coded */
101466 SelectDest *pDest /* What to do with query results */
101468 int rc = SQLITE_OK; /* Success code from a subroutine */
101469 Select *pPrior; /* Another SELECT immediately to our left */
101470 Vdbe *v; /* Generate code to this VDBE */
101471 SelectDest dest; /* Alternative data destination */
101472 Select *pDelete = 0; /* Chain of simple selects to delete */
101473 sqlite3 *db; /* Database connection */
101474 #ifndef SQLITE_OMIT_EXPLAIN
101475 int iSub1 = 0; /* EQP id of left-hand query */
101476 int iSub2 = 0; /* EQP id of right-hand query */
101477 #endif
101479 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
101480 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
101482 assert( p && p->pPrior ); /* Calling function guarantees this much */
101483 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
101484 db = pParse->db;
101485 pPrior = p->pPrior;
101486 assert( pPrior->pRightmost!=pPrior );
101487 assert( pPrior->pRightmost==p->pRightmost );
101488 dest = *pDest;
101489 if( pPrior->pOrderBy ){
101490 sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
101491 selectOpName(p->op));
101492 rc = 1;
101493 goto multi_select_end;
101495 if( pPrior->pLimit ){
101496 sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
101497 selectOpName(p->op));
101498 rc = 1;
101499 goto multi_select_end;
101502 v = sqlite3GetVdbe(pParse);
101503 assert( v!=0 ); /* The VDBE already created by calling function */
101505 /* Create the destination temporary table if necessary
101507 if( dest.eDest==SRT_EphemTab ){
101508 assert( p->pEList );
101509 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
101510 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
101511 dest.eDest = SRT_Table;
101514 /* Make sure all SELECTs in the statement have the same number of elements
101515 ** in their result sets.
101517 assert( p->pEList && pPrior->pEList );
101518 if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
101519 if( p->selFlags & SF_Values ){
101520 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
101521 }else{
101522 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
101523 " do not have the same number of result columns", selectOpName(p->op));
101525 rc = 1;
101526 goto multi_select_end;
101529 #ifndef SQLITE_OMIT_CTE
101530 if( p->selFlags & SF_Recursive ){
101531 generateWithRecursiveQuery(pParse, p, &dest);
101532 }else
101533 #endif
101535 /* Compound SELECTs that have an ORDER BY clause are handled separately.
101537 if( p->pOrderBy ){
101538 return multiSelectOrderBy(pParse, p, pDest);
101539 }else
101541 /* Generate code for the left and right SELECT statements.
101543 switch( p->op ){
101544 case TK_ALL: {
101545 int addr = 0;
101546 int nLimit;
101547 assert( !pPrior->pLimit );
101548 pPrior->iLimit = p->iLimit;
101549 pPrior->iOffset = p->iOffset;
101550 pPrior->pLimit = p->pLimit;
101551 pPrior->pOffset = p->pOffset;
101552 explainSetInteger(iSub1, pParse->iNextSelectId);
101553 rc = sqlite3Select(pParse, pPrior, &dest);
101554 p->pLimit = 0;
101555 p->pOffset = 0;
101556 if( rc ){
101557 goto multi_select_end;
101559 p->pPrior = 0;
101560 p->iLimit = pPrior->iLimit;
101561 p->iOffset = pPrior->iOffset;
101562 if( p->iLimit ){
101563 addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
101564 VdbeComment((v, "Jump ahead if LIMIT reached"));
101566 explainSetInteger(iSub2, pParse->iNextSelectId);
101567 rc = sqlite3Select(pParse, p, &dest);
101568 testcase( rc!=SQLITE_OK );
101569 pDelete = p->pPrior;
101570 p->pPrior = pPrior;
101571 p->nSelectRow += pPrior->nSelectRow;
101572 if( pPrior->pLimit
101573 && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
101574 && nLimit>0 && p->nSelectRow > (u64)nLimit
101576 p->nSelectRow = nLimit;
101578 if( addr ){
101579 sqlite3VdbeJumpHere(v, addr);
101581 break;
101583 case TK_EXCEPT:
101584 case TK_UNION: {
101585 int unionTab; /* Cursor number of the temporary table holding result */
101586 u8 op = 0; /* One of the SRT_ operations to apply to self */
101587 int priorOp; /* The SRT_ operation to apply to prior selects */
101588 Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
101589 int addr;
101590 SelectDest uniondest;
101592 testcase( p->op==TK_EXCEPT );
101593 testcase( p->op==TK_UNION );
101594 priorOp = SRT_Union;
101595 if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
101596 /* We can reuse a temporary table generated by a SELECT to our
101597 ** right.
101599 assert( p->pRightmost!=p ); /* Can only happen for leftward elements
101600 ** of a 3-way or more compound */
101601 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
101602 assert( p->pOffset==0 ); /* Not allowed on leftward elements */
101603 unionTab = dest.iSDParm;
101604 }else{
101605 /* We will need to create our own temporary table to hold the
101606 ** intermediate results.
101608 unionTab = pParse->nTab++;
101609 assert( p->pOrderBy==0 );
101610 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
101611 assert( p->addrOpenEphm[0] == -1 );
101612 p->addrOpenEphm[0] = addr;
101613 p->pRightmost->selFlags |= SF_UsesEphemeral;
101614 assert( p->pEList );
101617 /* Code the SELECT statements to our left
101619 assert( !pPrior->pOrderBy );
101620 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
101621 explainSetInteger(iSub1, pParse->iNextSelectId);
101622 rc = sqlite3Select(pParse, pPrior, &uniondest);
101623 if( rc ){
101624 goto multi_select_end;
101627 /* Code the current SELECT statement
101629 if( p->op==TK_EXCEPT ){
101630 op = SRT_Except;
101631 }else{
101632 assert( p->op==TK_UNION );
101633 op = SRT_Union;
101635 p->pPrior = 0;
101636 pLimit = p->pLimit;
101637 p->pLimit = 0;
101638 pOffset = p->pOffset;
101639 p->pOffset = 0;
101640 uniondest.eDest = op;
101641 explainSetInteger(iSub2, pParse->iNextSelectId);
101642 rc = sqlite3Select(pParse, p, &uniondest);
101643 testcase( rc!=SQLITE_OK );
101644 /* Query flattening in sqlite3Select() might refill p->pOrderBy.
101645 ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
101646 sqlite3ExprListDelete(db, p->pOrderBy);
101647 pDelete = p->pPrior;
101648 p->pPrior = pPrior;
101649 p->pOrderBy = 0;
101650 if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
101651 sqlite3ExprDelete(db, p->pLimit);
101652 p->pLimit = pLimit;
101653 p->pOffset = pOffset;
101654 p->iLimit = 0;
101655 p->iOffset = 0;
101657 /* Convert the data in the temporary table into whatever form
101658 ** it is that we currently need.
101660 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
101661 if( dest.eDest!=priorOp ){
101662 int iCont, iBreak, iStart;
101663 assert( p->pEList );
101664 if( dest.eDest==SRT_Output ){
101665 Select *pFirst = p;
101666 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
101667 generateColumnNames(pParse, 0, pFirst->pEList);
101669 iBreak = sqlite3VdbeMakeLabel(v);
101670 iCont = sqlite3VdbeMakeLabel(v);
101671 computeLimitRegisters(pParse, p, iBreak);
101672 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
101673 iStart = sqlite3VdbeCurrentAddr(v);
101674 selectInnerLoop(pParse, p, p->pEList, unionTab,
101675 0, 0, &dest, iCont, iBreak);
101676 sqlite3VdbeResolveLabel(v, iCont);
101677 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
101678 sqlite3VdbeResolveLabel(v, iBreak);
101679 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
101681 break;
101683 default: assert( p->op==TK_INTERSECT ); {
101684 int tab1, tab2;
101685 int iCont, iBreak, iStart;
101686 Expr *pLimit, *pOffset;
101687 int addr;
101688 SelectDest intersectdest;
101689 int r1;
101691 /* INTERSECT is different from the others since it requires
101692 ** two temporary tables. Hence it has its own case. Begin
101693 ** by allocating the tables we will need.
101695 tab1 = pParse->nTab++;
101696 tab2 = pParse->nTab++;
101697 assert( p->pOrderBy==0 );
101699 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
101700 assert( p->addrOpenEphm[0] == -1 );
101701 p->addrOpenEphm[0] = addr;
101702 p->pRightmost->selFlags |= SF_UsesEphemeral;
101703 assert( p->pEList );
101705 /* Code the SELECTs to our left into temporary table "tab1".
101707 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
101708 explainSetInteger(iSub1, pParse->iNextSelectId);
101709 rc = sqlite3Select(pParse, pPrior, &intersectdest);
101710 if( rc ){
101711 goto multi_select_end;
101714 /* Code the current SELECT into temporary table "tab2"
101716 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
101717 assert( p->addrOpenEphm[1] == -1 );
101718 p->addrOpenEphm[1] = addr;
101719 p->pPrior = 0;
101720 pLimit = p->pLimit;
101721 p->pLimit = 0;
101722 pOffset = p->pOffset;
101723 p->pOffset = 0;
101724 intersectdest.iSDParm = tab2;
101725 explainSetInteger(iSub2, pParse->iNextSelectId);
101726 rc = sqlite3Select(pParse, p, &intersectdest);
101727 testcase( rc!=SQLITE_OK );
101728 pDelete = p->pPrior;
101729 p->pPrior = pPrior;
101730 if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
101731 sqlite3ExprDelete(db, p->pLimit);
101732 p->pLimit = pLimit;
101733 p->pOffset = pOffset;
101735 /* Generate code to take the intersection of the two temporary
101736 ** tables.
101738 assert( p->pEList );
101739 if( dest.eDest==SRT_Output ){
101740 Select *pFirst = p;
101741 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
101742 generateColumnNames(pParse, 0, pFirst->pEList);
101744 iBreak = sqlite3VdbeMakeLabel(v);
101745 iCont = sqlite3VdbeMakeLabel(v);
101746 computeLimitRegisters(pParse, p, iBreak);
101747 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
101748 r1 = sqlite3GetTempReg(pParse);
101749 iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
101750 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
101751 sqlite3ReleaseTempReg(pParse, r1);
101752 selectInnerLoop(pParse, p, p->pEList, tab1,
101753 0, 0, &dest, iCont, iBreak);
101754 sqlite3VdbeResolveLabel(v, iCont);
101755 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
101756 sqlite3VdbeResolveLabel(v, iBreak);
101757 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
101758 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
101759 break;
101763 explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
101765 /* Compute collating sequences used by
101766 ** temporary tables needed to implement the compound select.
101767 ** Attach the KeyInfo structure to all temporary tables.
101769 ** This section is run by the right-most SELECT statement only.
101770 ** SELECT statements to the left always skip this part. The right-most
101771 ** SELECT might also skip this part if it has no ORDER BY clause and
101772 ** no temp tables are required.
101774 if( p->selFlags & SF_UsesEphemeral ){
101775 int i; /* Loop counter */
101776 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
101777 Select *pLoop; /* For looping through SELECT statements */
101778 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
101779 int nCol; /* Number of columns in result set */
101781 assert( p->pRightmost==p );
101782 nCol = p->pEList->nExpr;
101783 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
101784 if( !pKeyInfo ){
101785 rc = SQLITE_NOMEM;
101786 goto multi_select_end;
101788 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
101789 *apColl = multiSelectCollSeq(pParse, p, i);
101790 if( 0==*apColl ){
101791 *apColl = db->pDfltColl;
101795 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
101796 for(i=0; i<2; i++){
101797 int addr = pLoop->addrOpenEphm[i];
101798 if( addr<0 ){
101799 /* If [0] is unused then [1] is also unused. So we can
101800 ** always safely abort as soon as the first unused slot is found */
101801 assert( pLoop->addrOpenEphm[1]<0 );
101802 break;
101804 sqlite3VdbeChangeP2(v, addr, nCol);
101805 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
101806 P4_KEYINFO);
101807 pLoop->addrOpenEphm[i] = -1;
101810 sqlite3KeyInfoUnref(pKeyInfo);
101813 multi_select_end:
101814 pDest->iSdst = dest.iSdst;
101815 pDest->nSdst = dest.nSdst;
101816 sqlite3SelectDelete(db, pDelete);
101817 return rc;
101819 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
101822 ** Code an output subroutine for a coroutine implementation of a
101823 ** SELECT statment.
101825 ** The data to be output is contained in pIn->iSdst. There are
101826 ** pIn->nSdst columns to be output. pDest is where the output should
101827 ** be sent.
101829 ** regReturn is the number of the register holding the subroutine
101830 ** return address.
101832 ** If regPrev>0 then it is the first register in a vector that
101833 ** records the previous output. mem[regPrev] is a flag that is false
101834 ** if there has been no previous output. If regPrev>0 then code is
101835 ** generated to suppress duplicates. pKeyInfo is used for comparing
101836 ** keys.
101838 ** If the LIMIT found in p->iLimit is reached, jump immediately to
101839 ** iBreak.
101841 static int generateOutputSubroutine(
101842 Parse *pParse, /* Parsing context */
101843 Select *p, /* The SELECT statement */
101844 SelectDest *pIn, /* Coroutine supplying data */
101845 SelectDest *pDest, /* Where to send the data */
101846 int regReturn, /* The return address register */
101847 int regPrev, /* Previous result register. No uniqueness if 0 */
101848 KeyInfo *pKeyInfo, /* For comparing with previous entry */
101849 int iBreak /* Jump here if we hit the LIMIT */
101851 Vdbe *v = pParse->pVdbe;
101852 int iContinue;
101853 int addr;
101855 addr = sqlite3VdbeCurrentAddr(v);
101856 iContinue = sqlite3VdbeMakeLabel(v);
101858 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
101860 if( regPrev ){
101861 int j1, j2;
101862 j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
101863 j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
101864 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
101865 sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
101866 sqlite3VdbeJumpHere(v, j1);
101867 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
101868 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
101870 if( pParse->db->mallocFailed ) return 0;
101872 /* Suppress the first OFFSET entries if there is an OFFSET clause
101874 codeOffset(v, p->iOffset, iContinue);
101876 switch( pDest->eDest ){
101877 /* Store the result as data using a unique key.
101879 case SRT_Table:
101880 case SRT_EphemTab: {
101881 int r1 = sqlite3GetTempReg(pParse);
101882 int r2 = sqlite3GetTempReg(pParse);
101883 testcase( pDest->eDest==SRT_Table );
101884 testcase( pDest->eDest==SRT_EphemTab );
101885 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
101886 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
101887 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
101888 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
101889 sqlite3ReleaseTempReg(pParse, r2);
101890 sqlite3ReleaseTempReg(pParse, r1);
101891 break;
101894 #ifndef SQLITE_OMIT_SUBQUERY
101895 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
101896 ** then there should be a single item on the stack. Write this
101897 ** item into the set table with bogus data.
101899 case SRT_Set: {
101900 int r1;
101901 assert( pIn->nSdst==1 );
101902 pDest->affSdst =
101903 sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
101904 r1 = sqlite3GetTempReg(pParse);
101905 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
101906 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
101907 sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
101908 sqlite3ReleaseTempReg(pParse, r1);
101909 break;
101912 #if 0 /* Never occurs on an ORDER BY query */
101913 /* If any row exist in the result set, record that fact and abort.
101915 case SRT_Exists: {
101916 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
101917 /* The LIMIT clause will terminate the loop for us */
101918 break;
101920 #endif
101922 /* If this is a scalar select that is part of an expression, then
101923 ** store the results in the appropriate memory cell and break out
101924 ** of the scan loop.
101926 case SRT_Mem: {
101927 assert( pIn->nSdst==1 );
101928 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
101929 /* The LIMIT clause will jump out of the loop for us */
101930 break;
101932 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
101934 /* The results are stored in a sequence of registers
101935 ** starting at pDest->iSdst. Then the co-routine yields.
101937 case SRT_Coroutine: {
101938 if( pDest->iSdst==0 ){
101939 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
101940 pDest->nSdst = pIn->nSdst;
101942 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
101943 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
101944 break;
101947 /* If none of the above, then the result destination must be
101948 ** SRT_Output. This routine is never called with any other
101949 ** destination other than the ones handled above or SRT_Output.
101951 ** For SRT_Output, results are stored in a sequence of registers.
101952 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
101953 ** return the next row of result.
101955 default: {
101956 assert( pDest->eDest==SRT_Output );
101957 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
101958 sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
101959 break;
101963 /* Jump to the end of the loop if the LIMIT is reached.
101965 if( p->iLimit ){
101966 sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
101969 /* Generate the subroutine return
101971 sqlite3VdbeResolveLabel(v, iContinue);
101972 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
101974 return addr;
101978 ** Alternative compound select code generator for cases when there
101979 ** is an ORDER BY clause.
101981 ** We assume a query of the following form:
101983 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
101985 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
101986 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
101987 ** co-routines. Then run the co-routines in parallel and merge the results
101988 ** into the output. In addition to the two coroutines (called selectA and
101989 ** selectB) there are 7 subroutines:
101991 ** outA: Move the output of the selectA coroutine into the output
101992 ** of the compound query.
101994 ** outB: Move the output of the selectB coroutine into the output
101995 ** of the compound query. (Only generated for UNION and
101996 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
101997 ** appears only in B.)
101999 ** AltB: Called when there is data from both coroutines and A<B.
102001 ** AeqB: Called when there is data from both coroutines and A==B.
102003 ** AgtB: Called when there is data from both coroutines and A>B.
102005 ** EofA: Called when data is exhausted from selectA.
102007 ** EofB: Called when data is exhausted from selectB.
102009 ** The implementation of the latter five subroutines depend on which
102010 ** <operator> is used:
102013 ** UNION ALL UNION EXCEPT INTERSECT
102014 ** ------------- ----------------- -------------- -----------------
102015 ** AltB: outA, nextA outA, nextA outA, nextA nextA
102017 ** AeqB: outA, nextA nextA nextA outA, nextA
102019 ** AgtB: outB, nextB outB, nextB nextB nextB
102021 ** EofA: outB, nextB outB, nextB halt halt
102023 ** EofB: outA, nextA outA, nextA outA, nextA halt
102025 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
102026 ** causes an immediate jump to EofA and an EOF on B following nextB causes
102027 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
102028 ** following nextX causes a jump to the end of the select processing.
102030 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
102031 ** within the output subroutine. The regPrev register set holds the previously
102032 ** output value. A comparison is made against this value and the output
102033 ** is skipped if the next results would be the same as the previous.
102035 ** The implementation plan is to implement the two coroutines and seven
102036 ** subroutines first, then put the control logic at the bottom. Like this:
102038 ** goto Init
102039 ** coA: coroutine for left query (A)
102040 ** coB: coroutine for right query (B)
102041 ** outA: output one row of A
102042 ** outB: output one row of B (UNION and UNION ALL only)
102043 ** EofA: ...
102044 ** EofB: ...
102045 ** AltB: ...
102046 ** AeqB: ...
102047 ** AgtB: ...
102048 ** Init: initialize coroutine registers
102049 ** yield coA
102050 ** if eof(A) goto EofA
102051 ** yield coB
102052 ** if eof(B) goto EofB
102053 ** Cmpr: Compare A, B
102054 ** Jump AltB, AeqB, AgtB
102055 ** End: ...
102057 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
102058 ** actually called using Gosub and they do not Return. EofA and EofB loop
102059 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
102060 ** and AgtB jump to either L2 or to one of EofA or EofB.
102062 #ifndef SQLITE_OMIT_COMPOUND_SELECT
102063 static int multiSelectOrderBy(
102064 Parse *pParse, /* Parsing context */
102065 Select *p, /* The right-most of SELECTs to be coded */
102066 SelectDest *pDest /* What to do with query results */
102068 int i, j; /* Loop counters */
102069 Select *pPrior; /* Another SELECT immediately to our left */
102070 Vdbe *v; /* Generate code to this VDBE */
102071 SelectDest destA; /* Destination for coroutine A */
102072 SelectDest destB; /* Destination for coroutine B */
102073 int regAddrA; /* Address register for select-A coroutine */
102074 int regEofA; /* Flag to indicate when select-A is complete */
102075 int regAddrB; /* Address register for select-B coroutine */
102076 int regEofB; /* Flag to indicate when select-B is complete */
102077 int addrSelectA; /* Address of the select-A coroutine */
102078 int addrSelectB; /* Address of the select-B coroutine */
102079 int regOutA; /* Address register for the output-A subroutine */
102080 int regOutB; /* Address register for the output-B subroutine */
102081 int addrOutA; /* Address of the output-A subroutine */
102082 int addrOutB = 0; /* Address of the output-B subroutine */
102083 int addrEofA; /* Address of the select-A-exhausted subroutine */
102084 int addrEofB; /* Address of the select-B-exhausted subroutine */
102085 int addrAltB; /* Address of the A<B subroutine */
102086 int addrAeqB; /* Address of the A==B subroutine */
102087 int addrAgtB; /* Address of the A>B subroutine */
102088 int regLimitA; /* Limit register for select-A */
102089 int regLimitB; /* Limit register for select-A */
102090 int regPrev; /* A range of registers to hold previous output */
102091 int savedLimit; /* Saved value of p->iLimit */
102092 int savedOffset; /* Saved value of p->iOffset */
102093 int labelCmpr; /* Label for the start of the merge algorithm */
102094 int labelEnd; /* Label for the end of the overall SELECT stmt */
102095 int j1; /* Jump instructions that get retargetted */
102096 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
102097 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
102098 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
102099 sqlite3 *db; /* Database connection */
102100 ExprList *pOrderBy; /* The ORDER BY clause */
102101 int nOrderBy; /* Number of terms in the ORDER BY clause */
102102 int *aPermute; /* Mapping from ORDER BY terms to result set columns */
102103 #ifndef SQLITE_OMIT_EXPLAIN
102104 int iSub1; /* EQP id of left-hand query */
102105 int iSub2; /* EQP id of right-hand query */
102106 #endif
102108 assert( p->pOrderBy!=0 );
102109 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
102110 db = pParse->db;
102111 v = pParse->pVdbe;
102112 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
102113 labelEnd = sqlite3VdbeMakeLabel(v);
102114 labelCmpr = sqlite3VdbeMakeLabel(v);
102117 /* Patch up the ORDER BY clause
102119 op = p->op;
102120 pPrior = p->pPrior;
102121 assert( pPrior->pOrderBy==0 );
102122 pOrderBy = p->pOrderBy;
102123 assert( pOrderBy );
102124 nOrderBy = pOrderBy->nExpr;
102126 /* For operators other than UNION ALL we have to make sure that
102127 ** the ORDER BY clause covers every term of the result set. Add
102128 ** terms to the ORDER BY clause as necessary.
102130 if( op!=TK_ALL ){
102131 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
102132 struct ExprList_item *pItem;
102133 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
102134 assert( pItem->u.x.iOrderByCol>0 );
102135 if( pItem->u.x.iOrderByCol==i ) break;
102137 if( j==nOrderBy ){
102138 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
102139 if( pNew==0 ) return SQLITE_NOMEM;
102140 pNew->flags |= EP_IntValue;
102141 pNew->u.iValue = i;
102142 pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
102143 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
102148 /* Compute the comparison permutation and keyinfo that is used with
102149 ** the permutation used to determine if the next
102150 ** row of results comes from selectA or selectB. Also add explicit
102151 ** collations to the ORDER BY clause terms so that when the subqueries
102152 ** to the right and the left are evaluated, they use the correct
102153 ** collation.
102155 aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
102156 if( aPermute ){
102157 struct ExprList_item *pItem;
102158 for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
102159 assert( pItem->u.x.iOrderByCol>0
102160 && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
102161 aPermute[i] = pItem->u.x.iOrderByCol - 1;
102163 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
102164 }else{
102165 pKeyMerge = 0;
102168 /* Reattach the ORDER BY clause to the query.
102170 p->pOrderBy = pOrderBy;
102171 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
102173 /* Allocate a range of temporary registers and the KeyInfo needed
102174 ** for the logic that removes duplicate result rows when the
102175 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
102177 if( op==TK_ALL ){
102178 regPrev = 0;
102179 }else{
102180 int nExpr = p->pEList->nExpr;
102181 assert( nOrderBy>=nExpr || db->mallocFailed );
102182 regPrev = pParse->nMem+1;
102183 pParse->nMem += nExpr+1;
102184 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
102185 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
102186 if( pKeyDup ){
102187 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
102188 for(i=0; i<nExpr; i++){
102189 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
102190 pKeyDup->aSortOrder[i] = 0;
102195 /* Separate the left and the right query from one another
102197 p->pPrior = 0;
102198 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
102199 if( pPrior->pPrior==0 ){
102200 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
102203 /* Compute the limit registers */
102204 computeLimitRegisters(pParse, p, labelEnd);
102205 if( p->iLimit && op==TK_ALL ){
102206 regLimitA = ++pParse->nMem;
102207 regLimitB = ++pParse->nMem;
102208 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
102209 regLimitA);
102210 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
102211 }else{
102212 regLimitA = regLimitB = 0;
102214 sqlite3ExprDelete(db, p->pLimit);
102215 p->pLimit = 0;
102216 sqlite3ExprDelete(db, p->pOffset);
102217 p->pOffset = 0;
102219 regAddrA = ++pParse->nMem;
102220 regEofA = ++pParse->nMem;
102221 regAddrB = ++pParse->nMem;
102222 regEofB = ++pParse->nMem;
102223 regOutA = ++pParse->nMem;
102224 regOutB = ++pParse->nMem;
102225 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
102226 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
102228 /* Jump past the various subroutines and coroutines to the main
102229 ** merge loop
102231 j1 = sqlite3VdbeAddOp0(v, OP_Goto);
102232 addrSelectA = sqlite3VdbeCurrentAddr(v);
102235 /* Generate a coroutine to evaluate the SELECT statement to the
102236 ** left of the compound operator - the "A" select.
102238 VdbeNoopComment((v, "Begin coroutine for left SELECT"));
102239 pPrior->iLimit = regLimitA;
102240 explainSetInteger(iSub1, pParse->iNextSelectId);
102241 sqlite3Select(pParse, pPrior, &destA);
102242 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
102243 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
102244 VdbeNoopComment((v, "End coroutine for left SELECT"));
102246 /* Generate a coroutine to evaluate the SELECT statement on
102247 ** the right - the "B" select
102249 addrSelectB = sqlite3VdbeCurrentAddr(v);
102250 VdbeNoopComment((v, "Begin coroutine for right SELECT"));
102251 savedLimit = p->iLimit;
102252 savedOffset = p->iOffset;
102253 p->iLimit = regLimitB;
102254 p->iOffset = 0;
102255 explainSetInteger(iSub2, pParse->iNextSelectId);
102256 sqlite3Select(pParse, p, &destB);
102257 p->iLimit = savedLimit;
102258 p->iOffset = savedOffset;
102259 sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
102260 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
102261 VdbeNoopComment((v, "End coroutine for right SELECT"));
102263 /* Generate a subroutine that outputs the current row of the A
102264 ** select as the next output row of the compound select.
102266 VdbeNoopComment((v, "Output routine for A"));
102267 addrOutA = generateOutputSubroutine(pParse,
102268 p, &destA, pDest, regOutA,
102269 regPrev, pKeyDup, labelEnd);
102271 /* Generate a subroutine that outputs the current row of the B
102272 ** select as the next output row of the compound select.
102274 if( op==TK_ALL || op==TK_UNION ){
102275 VdbeNoopComment((v, "Output routine for B"));
102276 addrOutB = generateOutputSubroutine(pParse,
102277 p, &destB, pDest, regOutB,
102278 regPrev, pKeyDup, labelEnd);
102280 sqlite3KeyInfoUnref(pKeyDup);
102282 /* Generate a subroutine to run when the results from select A
102283 ** are exhausted and only data in select B remains.
102285 VdbeNoopComment((v, "eof-A subroutine"));
102286 if( op==TK_EXCEPT || op==TK_INTERSECT ){
102287 addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
102288 }else{
102289 addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
102290 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
102291 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
102292 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
102293 p->nSelectRow += pPrior->nSelectRow;
102296 /* Generate a subroutine to run when the results from select B
102297 ** are exhausted and only data in select A remains.
102299 if( op==TK_INTERSECT ){
102300 addrEofB = addrEofA;
102301 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
102302 }else{
102303 VdbeNoopComment((v, "eof-B subroutine"));
102304 addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
102305 sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
102306 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
102307 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
102310 /* Generate code to handle the case of A<B
102312 VdbeNoopComment((v, "A-lt-B subroutine"));
102313 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
102314 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
102315 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
102316 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
102318 /* Generate code to handle the case of A==B
102320 if( op==TK_ALL ){
102321 addrAeqB = addrAltB;
102322 }else if( op==TK_INTERSECT ){
102323 addrAeqB = addrAltB;
102324 addrAltB++;
102325 }else{
102326 VdbeNoopComment((v, "A-eq-B subroutine"));
102327 addrAeqB =
102328 sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
102329 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
102330 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
102333 /* Generate code to handle the case of A>B
102335 VdbeNoopComment((v, "A-gt-B subroutine"));
102336 addrAgtB = sqlite3VdbeCurrentAddr(v);
102337 if( op==TK_ALL || op==TK_UNION ){
102338 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
102340 sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
102341 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
102342 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
102344 /* This code runs once to initialize everything.
102346 sqlite3VdbeJumpHere(v, j1);
102347 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
102348 sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
102349 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
102350 sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
102351 sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
102352 sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
102354 /* Implement the main merge loop
102356 sqlite3VdbeResolveLabel(v, labelCmpr);
102357 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
102358 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
102359 (char*)pKeyMerge, P4_KEYINFO);
102360 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
102361 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
102363 /* Jump to the this point in order to terminate the query.
102365 sqlite3VdbeResolveLabel(v, labelEnd);
102367 /* Set the number of output columns
102369 if( pDest->eDest==SRT_Output ){
102370 Select *pFirst = pPrior;
102371 while( pFirst->pPrior ) pFirst = pFirst->pPrior;
102372 generateColumnNames(pParse, 0, pFirst->pEList);
102375 /* Reassembly the compound query so that it will be freed correctly
102376 ** by the calling function */
102377 if( p->pPrior ){
102378 sqlite3SelectDelete(db, p->pPrior);
102380 p->pPrior = pPrior;
102382 /*** TBD: Insert subroutine calls to close cursors on incomplete
102383 **** subqueries ****/
102384 explainComposite(pParse, p->op, iSub1, iSub2, 0);
102385 return SQLITE_OK;
102387 #endif
102389 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
102390 /* Forward Declarations */
102391 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
102392 static void substSelect(sqlite3*, Select *, int, ExprList *);
102395 ** Scan through the expression pExpr. Replace every reference to
102396 ** a column in table number iTable with a copy of the iColumn-th
102397 ** entry in pEList. (But leave references to the ROWID column
102398 ** unchanged.)
102400 ** This routine is part of the flattening procedure. A subquery
102401 ** whose result set is defined by pEList appears as entry in the
102402 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
102403 ** FORM clause entry is iTable. This routine make the necessary
102404 ** changes to pExpr so that it refers directly to the source table
102405 ** of the subquery rather the result set of the subquery.
102407 static Expr *substExpr(
102408 sqlite3 *db, /* Report malloc errors to this connection */
102409 Expr *pExpr, /* Expr in which substitution occurs */
102410 int iTable, /* Table to be substituted */
102411 ExprList *pEList /* Substitute expressions */
102413 if( pExpr==0 ) return 0;
102414 if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
102415 if( pExpr->iColumn<0 ){
102416 pExpr->op = TK_NULL;
102417 }else{
102418 Expr *pNew;
102419 assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
102420 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
102421 pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
102422 sqlite3ExprDelete(db, pExpr);
102423 pExpr = pNew;
102425 }else{
102426 pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
102427 pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
102428 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
102429 substSelect(db, pExpr->x.pSelect, iTable, pEList);
102430 }else{
102431 substExprList(db, pExpr->x.pList, iTable, pEList);
102434 return pExpr;
102436 static void substExprList(
102437 sqlite3 *db, /* Report malloc errors here */
102438 ExprList *pList, /* List to scan and in which to make substitutes */
102439 int iTable, /* Table to be substituted */
102440 ExprList *pEList /* Substitute values */
102442 int i;
102443 if( pList==0 ) return;
102444 for(i=0; i<pList->nExpr; i++){
102445 pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
102448 static void substSelect(
102449 sqlite3 *db, /* Report malloc errors here */
102450 Select *p, /* SELECT statement in which to make substitutions */
102451 int iTable, /* Table to be replaced */
102452 ExprList *pEList /* Substitute values */
102454 SrcList *pSrc;
102455 struct SrcList_item *pItem;
102456 int i;
102457 if( !p ) return;
102458 substExprList(db, p->pEList, iTable, pEList);
102459 substExprList(db, p->pGroupBy, iTable, pEList);
102460 substExprList(db, p->pOrderBy, iTable, pEList);
102461 p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
102462 p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
102463 substSelect(db, p->pPrior, iTable, pEList);
102464 pSrc = p->pSrc;
102465 assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
102466 if( ALWAYS(pSrc) ){
102467 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
102468 substSelect(db, pItem->pSelect, iTable, pEList);
102472 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
102474 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
102476 ** This routine attempts to flatten subqueries as a performance optimization.
102477 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
102479 ** To understand the concept of flattening, consider the following
102480 ** query:
102482 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
102484 ** The default way of implementing this query is to execute the
102485 ** subquery first and store the results in a temporary table, then
102486 ** run the outer query on that temporary table. This requires two
102487 ** passes over the data. Furthermore, because the temporary table
102488 ** has no indices, the WHERE clause on the outer query cannot be
102489 ** optimized.
102491 ** This routine attempts to rewrite queries such as the above into
102492 ** a single flat select, like this:
102494 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
102496 ** The code generated for this simpification gives the same result
102497 ** but only has to scan the data once. And because indices might
102498 ** exist on the table t1, a complete scan of the data might be
102499 ** avoided.
102501 ** Flattening is only attempted if all of the following are true:
102503 ** (1) The subquery and the outer query do not both use aggregates.
102505 ** (2) The subquery is not an aggregate or the outer query is not a join.
102507 ** (3) The subquery is not the right operand of a left outer join
102508 ** (Originally ticket #306. Strengthened by ticket #3300)
102510 ** (4) The subquery is not DISTINCT.
102512 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
102513 ** sub-queries that were excluded from this optimization. Restriction
102514 ** (4) has since been expanded to exclude all DISTINCT subqueries.
102516 ** (6) The subquery does not use aggregates or the outer query is not
102517 ** DISTINCT.
102519 ** (7) The subquery has a FROM clause. TODO: For subqueries without
102520 ** A FROM clause, consider adding a FROM close with the special
102521 ** table sqlite_once that consists of a single row containing a
102522 ** single NULL.
102524 ** (8) The subquery does not use LIMIT or the outer query is not a join.
102526 ** (9) The subquery does not use LIMIT or the outer query does not use
102527 ** aggregates.
102529 ** (10) The subquery does not use aggregates or the outer query does not
102530 ** use LIMIT.
102532 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
102534 ** (**) Not implemented. Subsumed into restriction (3). Was previously
102535 ** a separate restriction deriving from ticket #350.
102537 ** (13) The subquery and outer query do not both use LIMIT.
102539 ** (14) The subquery does not use OFFSET.
102541 ** (15) The outer query is not part of a compound select or the
102542 ** subquery does not have a LIMIT clause.
102543 ** (See ticket #2339 and ticket [02a8e81d44]).
102545 ** (16) The outer query is not an aggregate or the subquery does
102546 ** not contain ORDER BY. (Ticket #2942) This used to not matter
102547 ** until we introduced the group_concat() function.
102549 ** (17) The sub-query is not a compound select, or it is a UNION ALL
102550 ** compound clause made up entirely of non-aggregate queries, and
102551 ** the parent query:
102553 ** * is not itself part of a compound select,
102554 ** * is not an aggregate or DISTINCT query, and
102555 ** * is not a join
102557 ** The parent and sub-query may contain WHERE clauses. Subject to
102558 ** rules (11), (13) and (14), they may also contain ORDER BY,
102559 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
102560 ** operator other than UNION ALL because all the other compound
102561 ** operators have an implied DISTINCT which is disallowed by
102562 ** restriction (4).
102564 ** Also, each component of the sub-query must return the same number
102565 ** of result columns. This is actually a requirement for any compound
102566 ** SELECT statement, but all the code here does is make sure that no
102567 ** such (illegal) sub-query is flattened. The caller will detect the
102568 ** syntax error and return a detailed message.
102570 ** (18) If the sub-query is a compound select, then all terms of the
102571 ** ORDER by clause of the parent must be simple references to
102572 ** columns of the sub-query.
102574 ** (19) The subquery does not use LIMIT or the outer query does not
102575 ** have a WHERE clause.
102577 ** (20) If the sub-query is a compound select, then it must not use
102578 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
102579 ** somewhat by saying that the terms of the ORDER BY clause must
102580 ** appear as unmodified result columns in the outer query. But we
102581 ** have other optimizations in mind to deal with that case.
102583 ** (21) The subquery does not use LIMIT or the outer query is not
102584 ** DISTINCT. (See ticket [752e1646fc]).
102586 ** (22) The subquery is not a recursive CTE.
102588 ** (23) The parent is not a recursive CTE, or the sub-query is not a
102589 ** compound query. This restriction is because transforming the
102590 ** parent to a compound query confuses the code that handles
102591 ** recursive queries in multiSelect().
102594 ** In this routine, the "p" parameter is a pointer to the outer query.
102595 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
102596 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
102598 ** If flattening is not attempted, this routine is a no-op and returns 0.
102599 ** If flattening is attempted this routine returns 1.
102601 ** All of the expression analysis must occur on both the outer query and
102602 ** the subquery before this routine runs.
102604 static int flattenSubquery(
102605 Parse *pParse, /* Parsing context */
102606 Select *p, /* The parent or outer SELECT statement */
102607 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
102608 int isAgg, /* True if outer SELECT uses aggregate functions */
102609 int subqueryIsAgg /* True if the subquery uses aggregate functions */
102611 const char *zSavedAuthContext = pParse->zAuthContext;
102612 Select *pParent;
102613 Select *pSub; /* The inner query or "subquery" */
102614 Select *pSub1; /* Pointer to the rightmost select in sub-query */
102615 SrcList *pSrc; /* The FROM clause of the outer query */
102616 SrcList *pSubSrc; /* The FROM clause of the subquery */
102617 ExprList *pList; /* The result set of the outer query */
102618 int iParent; /* VDBE cursor number of the pSub result set temp table */
102619 int i; /* Loop counter */
102620 Expr *pWhere; /* The WHERE clause */
102621 struct SrcList_item *pSubitem; /* The subquery */
102622 sqlite3 *db = pParse->db;
102624 /* Check to see if flattening is permitted. Return 0 if not.
102626 assert( p!=0 );
102627 assert( p->pPrior==0 ); /* Unable to flatten compound queries */
102628 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
102629 pSrc = p->pSrc;
102630 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
102631 pSubitem = &pSrc->a[iFrom];
102632 iParent = pSubitem->iCursor;
102633 pSub = pSubitem->pSelect;
102634 assert( pSub!=0 );
102635 if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
102636 if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
102637 pSubSrc = pSub->pSrc;
102638 assert( pSubSrc );
102639 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
102640 ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
102641 ** because they could be computed at compile-time. But when LIMIT and OFFSET
102642 ** became arbitrary expressions, we were forced to add restrictions (13)
102643 ** and (14). */
102644 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
102645 if( pSub->pOffset ) return 0; /* Restriction (14) */
102646 if( p->pRightmost && pSub->pLimit ){
102647 return 0; /* Restriction (15) */
102649 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
102650 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
102651 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
102652 return 0; /* Restrictions (8)(9) */
102654 if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
102655 return 0; /* Restriction (6) */
102657 if( p->pOrderBy && pSub->pOrderBy ){
102658 return 0; /* Restriction (11) */
102660 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
102661 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
102662 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
102663 return 0; /* Restriction (21) */
102665 if( pSub->selFlags & SF_Recursive ) return 0; /* Restriction (22) */
102666 if( (p->selFlags & SF_Recursive) && pSub->pPrior ) return 0; /* (23) */
102668 /* OBSOLETE COMMENT 1:
102669 ** Restriction 3: If the subquery is a join, make sure the subquery is
102670 ** not used as the right operand of an outer join. Examples of why this
102671 ** is not allowed:
102673 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
102675 ** If we flatten the above, we would get
102677 ** (t1 LEFT OUTER JOIN t2) JOIN t3
102679 ** which is not at all the same thing.
102681 ** OBSOLETE COMMENT 2:
102682 ** Restriction 12: If the subquery is the right operand of a left outer
102683 ** join, make sure the subquery has no WHERE clause.
102684 ** An examples of why this is not allowed:
102686 ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
102688 ** If we flatten the above, we would get
102690 ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
102692 ** But the t2.x>0 test will always fail on a NULL row of t2, which
102693 ** effectively converts the OUTER JOIN into an INNER JOIN.
102695 ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
102696 ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
102697 ** is fraught with danger. Best to avoid the whole thing. If the
102698 ** subquery is the right term of a LEFT JOIN, then do not flatten.
102700 if( (pSubitem->jointype & JT_OUTER)!=0 ){
102701 return 0;
102704 /* Restriction 17: If the sub-query is a compound SELECT, then it must
102705 ** use only the UNION ALL operator. And none of the simple select queries
102706 ** that make up the compound SELECT are allowed to be aggregate or distinct
102707 ** queries.
102709 if( pSub->pPrior ){
102710 if( pSub->pOrderBy ){
102711 return 0; /* Restriction 20 */
102713 if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
102714 return 0;
102716 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
102717 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
102718 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
102719 assert( pSub->pSrc!=0 );
102720 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
102721 || (pSub1->pPrior && pSub1->op!=TK_ALL)
102722 || pSub1->pSrc->nSrc<1
102723 || pSub->pEList->nExpr!=pSub1->pEList->nExpr
102725 return 0;
102727 testcase( pSub1->pSrc->nSrc>1 );
102730 /* Restriction 18. */
102731 if( p->pOrderBy ){
102732 int ii;
102733 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
102734 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
102739 /***** If we reach this point, flattening is permitted. *****/
102741 /* Authorize the subquery */
102742 pParse->zAuthContext = pSubitem->zName;
102743 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
102744 testcase( i==SQLITE_DENY );
102745 pParse->zAuthContext = zSavedAuthContext;
102747 /* If the sub-query is a compound SELECT statement, then (by restrictions
102748 ** 17 and 18 above) it must be a UNION ALL and the parent query must
102749 ** be of the form:
102751 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
102753 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
102754 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
102755 ** OFFSET clauses and joins them to the left-hand-side of the original
102756 ** using UNION ALL operators. In this case N is the number of simple
102757 ** select statements in the compound sub-query.
102759 ** Example:
102761 ** SELECT a+1 FROM (
102762 ** SELECT x FROM tab
102763 ** UNION ALL
102764 ** SELECT y FROM tab
102765 ** UNION ALL
102766 ** SELECT abs(z*2) FROM tab2
102767 ** ) WHERE a!=5 ORDER BY 1
102769 ** Transformed into:
102771 ** SELECT x+1 FROM tab WHERE x+1!=5
102772 ** UNION ALL
102773 ** SELECT y+1 FROM tab WHERE y+1!=5
102774 ** UNION ALL
102775 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
102776 ** ORDER BY 1
102778 ** We call this the "compound-subquery flattening".
102780 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
102781 Select *pNew;
102782 ExprList *pOrderBy = p->pOrderBy;
102783 Expr *pLimit = p->pLimit;
102784 Expr *pOffset = p->pOffset;
102785 Select *pPrior = p->pPrior;
102786 p->pOrderBy = 0;
102787 p->pSrc = 0;
102788 p->pPrior = 0;
102789 p->pLimit = 0;
102790 p->pOffset = 0;
102791 pNew = sqlite3SelectDup(db, p, 0);
102792 p->pOffset = pOffset;
102793 p->pLimit = pLimit;
102794 p->pOrderBy = pOrderBy;
102795 p->pSrc = pSrc;
102796 p->op = TK_ALL;
102797 p->pRightmost = 0;
102798 if( pNew==0 ){
102799 pNew = pPrior;
102800 }else{
102801 pNew->pPrior = pPrior;
102802 pNew->pRightmost = 0;
102804 p->pPrior = pNew;
102805 if( db->mallocFailed ) return 1;
102808 /* Begin flattening the iFrom-th entry of the FROM clause
102809 ** in the outer query.
102811 pSub = pSub1 = pSubitem->pSelect;
102813 /* Delete the transient table structure associated with the
102814 ** subquery
102816 sqlite3DbFree(db, pSubitem->zDatabase);
102817 sqlite3DbFree(db, pSubitem->zName);
102818 sqlite3DbFree(db, pSubitem->zAlias);
102819 pSubitem->zDatabase = 0;
102820 pSubitem->zName = 0;
102821 pSubitem->zAlias = 0;
102822 pSubitem->pSelect = 0;
102824 /* Defer deleting the Table object associated with the
102825 ** subquery until code generation is
102826 ** complete, since there may still exist Expr.pTab entries that
102827 ** refer to the subquery even after flattening. Ticket #3346.
102829 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
102831 if( ALWAYS(pSubitem->pTab!=0) ){
102832 Table *pTabToDel = pSubitem->pTab;
102833 if( pTabToDel->nRef==1 ){
102834 Parse *pToplevel = sqlite3ParseToplevel(pParse);
102835 pTabToDel->pNextZombie = pToplevel->pZombieTab;
102836 pToplevel->pZombieTab = pTabToDel;
102837 }else{
102838 pTabToDel->nRef--;
102840 pSubitem->pTab = 0;
102843 /* The following loop runs once for each term in a compound-subquery
102844 ** flattening (as described above). If we are doing a different kind
102845 ** of flattening - a flattening other than a compound-subquery flattening -
102846 ** then this loop only runs once.
102848 ** This loop moves all of the FROM elements of the subquery into the
102849 ** the FROM clause of the outer query. Before doing this, remember
102850 ** the cursor number for the original outer query FROM element in
102851 ** iParent. The iParent cursor will never be used. Subsequent code
102852 ** will scan expressions looking for iParent references and replace
102853 ** those references with expressions that resolve to the subquery FROM
102854 ** elements we are now copying in.
102856 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
102857 int nSubSrc;
102858 u8 jointype = 0;
102859 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
102860 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
102861 pSrc = pParent->pSrc; /* FROM clause of the outer query */
102863 if( pSrc ){
102864 assert( pParent==p ); /* First time through the loop */
102865 jointype = pSubitem->jointype;
102866 }else{
102867 assert( pParent!=p ); /* 2nd and subsequent times through the loop */
102868 pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
102869 if( pSrc==0 ){
102870 assert( db->mallocFailed );
102871 break;
102875 /* The subquery uses a single slot of the FROM clause of the outer
102876 ** query. If the subquery has more than one element in its FROM clause,
102877 ** then expand the outer query to make space for it to hold all elements
102878 ** of the subquery.
102880 ** Example:
102882 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
102884 ** The outer query has 3 slots in its FROM clause. One slot of the
102885 ** outer query (the middle slot) is used by the subquery. The next
102886 ** block of code will expand the out query to 4 slots. The middle
102887 ** slot is expanded to two slots in order to make space for the
102888 ** two elements in the FROM clause of the subquery.
102890 if( nSubSrc>1 ){
102891 pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
102892 if( db->mallocFailed ){
102893 break;
102897 /* Transfer the FROM clause terms from the subquery into the
102898 ** outer query.
102900 for(i=0; i<nSubSrc; i++){
102901 sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
102902 pSrc->a[i+iFrom] = pSubSrc->a[i];
102903 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
102905 pSrc->a[iFrom].jointype = jointype;
102907 /* Now begin substituting subquery result set expressions for
102908 ** references to the iParent in the outer query.
102910 ** Example:
102912 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
102913 ** \ \_____________ subquery __________/ /
102914 ** \_____________________ outer query ______________________________/
102916 ** We look at every expression in the outer query and every place we see
102917 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
102919 pList = pParent->pEList;
102920 for(i=0; i<pList->nExpr; i++){
102921 if( pList->a[i].zName==0 ){
102922 char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
102923 sqlite3Dequote(zName);
102924 pList->a[i].zName = zName;
102927 substExprList(db, pParent->pEList, iParent, pSub->pEList);
102928 if( isAgg ){
102929 substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
102930 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
102932 if( pSub->pOrderBy ){
102933 assert( pParent->pOrderBy==0 );
102934 pParent->pOrderBy = pSub->pOrderBy;
102935 pSub->pOrderBy = 0;
102936 }else if( pParent->pOrderBy ){
102937 substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
102939 if( pSub->pWhere ){
102940 pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
102941 }else{
102942 pWhere = 0;
102944 if( subqueryIsAgg ){
102945 assert( pParent->pHaving==0 );
102946 pParent->pHaving = pParent->pWhere;
102947 pParent->pWhere = pWhere;
102948 pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
102949 pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
102950 sqlite3ExprDup(db, pSub->pHaving, 0));
102951 assert( pParent->pGroupBy==0 );
102952 pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
102953 }else{
102954 pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
102955 pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
102958 /* The flattened query is distinct if either the inner or the
102959 ** outer query is distinct.
102961 pParent->selFlags |= pSub->selFlags & SF_Distinct;
102964 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
102966 ** One is tempted to try to add a and b to combine the limits. But this
102967 ** does not work if either limit is negative.
102969 if( pSub->pLimit ){
102970 pParent->pLimit = pSub->pLimit;
102971 pSub->pLimit = 0;
102975 /* Finially, delete what is left of the subquery and return
102976 ** success.
102978 sqlite3SelectDelete(db, pSub1);
102980 return 1;
102982 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
102985 ** Based on the contents of the AggInfo structure indicated by the first
102986 ** argument, this function checks if the following are true:
102988 ** * the query contains just a single aggregate function,
102989 ** * the aggregate function is either min() or max(), and
102990 ** * the argument to the aggregate function is a column value.
102992 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
102993 ** is returned as appropriate. Also, *ppMinMax is set to point to the
102994 ** list of arguments passed to the aggregate before returning.
102996 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
102997 ** WHERE_ORDERBY_NORMAL is returned.
102999 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
103000 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
103002 *ppMinMax = 0;
103003 if( pAggInfo->nFunc==1 ){
103004 Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
103005 ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
103007 assert( pExpr->op==TK_AGG_FUNCTION );
103008 if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
103009 const char *zFunc = pExpr->u.zToken;
103010 if( sqlite3StrICmp(zFunc, "min")==0 ){
103011 eRet = WHERE_ORDERBY_MIN;
103012 *ppMinMax = pEList;
103013 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
103014 eRet = WHERE_ORDERBY_MAX;
103015 *ppMinMax = pEList;
103020 assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
103021 return eRet;
103025 ** The select statement passed as the first argument is an aggregate query.
103026 ** The second argment is the associated aggregate-info object. This
103027 ** function tests if the SELECT is of the form:
103029 ** SELECT count(*) FROM <tbl>
103031 ** where table is a database table, not a sub-select or view. If the query
103032 ** does match this pattern, then a pointer to the Table object representing
103033 ** <tbl> is returned. Otherwise, 0 is returned.
103035 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
103036 Table *pTab;
103037 Expr *pExpr;
103039 assert( !p->pGroupBy );
103041 if( p->pWhere || p->pEList->nExpr!=1
103042 || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
103044 return 0;
103046 pTab = p->pSrc->a[0].pTab;
103047 pExpr = p->pEList->a[0].pExpr;
103048 assert( pTab && !pTab->pSelect && pExpr );
103050 if( IsVirtual(pTab) ) return 0;
103051 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
103052 if( NEVER(pAggInfo->nFunc==0) ) return 0;
103053 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
103054 if( pExpr->flags&EP_Distinct ) return 0;
103056 return pTab;
103060 ** If the source-list item passed as an argument was augmented with an
103061 ** INDEXED BY clause, then try to locate the specified index. If there
103062 ** was such a clause and the named index cannot be found, return
103063 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
103064 ** pFrom->pIndex and return SQLITE_OK.
103066 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
103067 if( pFrom->pTab && pFrom->zIndex ){
103068 Table *pTab = pFrom->pTab;
103069 char *zIndex = pFrom->zIndex;
103070 Index *pIdx;
103071 for(pIdx=pTab->pIndex;
103072 pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
103073 pIdx=pIdx->pNext
103075 if( !pIdx ){
103076 sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
103077 pParse->checkSchema = 1;
103078 return SQLITE_ERROR;
103080 pFrom->pIndex = pIdx;
103082 return SQLITE_OK;
103085 ** Detect compound SELECT statements that use an ORDER BY clause with
103086 ** an alternative collating sequence.
103088 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
103090 ** These are rewritten as a subquery:
103092 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
103093 ** ORDER BY ... COLLATE ...
103095 ** This transformation is necessary because the multiSelectOrderBy() routine
103096 ** above that generates the code for a compound SELECT with an ORDER BY clause
103097 ** uses a merge algorithm that requires the same collating sequence on the
103098 ** result columns as on the ORDER BY clause. See ticket
103099 ** http://www.sqlite.org/src/info/6709574d2a
103101 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
103102 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
103103 ** there are COLLATE terms in the ORDER BY.
103105 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
103106 int i;
103107 Select *pNew;
103108 Select *pX;
103109 sqlite3 *db;
103110 struct ExprList_item *a;
103111 SrcList *pNewSrc;
103112 Parse *pParse;
103113 Token dummy;
103115 if( p->pPrior==0 ) return WRC_Continue;
103116 if( p->pOrderBy==0 ) return WRC_Continue;
103117 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
103118 if( pX==0 ) return WRC_Continue;
103119 a = p->pOrderBy->a;
103120 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
103121 if( a[i].pExpr->flags & EP_Collate ) break;
103123 if( i<0 ) return WRC_Continue;
103125 /* If we reach this point, that means the transformation is required. */
103127 pParse = pWalker->pParse;
103128 db = pParse->db;
103129 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
103130 if( pNew==0 ) return WRC_Abort;
103131 memset(&dummy, 0, sizeof(dummy));
103132 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
103133 if( pNewSrc==0 ) return WRC_Abort;
103134 *pNew = *p;
103135 p->pSrc = pNewSrc;
103136 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
103137 p->op = TK_SELECT;
103138 p->pWhere = 0;
103139 pNew->pGroupBy = 0;
103140 pNew->pHaving = 0;
103141 pNew->pOrderBy = 0;
103142 p->pPrior = 0;
103143 pNew->pLimit = 0;
103144 pNew->pOffset = 0;
103145 return WRC_Continue;
103148 #ifndef SQLITE_OMIT_CTE
103150 ** Argument pWith (which may be NULL) points to a linked list of nested
103151 ** WITH contexts, from inner to outermost. If the table identified by
103152 ** FROM clause element pItem is really a common-table-expression (CTE)
103153 ** then return a pointer to the CTE definition for that table. Otherwise
103154 ** return NULL.
103156 ** If a non-NULL value is returned, set *ppContext to point to the With
103157 ** object that the returned CTE belongs to.
103159 static struct Cte *searchWith(
103160 With *pWith, /* Current outermost WITH clause */
103161 struct SrcList_item *pItem, /* FROM clause element to resolve */
103162 With **ppContext /* OUT: WITH clause return value belongs to */
103164 const char *zName;
103165 if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
103166 With *p;
103167 for(p=pWith; p; p=p->pOuter){
103168 int i;
103169 for(i=0; i<p->nCte; i++){
103170 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
103171 *ppContext = p;
103172 return &p->a[i];
103177 return 0;
103180 /* The code generator maintains a stack of active WITH clauses
103181 ** with the inner-most WITH clause being at the top of the stack.
103183 ** This routine pushes the WITH clause passed as the second argument
103184 ** onto the top of the stack. If argument bFree is true, then this
103185 ** WITH clause will never be popped from the stack. In this case it
103186 ** should be freed along with the Parse object. In other cases, when
103187 ** bFree==0, the With object will be freed along with the SELECT
103188 ** statement with which it is associated.
103190 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
103191 assert( bFree==0 || pParse->pWith==0 );
103192 if( pWith ){
103193 pWith->pOuter = pParse->pWith;
103194 pParse->pWith = pWith;
103195 pParse->bFreeWith = bFree;
103200 ** This function checks if argument pFrom refers to a CTE declared by
103201 ** a WITH clause on the stack currently maintained by the parser. And,
103202 ** if currently processing a CTE expression, if it is a recursive
103203 ** reference to the current CTE.
103205 ** If pFrom falls into either of the two categories above, pFrom->pTab
103206 ** and other fields are populated accordingly. The caller should check
103207 ** (pFrom->pTab!=0) to determine whether or not a successful match
103208 ** was found.
103210 ** Whether or not a match is found, SQLITE_OK is returned if no error
103211 ** occurs. If an error does occur, an error message is stored in the
103212 ** parser and some error code other than SQLITE_OK returned.
103214 static int withExpand(
103215 Walker *pWalker,
103216 struct SrcList_item *pFrom
103218 Parse *pParse = pWalker->pParse;
103219 sqlite3 *db = pParse->db;
103220 struct Cte *pCte; /* Matched CTE (or NULL if no match) */
103221 With *pWith; /* WITH clause that pCte belongs to */
103223 assert( pFrom->pTab==0 );
103225 pCte = searchWith(pParse->pWith, pFrom, &pWith);
103226 if( pCte ){
103227 Table *pTab;
103228 ExprList *pEList;
103229 Select *pSel;
103230 Select *pLeft; /* Left-most SELECT statement */
103231 int bMayRecursive; /* True if compound joined by UNION [ALL] */
103232 With *pSavedWith; /* Initial value of pParse->pWith */
103234 /* If pCte->zErr is non-NULL at this point, then this is an illegal
103235 ** recursive reference to CTE pCte. Leave an error in pParse and return
103236 ** early. If pCte->zErr is NULL, then this is not a recursive reference.
103237 ** In this case, proceed. */
103238 if( pCte->zErr ){
103239 sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
103240 return SQLITE_ERROR;
103243 assert( pFrom->pTab==0 );
103244 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
103245 if( pTab==0 ) return WRC_Abort;
103246 pTab->nRef = 1;
103247 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
103248 pTab->iPKey = -1;
103249 pTab->nRowEst = 1048576;
103250 pTab->tabFlags |= TF_Ephemeral;
103251 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
103252 if( db->mallocFailed ) return SQLITE_NOMEM;
103253 assert( pFrom->pSelect );
103255 /* Check if this is a recursive CTE. */
103256 pSel = pFrom->pSelect;
103257 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
103258 if( bMayRecursive ){
103259 int i;
103260 SrcList *pSrc = pFrom->pSelect->pSrc;
103261 for(i=0; i<pSrc->nSrc; i++){
103262 struct SrcList_item *pItem = &pSrc->a[i];
103263 if( pItem->zDatabase==0
103264 && pItem->zName!=0
103265 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
103267 pItem->pTab = pTab;
103268 pItem->isRecursive = 1;
103269 pTab->nRef++;
103270 pSel->selFlags |= SF_Recursive;
103275 /* Only one recursive reference is permitted. */
103276 if( pTab->nRef>2 ){
103277 sqlite3ErrorMsg(
103278 pParse, "multiple references to recursive table: %s", pCte->zName
103280 return SQLITE_ERROR;
103282 assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
103284 pCte->zErr = "circular reference: %s";
103285 pSavedWith = pParse->pWith;
103286 pParse->pWith = pWith;
103287 sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
103289 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
103290 pEList = pLeft->pEList;
103291 if( pCte->pCols ){
103292 if( pEList->nExpr!=pCte->pCols->nExpr ){
103293 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
103294 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
103296 pParse->pWith = pSavedWith;
103297 return SQLITE_ERROR;
103299 pEList = pCte->pCols;
103302 selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
103303 if( bMayRecursive ){
103304 if( pSel->selFlags & SF_Recursive ){
103305 pCte->zErr = "multiple recursive references: %s";
103306 }else{
103307 pCte->zErr = "recursive reference in a subquery: %s";
103309 sqlite3WalkSelect(pWalker, pSel);
103311 pCte->zErr = 0;
103312 pParse->pWith = pSavedWith;
103315 return SQLITE_OK;
103317 #endif
103319 #ifndef SQLITE_OMIT_CTE
103321 ** If the SELECT passed as the second argument has an associated WITH
103322 ** clause, pop it from the stack stored as part of the Parse object.
103324 ** This function is used as the xSelectCallback2() callback by
103325 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
103326 ** names and other FROM clause elements.
103328 static void selectPopWith(Walker *pWalker, Select *p){
103329 Parse *pParse = pWalker->pParse;
103330 if( p->pWith ){
103331 assert( pParse->pWith==p->pWith );
103332 pParse->pWith = p->pWith->pOuter;
103335 #else
103336 #define selectPopWith 0
103337 #endif
103340 ** This routine is a Walker callback for "expanding" a SELECT statement.
103341 ** "Expanding" means to do the following:
103343 ** (1) Make sure VDBE cursor numbers have been assigned to every
103344 ** element of the FROM clause.
103346 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
103347 ** defines FROM clause. When views appear in the FROM clause,
103348 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
103349 ** that implements the view. A copy is made of the view's SELECT
103350 ** statement so that we can freely modify or delete that statement
103351 ** without worrying about messing up the presistent representation
103352 ** of the view.
103354 ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
103355 ** on joins and the ON and USING clause of joins.
103357 ** (4) Scan the list of columns in the result set (pEList) looking
103358 ** for instances of the "*" operator or the TABLE.* operator.
103359 ** If found, expand each "*" to be every column in every table
103360 ** and TABLE.* to be every column in TABLE.
103363 static int selectExpander(Walker *pWalker, Select *p){
103364 Parse *pParse = pWalker->pParse;
103365 int i, j, k;
103366 SrcList *pTabList;
103367 ExprList *pEList;
103368 struct SrcList_item *pFrom;
103369 sqlite3 *db = pParse->db;
103370 Expr *pE, *pRight, *pExpr;
103371 u16 selFlags = p->selFlags;
103373 p->selFlags |= SF_Expanded;
103374 if( db->mallocFailed ){
103375 return WRC_Abort;
103377 if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
103378 return WRC_Prune;
103380 pTabList = p->pSrc;
103381 pEList = p->pEList;
103382 sqlite3WithPush(pParse, p->pWith, 0);
103384 /* Make sure cursor numbers have been assigned to all entries in
103385 ** the FROM clause of the SELECT statement.
103387 sqlite3SrcListAssignCursors(pParse, pTabList);
103389 /* Look up every table named in the FROM clause of the select. If
103390 ** an entry of the FROM clause is a subquery instead of a table or view,
103391 ** then create a transient table structure to describe the subquery.
103393 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
103394 Table *pTab;
103395 assert( pFrom->isRecursive==0 || pFrom->pTab );
103396 if( pFrom->isRecursive ) continue;
103397 if( pFrom->pTab!=0 ){
103398 /* This statement has already been prepared. There is no need
103399 ** to go further. */
103400 assert( i==0 );
103401 #ifndef SQLITE_OMIT_CTE
103402 selectPopWith(pWalker, p);
103403 #endif
103404 return WRC_Prune;
103406 #ifndef SQLITE_OMIT_CTE
103407 if( withExpand(pWalker, pFrom) ) return WRC_Abort;
103408 if( pFrom->pTab ) {} else
103409 #endif
103410 if( pFrom->zName==0 ){
103411 #ifndef SQLITE_OMIT_SUBQUERY
103412 Select *pSel = pFrom->pSelect;
103413 /* A sub-query in the FROM clause of a SELECT */
103414 assert( pSel!=0 );
103415 assert( pFrom->pTab==0 );
103416 sqlite3WalkSelect(pWalker, pSel);
103417 pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
103418 if( pTab==0 ) return WRC_Abort;
103419 pTab->nRef = 1;
103420 pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
103421 while( pSel->pPrior ){ pSel = pSel->pPrior; }
103422 selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
103423 pTab->iPKey = -1;
103424 pTab->nRowEst = 1048576;
103425 pTab->tabFlags |= TF_Ephemeral;
103426 #endif
103427 }else{
103428 /* An ordinary table or view name in the FROM clause */
103429 assert( pFrom->pTab==0 );
103430 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
103431 if( pTab==0 ) return WRC_Abort;
103432 if( pTab->nRef==0xffff ){
103433 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
103434 pTab->zName);
103435 pFrom->pTab = 0;
103436 return WRC_Abort;
103438 pTab->nRef++;
103439 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
103440 if( pTab->pSelect || IsVirtual(pTab) ){
103441 /* We reach here if the named table is a really a view */
103442 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
103443 assert( pFrom->pSelect==0 );
103444 pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
103445 sqlite3WalkSelect(pWalker, pFrom->pSelect);
103447 #endif
103450 /* Locate the index named by the INDEXED BY clause, if any. */
103451 if( sqlite3IndexedByLookup(pParse, pFrom) ){
103452 return WRC_Abort;
103456 /* Process NATURAL keywords, and ON and USING clauses of joins.
103458 if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
103459 return WRC_Abort;
103462 /* For every "*" that occurs in the column list, insert the names of
103463 ** all columns in all tables. And for every TABLE.* insert the names
103464 ** of all columns in TABLE. The parser inserted a special expression
103465 ** with the TK_ALL operator for each "*" that it found in the column list.
103466 ** The following code just has to locate the TK_ALL expressions and expand
103467 ** each one to the list of all columns in all tables.
103469 ** The first loop just checks to see if there are any "*" operators
103470 ** that need expanding.
103472 for(k=0; k<pEList->nExpr; k++){
103473 pE = pEList->a[k].pExpr;
103474 if( pE->op==TK_ALL ) break;
103475 assert( pE->op!=TK_DOT || pE->pRight!=0 );
103476 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
103477 if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
103479 if( k<pEList->nExpr ){
103481 ** If we get here it means the result set contains one or more "*"
103482 ** operators that need to be expanded. Loop through each expression
103483 ** in the result set and expand them one by one.
103485 struct ExprList_item *a = pEList->a;
103486 ExprList *pNew = 0;
103487 int flags = pParse->db->flags;
103488 int longNames = (flags & SQLITE_FullColNames)!=0
103489 && (flags & SQLITE_ShortColNames)==0;
103491 /* When processing FROM-clause subqueries, it is always the case
103492 ** that full_column_names=OFF and short_column_names=ON. The
103493 ** sqlite3ResultSetOfSelect() routine makes it so. */
103494 assert( (p->selFlags & SF_NestedFrom)==0
103495 || ((flags & SQLITE_FullColNames)==0 &&
103496 (flags & SQLITE_ShortColNames)!=0) );
103498 for(k=0; k<pEList->nExpr; k++){
103499 pE = a[k].pExpr;
103500 pRight = pE->pRight;
103501 assert( pE->op!=TK_DOT || pRight!=0 );
103502 if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
103503 /* This particular expression does not need to be expanded.
103505 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
103506 if( pNew ){
103507 pNew->a[pNew->nExpr-1].zName = a[k].zName;
103508 pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
103509 a[k].zName = 0;
103510 a[k].zSpan = 0;
103512 a[k].pExpr = 0;
103513 }else{
103514 /* This expression is a "*" or a "TABLE.*" and needs to be
103515 ** expanded. */
103516 int tableSeen = 0; /* Set to 1 when TABLE matches */
103517 char *zTName = 0; /* text of name of TABLE */
103518 if( pE->op==TK_DOT ){
103519 assert( pE->pLeft!=0 );
103520 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
103521 zTName = pE->pLeft->u.zToken;
103523 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
103524 Table *pTab = pFrom->pTab;
103525 Select *pSub = pFrom->pSelect;
103526 char *zTabName = pFrom->zAlias;
103527 const char *zSchemaName = 0;
103528 int iDb;
103529 if( zTabName==0 ){
103530 zTabName = pTab->zName;
103532 if( db->mallocFailed ) break;
103533 if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
103534 pSub = 0;
103535 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
103536 continue;
103538 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103539 zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
103541 for(j=0; j<pTab->nCol; j++){
103542 char *zName = pTab->aCol[j].zName;
103543 char *zColname; /* The computed column name */
103544 char *zToFree; /* Malloced string that needs to be freed */
103545 Token sColname; /* Computed column name as a token */
103547 assert( zName );
103548 if( zTName && pSub
103549 && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
103551 continue;
103554 /* If a column is marked as 'hidden' (currently only possible
103555 ** for virtual tables), do not include it in the expanded
103556 ** result-set list.
103558 if( IsHiddenColumn(&pTab->aCol[j]) ){
103559 assert(IsVirtual(pTab));
103560 continue;
103562 tableSeen = 1;
103564 if( i>0 && zTName==0 ){
103565 if( (pFrom->jointype & JT_NATURAL)!=0
103566 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
103568 /* In a NATURAL join, omit the join columns from the
103569 ** table to the right of the join */
103570 continue;
103572 if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
103573 /* In a join with a USING clause, omit columns in the
103574 ** using clause from the table on the right. */
103575 continue;
103578 pRight = sqlite3Expr(db, TK_ID, zName);
103579 zColname = zName;
103580 zToFree = 0;
103581 if( longNames || pTabList->nSrc>1 ){
103582 Expr *pLeft;
103583 pLeft = sqlite3Expr(db, TK_ID, zTabName);
103584 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
103585 if( zSchemaName ){
103586 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
103587 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
103589 if( longNames ){
103590 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
103591 zToFree = zColname;
103593 }else{
103594 pExpr = pRight;
103596 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
103597 sColname.z = zColname;
103598 sColname.n = sqlite3Strlen30(zColname);
103599 sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
103600 if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
103601 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
103602 if( pSub ){
103603 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
103604 testcase( pX->zSpan==0 );
103605 }else{
103606 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
103607 zSchemaName, zTabName, zColname);
103608 testcase( pX->zSpan==0 );
103610 pX->bSpanIsTab = 1;
103612 sqlite3DbFree(db, zToFree);
103615 if( !tableSeen ){
103616 if( zTName ){
103617 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
103618 }else{
103619 sqlite3ErrorMsg(pParse, "no tables specified");
103624 sqlite3ExprListDelete(db, pEList);
103625 p->pEList = pNew;
103627 #if SQLITE_MAX_COLUMN
103628 if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
103629 sqlite3ErrorMsg(pParse, "too many columns in result set");
103631 #endif
103632 return WRC_Continue;
103636 ** No-op routine for the parse-tree walker.
103638 ** When this routine is the Walker.xExprCallback then expression trees
103639 ** are walked without any actions being taken at each node. Presumably,
103640 ** when this routine is used for Walker.xExprCallback then
103641 ** Walker.xSelectCallback is set to do something useful for every
103642 ** subquery in the parser tree.
103644 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
103645 UNUSED_PARAMETER2(NotUsed, NotUsed2);
103646 return WRC_Continue;
103650 ** This routine "expands" a SELECT statement and all of its subqueries.
103651 ** For additional information on what it means to "expand" a SELECT
103652 ** statement, see the comment on the selectExpand worker callback above.
103654 ** Expanding a SELECT statement is the first step in processing a
103655 ** SELECT statement. The SELECT statement must be expanded before
103656 ** name resolution is performed.
103658 ** If anything goes wrong, an error message is written into pParse.
103659 ** The calling function can detect the problem by looking at pParse->nErr
103660 ** and/or pParse->db->mallocFailed.
103662 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
103663 Walker w;
103664 memset(&w, 0, sizeof(w));
103665 w.xExprCallback = exprWalkNoop;
103666 w.pParse = pParse;
103667 if( pParse->hasCompound ){
103668 w.xSelectCallback = convertCompoundSelectToSubquery;
103669 sqlite3WalkSelect(&w, pSelect);
103671 w.xSelectCallback = selectExpander;
103672 w.xSelectCallback2 = selectPopWith;
103673 sqlite3WalkSelect(&w, pSelect);
103677 #ifndef SQLITE_OMIT_SUBQUERY
103679 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
103680 ** interface.
103682 ** For each FROM-clause subquery, add Column.zType and Column.zColl
103683 ** information to the Table structure that represents the result set
103684 ** of that subquery.
103686 ** The Table structure that represents the result set was constructed
103687 ** by selectExpander() but the type and collation information was omitted
103688 ** at that point because identifiers had not yet been resolved. This
103689 ** routine is called after identifier resolution.
103691 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
103692 Parse *pParse;
103693 int i;
103694 SrcList *pTabList;
103695 struct SrcList_item *pFrom;
103697 assert( p->selFlags & SF_Resolved );
103698 if( (p->selFlags & SF_HasTypeInfo)==0 ){
103699 p->selFlags |= SF_HasTypeInfo;
103700 pParse = pWalker->pParse;
103701 pTabList = p->pSrc;
103702 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
103703 Table *pTab = pFrom->pTab;
103704 if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
103705 /* A sub-query in the FROM clause of a SELECT */
103706 Select *pSel = pFrom->pSelect;
103707 if( pSel ){
103708 while( pSel->pPrior ) pSel = pSel->pPrior;
103709 selectAddColumnTypeAndCollation(pParse, pTab, pSel);
103715 #endif
103719 ** This routine adds datatype and collating sequence information to
103720 ** the Table structures of all FROM-clause subqueries in a
103721 ** SELECT statement.
103723 ** Use this routine after name resolution.
103725 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
103726 #ifndef SQLITE_OMIT_SUBQUERY
103727 Walker w;
103728 memset(&w, 0, sizeof(w));
103729 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
103730 w.xExprCallback = exprWalkNoop;
103731 w.pParse = pParse;
103732 sqlite3WalkSelect(&w, pSelect);
103733 #endif
103738 ** This routine sets up a SELECT statement for processing. The
103739 ** following is accomplished:
103741 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
103742 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
103743 ** * ON and USING clauses are shifted into WHERE statements
103744 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
103745 ** * Identifiers in expression are matched to tables.
103747 ** This routine acts recursively on all subqueries within the SELECT.
103749 SQLITE_PRIVATE void sqlite3SelectPrep(
103750 Parse *pParse, /* The parser context */
103751 Select *p, /* The SELECT statement being coded. */
103752 NameContext *pOuterNC /* Name context for container */
103754 sqlite3 *db;
103755 if( NEVER(p==0) ) return;
103756 db = pParse->db;
103757 if( db->mallocFailed ) return;
103758 if( p->selFlags & SF_HasTypeInfo ) return;
103759 sqlite3SelectExpand(pParse, p);
103760 if( pParse->nErr || db->mallocFailed ) return;
103761 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
103762 if( pParse->nErr || db->mallocFailed ) return;
103763 sqlite3SelectAddTypeInfo(pParse, p);
103767 ** Reset the aggregate accumulator.
103769 ** The aggregate accumulator is a set of memory cells that hold
103770 ** intermediate results while calculating an aggregate. This
103771 ** routine generates code that stores NULLs in all of those memory
103772 ** cells.
103774 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
103775 Vdbe *v = pParse->pVdbe;
103776 int i;
103777 struct AggInfo_func *pFunc;
103778 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
103779 if( nReg==0 ) return;
103780 #ifdef SQLITE_DEBUG
103781 /* Verify that all AggInfo registers are within the range specified by
103782 ** AggInfo.mnReg..AggInfo.mxReg */
103783 assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
103784 for(i=0; i<pAggInfo->nColumn; i++){
103785 assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
103786 && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
103788 for(i=0; i<pAggInfo->nFunc; i++){
103789 assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
103790 && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
103792 #endif
103793 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
103794 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
103795 if( pFunc->iDistinct>=0 ){
103796 Expr *pE = pFunc->pExpr;
103797 assert( !ExprHasProperty(pE, EP_xIsSelect) );
103798 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
103799 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
103800 "argument");
103801 pFunc->iDistinct = -1;
103802 }else{
103803 KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0);
103804 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
103805 (char*)pKeyInfo, P4_KEYINFO);
103812 ** Invoke the OP_AggFinalize opcode for every aggregate function
103813 ** in the AggInfo structure.
103815 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
103816 Vdbe *v = pParse->pVdbe;
103817 int i;
103818 struct AggInfo_func *pF;
103819 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
103820 ExprList *pList = pF->pExpr->x.pList;
103821 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
103822 sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
103823 (void*)pF->pFunc, P4_FUNCDEF);
103828 ** Update the accumulator memory cells for an aggregate based on
103829 ** the current cursor position.
103831 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
103832 Vdbe *v = pParse->pVdbe;
103833 int i;
103834 int regHit = 0;
103835 int addrHitTest = 0;
103836 struct AggInfo_func *pF;
103837 struct AggInfo_col *pC;
103839 pAggInfo->directMode = 1;
103840 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
103841 int nArg;
103842 int addrNext = 0;
103843 int regAgg;
103844 ExprList *pList = pF->pExpr->x.pList;
103845 assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
103846 if( pList ){
103847 nArg = pList->nExpr;
103848 regAgg = sqlite3GetTempRange(pParse, nArg);
103849 sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
103850 }else{
103851 nArg = 0;
103852 regAgg = 0;
103854 if( pF->iDistinct>=0 ){
103855 addrNext = sqlite3VdbeMakeLabel(v);
103856 assert( nArg==1 );
103857 codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
103859 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
103860 CollSeq *pColl = 0;
103861 struct ExprList_item *pItem;
103862 int j;
103863 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
103864 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
103865 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
103867 if( !pColl ){
103868 pColl = pParse->db->pDfltColl;
103870 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
103871 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
103873 sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
103874 (void*)pF->pFunc, P4_FUNCDEF);
103875 sqlite3VdbeChangeP5(v, (u8)nArg);
103876 sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
103877 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
103878 if( addrNext ){
103879 sqlite3VdbeResolveLabel(v, addrNext);
103880 sqlite3ExprCacheClear(pParse);
103884 /* Before populating the accumulator registers, clear the column cache.
103885 ** Otherwise, if any of the required column values are already present
103886 ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
103887 ** to pC->iMem. But by the time the value is used, the original register
103888 ** may have been used, invalidating the underlying buffer holding the
103889 ** text or blob value. See ticket [883034dcb5].
103891 ** Another solution would be to change the OP_SCopy used to copy cached
103892 ** values to an OP_Copy.
103894 if( regHit ){
103895 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
103897 sqlite3ExprCacheClear(pParse);
103898 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
103899 sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
103901 pAggInfo->directMode = 0;
103902 sqlite3ExprCacheClear(pParse);
103903 if( addrHitTest ){
103904 sqlite3VdbeJumpHere(v, addrHitTest);
103909 ** Add a single OP_Explain instruction to the VDBE to explain a simple
103910 ** count(*) query ("SELECT count(*) FROM pTab").
103912 #ifndef SQLITE_OMIT_EXPLAIN
103913 static void explainSimpleCount(
103914 Parse *pParse, /* Parse context */
103915 Table *pTab, /* Table being queried */
103916 Index *pIdx /* Index used to optimize scan, or NULL */
103918 if( pParse->explain==2 ){
103919 char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
103920 pTab->zName,
103921 pIdx ? " USING COVERING INDEX " : "",
103922 pIdx ? pIdx->zName : ""
103924 sqlite3VdbeAddOp4(
103925 pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
103929 #else
103930 # define explainSimpleCount(a,b,c)
103931 #endif
103934 ** Generate code for the SELECT statement given in the p argument.
103936 ** The results are returned according to the SelectDest structure.
103937 ** See comments in sqliteInt.h for further information.
103939 ** This routine returns the number of errors. If any errors are
103940 ** encountered, then an appropriate error message is left in
103941 ** pParse->zErrMsg.
103943 ** This routine does NOT free the Select structure passed in. The
103944 ** calling function needs to do that.
103946 SQLITE_PRIVATE int sqlite3Select(
103947 Parse *pParse, /* The parser context */
103948 Select *p, /* The SELECT statement being coded. */
103949 SelectDest *pDest /* What to do with the query results */
103951 int i, j; /* Loop counters */
103952 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
103953 Vdbe *v; /* The virtual machine under construction */
103954 int isAgg; /* True for select lists like "count(*)" */
103955 ExprList *pEList; /* List of columns to extract. */
103956 SrcList *pTabList; /* List of tables to select from */
103957 Expr *pWhere; /* The WHERE clause. May be NULL */
103958 ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
103959 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
103960 Expr *pHaving; /* The HAVING clause. May be NULL */
103961 int rc = 1; /* Value to return from this function */
103962 int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
103963 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
103964 AggInfo sAggInfo; /* Information used by aggregate queries */
103965 int iEnd; /* Address of the end of the query */
103966 sqlite3 *db; /* The database connection */
103968 #ifndef SQLITE_OMIT_EXPLAIN
103969 int iRestoreSelectId = pParse->iSelectId;
103970 pParse->iSelectId = pParse->iNextSelectId++;
103971 #endif
103973 db = pParse->db;
103974 if( p==0 || db->mallocFailed || pParse->nErr ){
103975 return 1;
103977 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
103978 memset(&sAggInfo, 0, sizeof(sAggInfo));
103980 if( IgnorableOrderby(pDest) ){
103981 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
103982 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
103983 /* If ORDER BY makes no difference in the output then neither does
103984 ** DISTINCT so it can be removed too. */
103985 sqlite3ExprListDelete(db, p->pOrderBy);
103986 p->pOrderBy = 0;
103987 p->selFlags &= ~SF_Distinct;
103989 sqlite3SelectPrep(pParse, p, 0);
103990 pOrderBy = p->pOrderBy;
103991 pTabList = p->pSrc;
103992 pEList = p->pEList;
103993 if( pParse->nErr || db->mallocFailed ){
103994 goto select_end;
103996 isAgg = (p->selFlags & SF_Aggregate)!=0;
103997 assert( pEList!=0 );
103999 /* Begin generating code.
104001 v = sqlite3GetVdbe(pParse);
104002 if( v==0 ) goto select_end;
104004 /* If writing to memory or generating a set
104005 ** only a single column may be output.
104007 #ifndef SQLITE_OMIT_SUBQUERY
104008 if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
104009 goto select_end;
104011 #endif
104013 /* Generate code for all sub-queries in the FROM clause
104015 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
104016 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
104017 struct SrcList_item *pItem = &pTabList->a[i];
104018 SelectDest dest;
104019 Select *pSub = pItem->pSelect;
104020 int isAggSub;
104022 if( pSub==0 ) continue;
104024 /* Sometimes the code for a subquery will be generated more than
104025 ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
104026 ** for example. In that case, do not regenerate the code to manifest
104027 ** a view or the co-routine to implement a view. The first instance
104028 ** is sufficient, though the subroutine to manifest the view does need
104029 ** to be invoked again. */
104030 if( pItem->addrFillSub ){
104031 if( pItem->viaCoroutine==0 ){
104032 sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
104034 continue;
104037 /* Increment Parse.nHeight by the height of the largest expression
104038 ** tree referred to by this, the parent select. The child select
104039 ** may contain expression trees of at most
104040 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
104041 ** more conservative than necessary, but much easier than enforcing
104042 ** an exact limit.
104044 pParse->nHeight += sqlite3SelectExprHeight(p);
104046 isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
104047 if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
104048 /* This subquery can be absorbed into its parent. */
104049 if( isAggSub ){
104050 isAgg = 1;
104051 p->selFlags |= SF_Aggregate;
104053 i = -1;
104054 }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
104055 && OptimizationEnabled(db, SQLITE_SubqCoroutine)
104057 /* Implement a co-routine that will return a single row of the result
104058 ** set on each invocation.
104060 int addrTop;
104061 int addrEof;
104062 pItem->regReturn = ++pParse->nMem;
104063 addrEof = ++pParse->nMem;
104064 /* Before coding the OP_Goto to jump to the start of the main routine,
104065 ** ensure that the jump to the verify-schema routine has already
104066 ** been coded. Otherwise, the verify-schema would likely be coded as
104067 ** part of the co-routine. If the main routine then accessed the
104068 ** database before invoking the co-routine for the first time (for
104069 ** example to initialize a LIMIT register from a sub-select), it would
104070 ** be doing so without having verified the schema version and obtained
104071 ** the required db locks. See ticket d6b36be38. */
104072 sqlite3CodeVerifySchema(pParse, -1);
104073 sqlite3VdbeAddOp0(v, OP_Goto);
104074 addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
104075 sqlite3VdbeChangeP5(v, 1);
104076 VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
104077 pItem->addrFillSub = addrTop;
104078 sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
104079 sqlite3VdbeChangeP5(v, 1);
104080 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
104081 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
104082 sqlite3Select(pParse, pSub, &dest);
104083 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
104084 pItem->viaCoroutine = 1;
104085 sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
104086 sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
104087 sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
104088 sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
104089 VdbeComment((v, "end %s", pItem->pTab->zName));
104090 sqlite3VdbeJumpHere(v, addrTop-1);
104091 sqlite3ClearTempRegCache(pParse);
104092 }else{
104093 /* Generate a subroutine that will fill an ephemeral table with
104094 ** the content of this subquery. pItem->addrFillSub will point
104095 ** to the address of the generated subroutine. pItem->regReturn
104096 ** is a register allocated to hold the subroutine return address
104098 int topAddr;
104099 int onceAddr = 0;
104100 int retAddr;
104101 assert( pItem->addrFillSub==0 );
104102 pItem->regReturn = ++pParse->nMem;
104103 topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
104104 pItem->addrFillSub = topAddr+1;
104105 VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
104106 if( pItem->isCorrelated==0 ){
104107 /* If the subquery is not correlated and if we are not inside of
104108 ** a trigger, then we only need to compute the value of the subquery
104109 ** once. */
104110 onceAddr = sqlite3CodeOnce(pParse);
104112 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
104113 explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
104114 sqlite3Select(pParse, pSub, &dest);
104115 pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
104116 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
104117 retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
104118 VdbeComment((v, "end %s", pItem->pTab->zName));
104119 sqlite3VdbeChangeP1(v, topAddr, retAddr);
104120 sqlite3ClearTempRegCache(pParse);
104122 if( /*pParse->nErr ||*/ db->mallocFailed ){
104123 goto select_end;
104125 pParse->nHeight -= sqlite3SelectExprHeight(p);
104126 pTabList = p->pSrc;
104127 if( !IgnorableOrderby(pDest) ){
104128 pOrderBy = p->pOrderBy;
104131 pEList = p->pEList;
104132 #endif
104133 pWhere = p->pWhere;
104134 pGroupBy = p->pGroupBy;
104135 pHaving = p->pHaving;
104136 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
104138 #ifndef SQLITE_OMIT_COMPOUND_SELECT
104139 /* If there is are a sequence of queries, do the earlier ones first.
104141 if( p->pPrior ){
104142 if( p->pRightmost==0 ){
104143 Select *pLoop, *pRight = 0;
104144 int cnt = 0;
104145 int mxSelect;
104146 for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
104147 pLoop->pRightmost = p;
104148 pLoop->pNext = pRight;
104149 pRight = pLoop;
104151 mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
104152 if( mxSelect && cnt>mxSelect ){
104153 sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
104154 goto select_end;
104157 rc = multiSelect(pParse, p, pDest);
104158 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
104159 return rc;
104161 #endif
104163 /* If there is both a GROUP BY and an ORDER BY clause and they are
104164 ** identical, then disable the ORDER BY clause since the GROUP BY
104165 ** will cause elements to come out in the correct order. This is
104166 ** an optimization - the correct answer should result regardless.
104167 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
104168 ** to disable this optimization for testing purposes.
104170 if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
104171 && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
104172 pOrderBy = 0;
104175 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
104176 ** if the select-list is the same as the ORDER BY list, then this query
104177 ** can be rewritten as a GROUP BY. In other words, this:
104179 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
104181 ** is transformed to:
104183 ** SELECT xyz FROM ... GROUP BY xyz
104185 ** The second form is preferred as a single index (or temp-table) may be
104186 ** used for both the ORDER BY and DISTINCT processing. As originally
104187 ** written the query must use a temp-table for at least one of the ORDER
104188 ** BY and DISTINCT, and an index or separate temp-table for the other.
104190 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
104191 && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
104193 p->selFlags &= ~SF_Distinct;
104194 p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
104195 pGroupBy = p->pGroupBy;
104196 pOrderBy = 0;
104197 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
104198 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
104199 ** original setting of the SF_Distinct flag, not the current setting */
104200 assert( sDistinct.isTnct );
104203 /* If there is an ORDER BY clause, then this sorting
104204 ** index might end up being unused if the data can be
104205 ** extracted in pre-sorted order. If that is the case, then the
104206 ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
104207 ** we figure out that the sorting index is not needed. The addrSortIndex
104208 ** variable is used to facilitate that change.
104210 if( pOrderBy ){
104211 KeyInfo *pKeyInfo;
104212 pKeyInfo = keyInfoFromExprList(pParse, pOrderBy, 0);
104213 pOrderBy->iECursor = pParse->nTab++;
104214 p->addrOpenEphm[2] = addrSortIndex =
104215 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
104216 pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
104217 (char*)pKeyInfo, P4_KEYINFO);
104218 }else{
104219 addrSortIndex = -1;
104222 /* If the output is destined for a temporary table, open that table.
104224 if( pDest->eDest==SRT_EphemTab ){
104225 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
104228 /* Set the limiter.
104230 iEnd = sqlite3VdbeMakeLabel(v);
104231 p->nSelectRow = LARGEST_INT64;
104232 computeLimitRegisters(pParse, p, iEnd);
104233 if( p->iLimit==0 && addrSortIndex>=0 ){
104234 sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
104235 p->selFlags |= SF_UseSorter;
104238 /* Open a virtual index to use for the distinct set.
104240 if( p->selFlags & SF_Distinct ){
104241 sDistinct.tabTnct = pParse->nTab++;
104242 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
104243 sDistinct.tabTnct, 0, 0,
104244 (char*)keyInfoFromExprList(pParse, p->pEList, 0),
104245 P4_KEYINFO);
104246 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
104247 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
104248 }else{
104249 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
104252 if( !isAgg && pGroupBy==0 ){
104253 /* No aggregate functions and no GROUP BY clause */
104254 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
104256 /* Begin the database scan. */
104257 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
104258 wctrlFlags, 0);
104259 if( pWInfo==0 ) goto select_end;
104260 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
104261 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
104263 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
104264 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
104266 if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
104268 /* If sorting index that was created by a prior OP_OpenEphemeral
104269 ** instruction ended up not being needed, then change the OP_OpenEphemeral
104270 ** into an OP_Noop.
104272 if( addrSortIndex>=0 && pOrderBy==0 ){
104273 sqlite3VdbeChangeToNoop(v, addrSortIndex);
104274 p->addrOpenEphm[2] = -1;
104277 /* Use the standard inner loop. */
104278 selectInnerLoop(pParse, p, pEList, -1, pOrderBy, &sDistinct, pDest,
104279 sqlite3WhereContinueLabel(pWInfo),
104280 sqlite3WhereBreakLabel(pWInfo));
104282 /* End the database scan loop.
104284 sqlite3WhereEnd(pWInfo);
104285 }else{
104286 /* This case when there exist aggregate functions or a GROUP BY clause
104287 ** or both */
104288 NameContext sNC; /* Name context for processing aggregate information */
104289 int iAMem; /* First Mem address for storing current GROUP BY */
104290 int iBMem; /* First Mem address for previous GROUP BY */
104291 int iUseFlag; /* Mem address holding flag indicating that at least
104292 ** one row of the input to the aggregator has been
104293 ** processed */
104294 int iAbortFlag; /* Mem address which causes query abort if positive */
104295 int groupBySort; /* Rows come from source in GROUP BY order */
104296 int addrEnd; /* End of processing for this SELECT */
104297 int sortPTab = 0; /* Pseudotable used to decode sorting results */
104298 int sortOut = 0; /* Output register from the sorter */
104300 /* Remove any and all aliases between the result set and the
104301 ** GROUP BY clause.
104303 if( pGroupBy ){
104304 int k; /* Loop counter */
104305 struct ExprList_item *pItem; /* For looping over expression in a list */
104307 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
104308 pItem->u.x.iAlias = 0;
104310 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
104311 pItem->u.x.iAlias = 0;
104313 if( p->nSelectRow>100 ) p->nSelectRow = 100;
104314 }else{
104315 p->nSelectRow = 1;
104319 /* Create a label to jump to when we want to abort the query */
104320 addrEnd = sqlite3VdbeMakeLabel(v);
104322 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
104323 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
104324 ** SELECT statement.
104326 memset(&sNC, 0, sizeof(sNC));
104327 sNC.pParse = pParse;
104328 sNC.pSrcList = pTabList;
104329 sNC.pAggInfo = &sAggInfo;
104330 sAggInfo.mnReg = pParse->nMem+1;
104331 sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
104332 sAggInfo.pGroupBy = pGroupBy;
104333 sqlite3ExprAnalyzeAggList(&sNC, pEList);
104334 sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
104335 if( pHaving ){
104336 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
104338 sAggInfo.nAccumulator = sAggInfo.nColumn;
104339 for(i=0; i<sAggInfo.nFunc; i++){
104340 assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
104341 sNC.ncFlags |= NC_InAggFunc;
104342 sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
104343 sNC.ncFlags &= ~NC_InAggFunc;
104345 sAggInfo.mxReg = pParse->nMem;
104346 if( db->mallocFailed ) goto select_end;
104348 /* Processing for aggregates with GROUP BY is very different and
104349 ** much more complex than aggregates without a GROUP BY.
104351 if( pGroupBy ){
104352 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
104353 int j1; /* A-vs-B comparision jump */
104354 int addrOutputRow; /* Start of subroutine that outputs a result row */
104355 int regOutputRow; /* Return address register for output subroutine */
104356 int addrSetAbort; /* Set the abort flag and return */
104357 int addrTopOfLoop; /* Top of the input loop */
104358 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
104359 int addrReset; /* Subroutine for resetting the accumulator */
104360 int regReset; /* Return address register for reset subroutine */
104362 /* If there is a GROUP BY clause we might need a sorting index to
104363 ** implement it. Allocate that sorting index now. If it turns out
104364 ** that we do not need it after all, the OP_SorterOpen instruction
104365 ** will be converted into a Noop.
104367 sAggInfo.sortingIdx = pParse->nTab++;
104368 pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0);
104369 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
104370 sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
104371 0, (char*)pKeyInfo, P4_KEYINFO);
104373 /* Initialize memory locations used by GROUP BY aggregate processing
104375 iUseFlag = ++pParse->nMem;
104376 iAbortFlag = ++pParse->nMem;
104377 regOutputRow = ++pParse->nMem;
104378 addrOutputRow = sqlite3VdbeMakeLabel(v);
104379 regReset = ++pParse->nMem;
104380 addrReset = sqlite3VdbeMakeLabel(v);
104381 iAMem = pParse->nMem + 1;
104382 pParse->nMem += pGroupBy->nExpr;
104383 iBMem = pParse->nMem + 1;
104384 pParse->nMem += pGroupBy->nExpr;
104385 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
104386 VdbeComment((v, "clear abort flag"));
104387 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
104388 VdbeComment((v, "indicate accumulator empty"));
104389 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
104391 /* Begin a loop that will extract all source rows in GROUP BY order.
104392 ** This might involve two separate loops with an OP_Sort in between, or
104393 ** it might be a single loop that uses an index to extract information
104394 ** in the right order to begin with.
104396 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
104397 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
104398 WHERE_GROUPBY, 0);
104399 if( pWInfo==0 ) goto select_end;
104400 if( sqlite3WhereIsOrdered(pWInfo) ){
104401 /* The optimizer is able to deliver rows in group by order so
104402 ** we do not have to sort. The OP_OpenEphemeral table will be
104403 ** cancelled later because we still need to use the pKeyInfo
104405 groupBySort = 0;
104406 }else{
104407 /* Rows are coming out in undetermined order. We have to push
104408 ** each row into a sorting index, terminate the first loop,
104409 ** then loop over the sorting index in order to get the output
104410 ** in sorted order
104412 int regBase;
104413 int regRecord;
104414 int nCol;
104415 int nGroupBy;
104417 explainTempTable(pParse,
104418 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
104419 "DISTINCT" : "GROUP BY");
104421 groupBySort = 1;
104422 nGroupBy = pGroupBy->nExpr;
104423 nCol = nGroupBy + 1;
104424 j = nGroupBy+1;
104425 for(i=0; i<sAggInfo.nColumn; i++){
104426 if( sAggInfo.aCol[i].iSorterColumn>=j ){
104427 nCol++;
104431 regBase = sqlite3GetTempRange(pParse, nCol);
104432 sqlite3ExprCacheClear(pParse);
104433 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
104434 sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
104435 j = nGroupBy+1;
104436 for(i=0; i<sAggInfo.nColumn; i++){
104437 struct AggInfo_col *pCol = &sAggInfo.aCol[i];
104438 if( pCol->iSorterColumn>=j ){
104439 int r1 = j + regBase;
104440 int r2;
104442 r2 = sqlite3ExprCodeGetColumn(pParse,
104443 pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
104444 if( r1!=r2 ){
104445 sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
104450 regRecord = sqlite3GetTempReg(pParse);
104451 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
104452 sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
104453 sqlite3ReleaseTempReg(pParse, regRecord);
104454 sqlite3ReleaseTempRange(pParse, regBase, nCol);
104455 sqlite3WhereEnd(pWInfo);
104456 sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
104457 sortOut = sqlite3GetTempReg(pParse);
104458 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
104459 sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
104460 VdbeComment((v, "GROUP BY sort"));
104461 sAggInfo.useSortingIdx = 1;
104462 sqlite3ExprCacheClear(pParse);
104465 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
104466 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
104467 ** Then compare the current GROUP BY terms against the GROUP BY terms
104468 ** from the previous row currently stored in a0, a1, a2...
104470 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
104471 sqlite3ExprCacheClear(pParse);
104472 if( groupBySort ){
104473 sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
104475 for(j=0; j<pGroupBy->nExpr; j++){
104476 if( groupBySort ){
104477 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
104478 if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
104479 }else{
104480 sAggInfo.directMode = 1;
104481 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
104484 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
104485 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
104486 j1 = sqlite3VdbeCurrentAddr(v);
104487 sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
104489 /* Generate code that runs whenever the GROUP BY changes.
104490 ** Changes in the GROUP BY are detected by the previous code
104491 ** block. If there were no changes, this block is skipped.
104493 ** This code copies current group by terms in b0,b1,b2,...
104494 ** over to a0,a1,a2. It then calls the output subroutine
104495 ** and resets the aggregate accumulator registers in preparation
104496 ** for the next GROUP BY batch.
104498 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
104499 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
104500 VdbeComment((v, "output one row"));
104501 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
104502 VdbeComment((v, "check abort flag"));
104503 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
104504 VdbeComment((v, "reset accumulator"));
104506 /* Update the aggregate accumulators based on the content of
104507 ** the current row
104509 sqlite3VdbeJumpHere(v, j1);
104510 updateAccumulator(pParse, &sAggInfo);
104511 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
104512 VdbeComment((v, "indicate data in accumulator"));
104514 /* End of the loop
104516 if( groupBySort ){
104517 sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
104518 }else{
104519 sqlite3WhereEnd(pWInfo);
104520 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
104523 /* Output the final row of result
104525 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
104526 VdbeComment((v, "output final row"));
104528 /* Jump over the subroutines
104530 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
104532 /* Generate a subroutine that outputs a single row of the result
104533 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
104534 ** is less than or equal to zero, the subroutine is a no-op. If
104535 ** the processing calls for the query to abort, this subroutine
104536 ** increments the iAbortFlag memory location before returning in
104537 ** order to signal the caller to abort.
104539 addrSetAbort = sqlite3VdbeCurrentAddr(v);
104540 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
104541 VdbeComment((v, "set abort flag"));
104542 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
104543 sqlite3VdbeResolveLabel(v, addrOutputRow);
104544 addrOutputRow = sqlite3VdbeCurrentAddr(v);
104545 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
104546 VdbeComment((v, "Groupby result generator entry point"));
104547 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
104548 finalizeAggFunctions(pParse, &sAggInfo);
104549 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
104550 selectInnerLoop(pParse, p, p->pEList, -1, pOrderBy,
104551 &sDistinct, pDest,
104552 addrOutputRow+1, addrSetAbort);
104553 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
104554 VdbeComment((v, "end groupby result generator"));
104556 /* Generate a subroutine that will reset the group-by accumulator
104558 sqlite3VdbeResolveLabel(v, addrReset);
104559 resetAccumulator(pParse, &sAggInfo);
104560 sqlite3VdbeAddOp1(v, OP_Return, regReset);
104562 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
104563 else {
104564 ExprList *pDel = 0;
104565 #ifndef SQLITE_OMIT_BTREECOUNT
104566 Table *pTab;
104567 if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
104568 /* If isSimpleCount() returns a pointer to a Table structure, then
104569 ** the SQL statement is of the form:
104571 ** SELECT count(*) FROM <tbl>
104573 ** where the Table structure returned represents table <tbl>.
104575 ** This statement is so common that it is optimized specially. The
104576 ** OP_Count instruction is executed either on the intkey table that
104577 ** contains the data for table <tbl> or on one of its indexes. It
104578 ** is better to execute the op on an index, as indexes are almost
104579 ** always spread across less pages than their corresponding tables.
104581 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
104582 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
104583 Index *pIdx; /* Iterator variable */
104584 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
104585 Index *pBest = 0; /* Best index found so far */
104586 int iRoot = pTab->tnum; /* Root page of scanned b-tree */
104588 sqlite3CodeVerifySchema(pParse, iDb);
104589 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
104591 /* Search for the index that has the lowest scan cost.
104593 ** (2011-04-15) Do not do a full scan of an unordered index.
104595 ** (2013-10-03) Do not count the entries in a partial index.
104597 ** In practice the KeyInfo structure will not be used. It is only
104598 ** passed to keep OP_OpenRead happy.
104600 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
104601 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104602 if( pIdx->bUnordered==0
104603 && pIdx->szIdxRow<pTab->szTabRow
104604 && pIdx->pPartIdxWhere==0
104605 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
104607 pBest = pIdx;
104610 if( pBest ){
104611 iRoot = pBest->tnum;
104612 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
104615 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
104616 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
104617 if( pKeyInfo ){
104618 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
104620 sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
104621 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
104622 explainSimpleCount(pParse, pTab, pBest);
104623 }else
104624 #endif /* SQLITE_OMIT_BTREECOUNT */
104626 /* Check if the query is of one of the following forms:
104628 ** SELECT min(x) FROM ...
104629 ** SELECT max(x) FROM ...
104631 ** If it is, then ask the code in where.c to attempt to sort results
104632 ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
104633 ** If where.c is able to produce results sorted in this order, then
104634 ** add vdbe code to break out of the processing loop after the
104635 ** first iteration (since the first iteration of the loop is
104636 ** guaranteed to operate on the row with the minimum or maximum
104637 ** value of x, the only row required).
104639 ** A special flag must be passed to sqlite3WhereBegin() to slightly
104640 ** modify behavior as follows:
104642 ** + If the query is a "SELECT min(x)", then the loop coded by
104643 ** where.c should not iterate over any values with a NULL value
104644 ** for x.
104646 ** + The optimizer code in where.c (the thing that decides which
104647 ** index or indices to use) should place a different priority on
104648 ** satisfying the 'ORDER BY' clause than it does in other cases.
104649 ** Refer to code and comments in where.c for details.
104651 ExprList *pMinMax = 0;
104652 u8 flag = WHERE_ORDERBY_NORMAL;
104654 assert( p->pGroupBy==0 );
104655 assert( flag==0 );
104656 if( p->pHaving==0 ){
104657 flag = minMaxQuery(&sAggInfo, &pMinMax);
104659 assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
104661 if( flag ){
104662 pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
104663 pDel = pMinMax;
104664 if( pMinMax && !db->mallocFailed ){
104665 pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
104666 pMinMax->a[0].pExpr->op = TK_COLUMN;
104670 /* This case runs if the aggregate has no GROUP BY clause. The
104671 ** processing is much simpler since there is only a single row
104672 ** of output.
104674 resetAccumulator(pParse, &sAggInfo);
104675 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
104676 if( pWInfo==0 ){
104677 sqlite3ExprListDelete(db, pDel);
104678 goto select_end;
104680 updateAccumulator(pParse, &sAggInfo);
104681 assert( pMinMax==0 || pMinMax->nExpr==1 );
104682 if( sqlite3WhereIsOrdered(pWInfo) ){
104683 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
104684 VdbeComment((v, "%s() by index",
104685 (flag==WHERE_ORDERBY_MIN?"min":"max")));
104687 sqlite3WhereEnd(pWInfo);
104688 finalizeAggFunctions(pParse, &sAggInfo);
104691 pOrderBy = 0;
104692 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
104693 selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
104694 pDest, addrEnd, addrEnd);
104695 sqlite3ExprListDelete(db, pDel);
104697 sqlite3VdbeResolveLabel(v, addrEnd);
104699 } /* endif aggregate query */
104701 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
104702 explainTempTable(pParse, "DISTINCT");
104705 /* If there is an ORDER BY clause, then we need to sort the results
104706 ** and send them to the callback one by one.
104708 if( pOrderBy ){
104709 explainTempTable(pParse, "ORDER BY");
104710 generateSortTail(pParse, p, v, pEList->nExpr, pDest);
104713 /* Jump here to skip this query
104715 sqlite3VdbeResolveLabel(v, iEnd);
104717 /* The SELECT was successfully coded. Set the return code to 0
104718 ** to indicate no errors.
104720 rc = 0;
104722 /* Control jumps to here if an error is encountered above, or upon
104723 ** successful coding of the SELECT.
104725 select_end:
104726 explainSetInteger(pParse->iSelectId, iRestoreSelectId);
104728 /* Identify column names if results of the SELECT are to be output.
104730 if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
104731 generateColumnNames(pParse, pTabList, pEList);
104734 sqlite3DbFree(db, sAggInfo.aCol);
104735 sqlite3DbFree(db, sAggInfo.aFunc);
104736 return rc;
104739 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
104741 ** Generate a human-readable description of a the Select object.
104743 static void explainOneSelect(Vdbe *pVdbe, Select *p){
104744 sqlite3ExplainPrintf(pVdbe, "SELECT ");
104745 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
104746 if( p->selFlags & SF_Distinct ){
104747 sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
104749 if( p->selFlags & SF_Aggregate ){
104750 sqlite3ExplainPrintf(pVdbe, "agg_flag ");
104752 sqlite3ExplainNL(pVdbe);
104753 sqlite3ExplainPrintf(pVdbe, " ");
104755 sqlite3ExplainExprList(pVdbe, p->pEList);
104756 sqlite3ExplainNL(pVdbe);
104757 if( p->pSrc && p->pSrc->nSrc ){
104758 int i;
104759 sqlite3ExplainPrintf(pVdbe, "FROM ");
104760 sqlite3ExplainPush(pVdbe);
104761 for(i=0; i<p->pSrc->nSrc; i++){
104762 struct SrcList_item *pItem = &p->pSrc->a[i];
104763 sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
104764 if( pItem->pSelect ){
104765 sqlite3ExplainSelect(pVdbe, pItem->pSelect);
104766 if( pItem->pTab ){
104767 sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
104769 }else if( pItem->zName ){
104770 sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
104772 if( pItem->zAlias ){
104773 sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
104775 if( pItem->jointype & JT_LEFT ){
104776 sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
104778 sqlite3ExplainNL(pVdbe);
104780 sqlite3ExplainPop(pVdbe);
104782 if( p->pWhere ){
104783 sqlite3ExplainPrintf(pVdbe, "WHERE ");
104784 sqlite3ExplainExpr(pVdbe, p->pWhere);
104785 sqlite3ExplainNL(pVdbe);
104787 if( p->pGroupBy ){
104788 sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
104789 sqlite3ExplainExprList(pVdbe, p->pGroupBy);
104790 sqlite3ExplainNL(pVdbe);
104792 if( p->pHaving ){
104793 sqlite3ExplainPrintf(pVdbe, "HAVING ");
104794 sqlite3ExplainExpr(pVdbe, p->pHaving);
104795 sqlite3ExplainNL(pVdbe);
104797 if( p->pOrderBy ){
104798 sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
104799 sqlite3ExplainExprList(pVdbe, p->pOrderBy);
104800 sqlite3ExplainNL(pVdbe);
104802 if( p->pLimit ){
104803 sqlite3ExplainPrintf(pVdbe, "LIMIT ");
104804 sqlite3ExplainExpr(pVdbe, p->pLimit);
104805 sqlite3ExplainNL(pVdbe);
104807 if( p->pOffset ){
104808 sqlite3ExplainPrintf(pVdbe, "OFFSET ");
104809 sqlite3ExplainExpr(pVdbe, p->pOffset);
104810 sqlite3ExplainNL(pVdbe);
104813 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
104814 if( p==0 ){
104815 sqlite3ExplainPrintf(pVdbe, "(null-select)");
104816 return;
104818 while( p->pPrior ){
104819 p->pPrior->pNext = p;
104820 p = p->pPrior;
104822 sqlite3ExplainPush(pVdbe);
104823 while( p ){
104824 explainOneSelect(pVdbe, p);
104825 p = p->pNext;
104826 if( p==0 ) break;
104827 sqlite3ExplainNL(pVdbe);
104828 sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
104830 sqlite3ExplainPrintf(pVdbe, "END");
104831 sqlite3ExplainPop(pVdbe);
104834 /* End of the structure debug printing code
104835 *****************************************************************************/
104836 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
104838 /************** End of select.c **********************************************/
104839 /************** Begin file table.c *******************************************/
104841 ** 2001 September 15
104843 ** The author disclaims copyright to this source code. In place of
104844 ** a legal notice, here is a blessing:
104846 ** May you do good and not evil.
104847 ** May you find forgiveness for yourself and forgive others.
104848 ** May you share freely, never taking more than you give.
104850 *************************************************************************
104851 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
104852 ** interface routines. These are just wrappers around the main
104853 ** interface routine of sqlite3_exec().
104855 ** These routines are in a separate files so that they will not be linked
104856 ** if they are not used.
104858 /* #include <stdlib.h> */
104859 /* #include <string.h> */
104861 #ifndef SQLITE_OMIT_GET_TABLE
104864 ** This structure is used to pass data from sqlite3_get_table() through
104865 ** to the callback function is uses to build the result.
104867 typedef struct TabResult {
104868 char **azResult; /* Accumulated output */
104869 char *zErrMsg; /* Error message text, if an error occurs */
104870 int nAlloc; /* Slots allocated for azResult[] */
104871 int nRow; /* Number of rows in the result */
104872 int nColumn; /* Number of columns in the result */
104873 int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
104874 int rc; /* Return code from sqlite3_exec() */
104875 } TabResult;
104878 ** This routine is called once for each row in the result table. Its job
104879 ** is to fill in the TabResult structure appropriately, allocating new
104880 ** memory as necessary.
104882 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
104883 TabResult *p = (TabResult*)pArg; /* Result accumulator */
104884 int need; /* Slots needed in p->azResult[] */
104885 int i; /* Loop counter */
104886 char *z; /* A single column of result */
104888 /* Make sure there is enough space in p->azResult to hold everything
104889 ** we need to remember from this invocation of the callback.
104891 if( p->nRow==0 && argv!=0 ){
104892 need = nCol*2;
104893 }else{
104894 need = nCol;
104896 if( p->nData + need > p->nAlloc ){
104897 char **azNew;
104898 p->nAlloc = p->nAlloc*2 + need;
104899 azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
104900 if( azNew==0 ) goto malloc_failed;
104901 p->azResult = azNew;
104904 /* If this is the first row, then generate an extra row containing
104905 ** the names of all columns.
104907 if( p->nRow==0 ){
104908 p->nColumn = nCol;
104909 for(i=0; i<nCol; i++){
104910 z = sqlite3_mprintf("%s", colv[i]);
104911 if( z==0 ) goto malloc_failed;
104912 p->azResult[p->nData++] = z;
104914 }else if( p->nColumn!=nCol ){
104915 sqlite3_free(p->zErrMsg);
104916 p->zErrMsg = sqlite3_mprintf(
104917 "sqlite3_get_table() called with two or more incompatible queries"
104919 p->rc = SQLITE_ERROR;
104920 return 1;
104923 /* Copy over the row data
104925 if( argv!=0 ){
104926 for(i=0; i<nCol; i++){
104927 if( argv[i]==0 ){
104928 z = 0;
104929 }else{
104930 int n = sqlite3Strlen30(argv[i])+1;
104931 z = sqlite3_malloc( n );
104932 if( z==0 ) goto malloc_failed;
104933 memcpy(z, argv[i], n);
104935 p->azResult[p->nData++] = z;
104937 p->nRow++;
104939 return 0;
104941 malloc_failed:
104942 p->rc = SQLITE_NOMEM;
104943 return 1;
104947 ** Query the database. But instead of invoking a callback for each row,
104948 ** malloc() for space to hold the result and return the entire results
104949 ** at the conclusion of the call.
104951 ** The result that is written to ***pazResult is held in memory obtained
104952 ** from malloc(). But the caller cannot free this memory directly.
104953 ** Instead, the entire table should be passed to sqlite3_free_table() when
104954 ** the calling procedure is finished using it.
104956 SQLITE_API int sqlite3_get_table(
104957 sqlite3 *db, /* The database on which the SQL executes */
104958 const char *zSql, /* The SQL to be executed */
104959 char ***pazResult, /* Write the result table here */
104960 int *pnRow, /* Write the number of rows in the result here */
104961 int *pnColumn, /* Write the number of columns of result here */
104962 char **pzErrMsg /* Write error messages here */
104964 int rc;
104965 TabResult res;
104967 *pazResult = 0;
104968 if( pnColumn ) *pnColumn = 0;
104969 if( pnRow ) *pnRow = 0;
104970 if( pzErrMsg ) *pzErrMsg = 0;
104971 res.zErrMsg = 0;
104972 res.nRow = 0;
104973 res.nColumn = 0;
104974 res.nData = 1;
104975 res.nAlloc = 20;
104976 res.rc = SQLITE_OK;
104977 res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
104978 if( res.azResult==0 ){
104979 db->errCode = SQLITE_NOMEM;
104980 return SQLITE_NOMEM;
104982 res.azResult[0] = 0;
104983 rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
104984 assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
104985 res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
104986 if( (rc&0xff)==SQLITE_ABORT ){
104987 sqlite3_free_table(&res.azResult[1]);
104988 if( res.zErrMsg ){
104989 if( pzErrMsg ){
104990 sqlite3_free(*pzErrMsg);
104991 *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
104993 sqlite3_free(res.zErrMsg);
104995 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
104996 return res.rc;
104998 sqlite3_free(res.zErrMsg);
104999 if( rc!=SQLITE_OK ){
105000 sqlite3_free_table(&res.azResult[1]);
105001 return rc;
105003 if( res.nAlloc>res.nData ){
105004 char **azNew;
105005 azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
105006 if( azNew==0 ){
105007 sqlite3_free_table(&res.azResult[1]);
105008 db->errCode = SQLITE_NOMEM;
105009 return SQLITE_NOMEM;
105011 res.azResult = azNew;
105013 *pazResult = &res.azResult[1];
105014 if( pnColumn ) *pnColumn = res.nColumn;
105015 if( pnRow ) *pnRow = res.nRow;
105016 return rc;
105020 ** This routine frees the space the sqlite3_get_table() malloced.
105022 SQLITE_API void sqlite3_free_table(
105023 char **azResult /* Result returned from from sqlite3_get_table() */
105025 if( azResult ){
105026 int i, n;
105027 azResult--;
105028 assert( azResult!=0 );
105029 n = SQLITE_PTR_TO_INT(azResult[0]);
105030 for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
105031 sqlite3_free(azResult);
105035 #endif /* SQLITE_OMIT_GET_TABLE */
105037 /************** End of table.c ***********************************************/
105038 /************** Begin file trigger.c *****************************************/
105041 ** The author disclaims copyright to this source code. In place of
105042 ** a legal notice, here is a blessing:
105044 ** May you do good and not evil.
105045 ** May you find forgiveness for yourself and forgive others.
105046 ** May you share freely, never taking more than you give.
105048 *************************************************************************
105049 ** This file contains the implementation for TRIGGERs
105052 #ifndef SQLITE_OMIT_TRIGGER
105054 ** Delete a linked list of TriggerStep structures.
105056 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
105057 while( pTriggerStep ){
105058 TriggerStep * pTmp = pTriggerStep;
105059 pTriggerStep = pTriggerStep->pNext;
105061 sqlite3ExprDelete(db, pTmp->pWhere);
105062 sqlite3ExprListDelete(db, pTmp->pExprList);
105063 sqlite3SelectDelete(db, pTmp->pSelect);
105064 sqlite3IdListDelete(db, pTmp->pIdList);
105066 sqlite3DbFree(db, pTmp);
105071 ** Given table pTab, return a list of all the triggers attached to
105072 ** the table. The list is connected by Trigger.pNext pointers.
105074 ** All of the triggers on pTab that are in the same database as pTab
105075 ** are already attached to pTab->pTrigger. But there might be additional
105076 ** triggers on pTab in the TEMP schema. This routine prepends all
105077 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
105078 ** and returns the combined list.
105080 ** To state it another way: This routine returns a list of all triggers
105081 ** that fire off of pTab. The list will include any TEMP triggers on
105082 ** pTab as well as the triggers lised in pTab->pTrigger.
105084 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
105085 Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
105086 Trigger *pList = 0; /* List of triggers to return */
105088 if( pParse->disableTriggers ){
105089 return 0;
105092 if( pTmpSchema!=pTab->pSchema ){
105093 HashElem *p;
105094 assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
105095 for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
105096 Trigger *pTrig = (Trigger *)sqliteHashData(p);
105097 if( pTrig->pTabSchema==pTab->pSchema
105098 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
105100 pTrig->pNext = (pList ? pList : pTab->pTrigger);
105101 pList = pTrig;
105106 return (pList ? pList : pTab->pTrigger);
105110 ** This is called by the parser when it sees a CREATE TRIGGER statement
105111 ** up to the point of the BEGIN before the trigger actions. A Trigger
105112 ** structure is generated based on the information available and stored
105113 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
105114 ** sqlite3FinishTrigger() function is called to complete the trigger
105115 ** construction process.
105117 SQLITE_PRIVATE void sqlite3BeginTrigger(
105118 Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
105119 Token *pName1, /* The name of the trigger */
105120 Token *pName2, /* The name of the trigger */
105121 int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
105122 int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
105123 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
105124 SrcList *pTableName,/* The name of the table/view the trigger applies to */
105125 Expr *pWhen, /* WHEN clause */
105126 int isTemp, /* True if the TEMPORARY keyword is present */
105127 int noErr /* Suppress errors if the trigger already exists */
105129 Trigger *pTrigger = 0; /* The new trigger */
105130 Table *pTab; /* Table that the trigger fires off of */
105131 char *zName = 0; /* Name of the trigger */
105132 sqlite3 *db = pParse->db; /* The database connection */
105133 int iDb; /* The database to store the trigger in */
105134 Token *pName; /* The unqualified db name */
105135 DbFixer sFix; /* State vector for the DB fixer */
105136 int iTabDb; /* Index of the database holding pTab */
105138 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
105139 assert( pName2!=0 );
105140 assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
105141 assert( op>0 && op<0xff );
105142 if( isTemp ){
105143 /* If TEMP was specified, then the trigger name may not be qualified. */
105144 if( pName2->n>0 ){
105145 sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
105146 goto trigger_cleanup;
105148 iDb = 1;
105149 pName = pName1;
105150 }else{
105151 /* Figure out the db that the trigger will be created in */
105152 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
105153 if( iDb<0 ){
105154 goto trigger_cleanup;
105157 if( !pTableName || db->mallocFailed ){
105158 goto trigger_cleanup;
105161 /* A long-standing parser bug is that this syntax was allowed:
105163 ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
105164 ** ^^^^^^^^
105166 ** To maintain backwards compatibility, ignore the database
105167 ** name on pTableName if we are reparsing our of SQLITE_MASTER.
105169 if( db->init.busy && iDb!=1 ){
105170 sqlite3DbFree(db, pTableName->a[0].zDatabase);
105171 pTableName->a[0].zDatabase = 0;
105174 /* If the trigger name was unqualified, and the table is a temp table,
105175 ** then set iDb to 1 to create the trigger in the temporary database.
105176 ** If sqlite3SrcListLookup() returns 0, indicating the table does not
105177 ** exist, the error is caught by the block below.
105179 pTab = sqlite3SrcListLookup(pParse, pTableName);
105180 if( db->init.busy==0 && pName2->n==0 && pTab
105181 && pTab->pSchema==db->aDb[1].pSchema ){
105182 iDb = 1;
105185 /* Ensure the table name matches database name and that the table exists */
105186 if( db->mallocFailed ) goto trigger_cleanup;
105187 assert( pTableName->nSrc==1 );
105188 sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
105189 if( sqlite3FixSrcList(&sFix, pTableName) ){
105190 goto trigger_cleanup;
105192 pTab = sqlite3SrcListLookup(pParse, pTableName);
105193 if( !pTab ){
105194 /* The table does not exist. */
105195 if( db->init.iDb==1 ){
105196 /* Ticket #3810.
105197 ** Normally, whenever a table is dropped, all associated triggers are
105198 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
105199 ** and the table is dropped by a different database connection, the
105200 ** trigger is not visible to the database connection that does the
105201 ** drop so the trigger cannot be dropped. This results in an
105202 ** "orphaned trigger" - a trigger whose associated table is missing.
105204 db->init.orphanTrigger = 1;
105206 goto trigger_cleanup;
105208 if( IsVirtual(pTab) ){
105209 sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
105210 goto trigger_cleanup;
105213 /* Check that the trigger name is not reserved and that no trigger of the
105214 ** specified name exists */
105215 zName = sqlite3NameFromToken(db, pName);
105216 if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
105217 goto trigger_cleanup;
105219 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
105220 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
105221 zName, sqlite3Strlen30(zName)) ){
105222 if( !noErr ){
105223 sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
105224 }else{
105225 assert( !db->init.busy );
105226 sqlite3CodeVerifySchema(pParse, iDb);
105228 goto trigger_cleanup;
105231 /* Do not create a trigger on a system table */
105232 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
105233 sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
105234 pParse->nErr++;
105235 goto trigger_cleanup;
105238 /* INSTEAD of triggers are only for views and views only support INSTEAD
105239 ** of triggers.
105241 if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
105242 sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
105243 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
105244 goto trigger_cleanup;
105246 if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
105247 sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
105248 " trigger on table: %S", pTableName, 0);
105249 goto trigger_cleanup;
105251 iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105253 #ifndef SQLITE_OMIT_AUTHORIZATION
105255 int code = SQLITE_CREATE_TRIGGER;
105256 const char *zDb = db->aDb[iTabDb].zName;
105257 const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
105258 if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
105259 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
105260 goto trigger_cleanup;
105262 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
105263 goto trigger_cleanup;
105266 #endif
105268 /* INSTEAD OF triggers can only appear on views and BEFORE triggers
105269 ** cannot appear on views. So we might as well translate every
105270 ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
105271 ** elsewhere.
105273 if (tr_tm == TK_INSTEAD){
105274 tr_tm = TK_BEFORE;
105277 /* Build the Trigger object */
105278 pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
105279 if( pTrigger==0 ) goto trigger_cleanup;
105280 pTrigger->zName = zName;
105281 zName = 0;
105282 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
105283 pTrigger->pSchema = db->aDb[iDb].pSchema;
105284 pTrigger->pTabSchema = pTab->pSchema;
105285 pTrigger->op = (u8)op;
105286 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
105287 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
105288 pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
105289 assert( pParse->pNewTrigger==0 );
105290 pParse->pNewTrigger = pTrigger;
105292 trigger_cleanup:
105293 sqlite3DbFree(db, zName);
105294 sqlite3SrcListDelete(db, pTableName);
105295 sqlite3IdListDelete(db, pColumns);
105296 sqlite3ExprDelete(db, pWhen);
105297 if( !pParse->pNewTrigger ){
105298 sqlite3DeleteTrigger(db, pTrigger);
105299 }else{
105300 assert( pParse->pNewTrigger==pTrigger );
105305 ** This routine is called after all of the trigger actions have been parsed
105306 ** in order to complete the process of building the trigger.
105308 SQLITE_PRIVATE void sqlite3FinishTrigger(
105309 Parse *pParse, /* Parser context */
105310 TriggerStep *pStepList, /* The triggered program */
105311 Token *pAll /* Token that describes the complete CREATE TRIGGER */
105313 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
105314 char *zName; /* Name of trigger */
105315 sqlite3 *db = pParse->db; /* The database */
105316 DbFixer sFix; /* Fixer object */
105317 int iDb; /* Database containing the trigger */
105318 Token nameToken; /* Trigger name for error reporting */
105320 pParse->pNewTrigger = 0;
105321 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
105322 zName = pTrig->zName;
105323 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
105324 pTrig->step_list = pStepList;
105325 while( pStepList ){
105326 pStepList->pTrig = pTrig;
105327 pStepList = pStepList->pNext;
105329 nameToken.z = pTrig->zName;
105330 nameToken.n = sqlite3Strlen30(nameToken.z);
105331 sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
105332 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
105333 || sqlite3FixExpr(&sFix, pTrig->pWhen)
105335 goto triggerfinish_cleanup;
105338 /* if we are not initializing,
105339 ** build the sqlite_master entry
105341 if( !db->init.busy ){
105342 Vdbe *v;
105343 char *z;
105345 /* Make an entry in the sqlite_master table */
105346 v = sqlite3GetVdbe(pParse);
105347 if( v==0 ) goto triggerfinish_cleanup;
105348 sqlite3BeginWriteOperation(pParse, 0, iDb);
105349 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
105350 sqlite3NestedParse(pParse,
105351 "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
105352 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
105353 pTrig->table, z);
105354 sqlite3DbFree(db, z);
105355 sqlite3ChangeCookie(pParse, iDb);
105356 sqlite3VdbeAddParseSchemaOp(v, iDb,
105357 sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
105360 if( db->init.busy ){
105361 Trigger *pLink = pTrig;
105362 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
105363 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
105364 pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
105365 if( pTrig ){
105366 db->mallocFailed = 1;
105367 }else if( pLink->pSchema==pLink->pTabSchema ){
105368 Table *pTab;
105369 int n = sqlite3Strlen30(pLink->table);
105370 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
105371 assert( pTab!=0 );
105372 pLink->pNext = pTab->pTrigger;
105373 pTab->pTrigger = pLink;
105377 triggerfinish_cleanup:
105378 sqlite3DeleteTrigger(db, pTrig);
105379 assert( !pParse->pNewTrigger );
105380 sqlite3DeleteTriggerStep(db, pStepList);
105384 ** Turn a SELECT statement (that the pSelect parameter points to) into
105385 ** a trigger step. Return a pointer to a TriggerStep structure.
105387 ** The parser calls this routine when it finds a SELECT statement in
105388 ** body of a TRIGGER.
105390 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
105391 TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
105392 if( pTriggerStep==0 ) {
105393 sqlite3SelectDelete(db, pSelect);
105394 return 0;
105396 pTriggerStep->op = TK_SELECT;
105397 pTriggerStep->pSelect = pSelect;
105398 pTriggerStep->orconf = OE_Default;
105399 return pTriggerStep;
105403 ** Allocate space to hold a new trigger step. The allocated space
105404 ** holds both the TriggerStep object and the TriggerStep.target.z string.
105406 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
105408 static TriggerStep *triggerStepAllocate(
105409 sqlite3 *db, /* Database connection */
105410 u8 op, /* Trigger opcode */
105411 Token *pName /* The target name */
105413 TriggerStep *pTriggerStep;
105415 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
105416 if( pTriggerStep ){
105417 char *z = (char*)&pTriggerStep[1];
105418 memcpy(z, pName->z, pName->n);
105419 pTriggerStep->target.z = z;
105420 pTriggerStep->target.n = pName->n;
105421 pTriggerStep->op = op;
105423 return pTriggerStep;
105427 ** Build a trigger step out of an INSERT statement. Return a pointer
105428 ** to the new trigger step.
105430 ** The parser calls this routine when it sees an INSERT inside the
105431 ** body of a trigger.
105433 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
105434 sqlite3 *db, /* The database connection */
105435 Token *pTableName, /* Name of the table into which we insert */
105436 IdList *pColumn, /* List of columns in pTableName to insert into */
105437 Select *pSelect, /* A SELECT statement that supplies values */
105438 u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
105440 TriggerStep *pTriggerStep;
105442 assert(pSelect != 0 || db->mallocFailed);
105444 pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
105445 if( pTriggerStep ){
105446 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
105447 pTriggerStep->pIdList = pColumn;
105448 pTriggerStep->orconf = orconf;
105449 }else{
105450 sqlite3IdListDelete(db, pColumn);
105452 sqlite3SelectDelete(db, pSelect);
105454 return pTriggerStep;
105458 ** Construct a trigger step that implements an UPDATE statement and return
105459 ** a pointer to that trigger step. The parser calls this routine when it
105460 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
105462 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
105463 sqlite3 *db, /* The database connection */
105464 Token *pTableName, /* Name of the table to be updated */
105465 ExprList *pEList, /* The SET clause: list of column and new values */
105466 Expr *pWhere, /* The WHERE clause */
105467 u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
105469 TriggerStep *pTriggerStep;
105471 pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
105472 if( pTriggerStep ){
105473 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
105474 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
105475 pTriggerStep->orconf = orconf;
105477 sqlite3ExprListDelete(db, pEList);
105478 sqlite3ExprDelete(db, pWhere);
105479 return pTriggerStep;
105483 ** Construct a trigger step that implements a DELETE statement and return
105484 ** a pointer to that trigger step. The parser calls this routine when it
105485 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
105487 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
105488 sqlite3 *db, /* Database connection */
105489 Token *pTableName, /* The table from which rows are deleted */
105490 Expr *pWhere /* The WHERE clause */
105492 TriggerStep *pTriggerStep;
105494 pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
105495 if( pTriggerStep ){
105496 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
105497 pTriggerStep->orconf = OE_Default;
105499 sqlite3ExprDelete(db, pWhere);
105500 return pTriggerStep;
105504 ** Recursively delete a Trigger structure
105506 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
105507 if( pTrigger==0 ) return;
105508 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
105509 sqlite3DbFree(db, pTrigger->zName);
105510 sqlite3DbFree(db, pTrigger->table);
105511 sqlite3ExprDelete(db, pTrigger->pWhen);
105512 sqlite3IdListDelete(db, pTrigger->pColumns);
105513 sqlite3DbFree(db, pTrigger);
105517 ** This function is called to drop a trigger from the database schema.
105519 ** This may be called directly from the parser and therefore identifies
105520 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
105521 ** same job as this routine except it takes a pointer to the trigger
105522 ** instead of the trigger name.
105524 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
105525 Trigger *pTrigger = 0;
105526 int i;
105527 const char *zDb;
105528 const char *zName;
105529 int nName;
105530 sqlite3 *db = pParse->db;
105532 if( db->mallocFailed ) goto drop_trigger_cleanup;
105533 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
105534 goto drop_trigger_cleanup;
105537 assert( pName->nSrc==1 );
105538 zDb = pName->a[0].zDatabase;
105539 zName = pName->a[0].zName;
105540 nName = sqlite3Strlen30(zName);
105541 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
105542 for(i=OMIT_TEMPDB; i<db->nDb; i++){
105543 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
105544 if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
105545 assert( sqlite3SchemaMutexHeld(db, j, 0) );
105546 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
105547 if( pTrigger ) break;
105549 if( !pTrigger ){
105550 if( !noErr ){
105551 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
105552 }else{
105553 sqlite3CodeVerifyNamedSchema(pParse, zDb);
105555 pParse->checkSchema = 1;
105556 goto drop_trigger_cleanup;
105558 sqlite3DropTriggerPtr(pParse, pTrigger);
105560 drop_trigger_cleanup:
105561 sqlite3SrcListDelete(db, pName);
105565 ** Return a pointer to the Table structure for the table that a trigger
105566 ** is set on.
105568 static Table *tableOfTrigger(Trigger *pTrigger){
105569 int n = sqlite3Strlen30(pTrigger->table);
105570 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
105575 ** Drop a trigger given a pointer to that trigger.
105577 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
105578 Table *pTable;
105579 Vdbe *v;
105580 sqlite3 *db = pParse->db;
105581 int iDb;
105583 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
105584 assert( iDb>=0 && iDb<db->nDb );
105585 pTable = tableOfTrigger(pTrigger);
105586 assert( pTable );
105587 assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
105588 #ifndef SQLITE_OMIT_AUTHORIZATION
105590 int code = SQLITE_DROP_TRIGGER;
105591 const char *zDb = db->aDb[iDb].zName;
105592 const char *zTab = SCHEMA_TABLE(iDb);
105593 if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
105594 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
105595 sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
105596 return;
105599 #endif
105601 /* Generate code to destroy the database record of the trigger.
105603 assert( pTable!=0 );
105604 if( (v = sqlite3GetVdbe(pParse))!=0 ){
105605 int base;
105606 static const VdbeOpList dropTrigger[] = {
105607 { OP_Rewind, 0, ADDR(9), 0},
105608 { OP_String8, 0, 1, 0}, /* 1 */
105609 { OP_Column, 0, 1, 2},
105610 { OP_Ne, 2, ADDR(8), 1},
105611 { OP_String8, 0, 1, 0}, /* 4: "trigger" */
105612 { OP_Column, 0, 0, 2},
105613 { OP_Ne, 2, ADDR(8), 1},
105614 { OP_Delete, 0, 0, 0},
105615 { OP_Next, 0, ADDR(1), 0}, /* 8 */
105618 sqlite3BeginWriteOperation(pParse, 0, iDb);
105619 sqlite3OpenMasterTable(pParse, iDb);
105620 base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
105621 sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
105622 sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
105623 sqlite3ChangeCookie(pParse, iDb);
105624 sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
105625 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
105626 if( pParse->nMem<3 ){
105627 pParse->nMem = 3;
105633 ** Remove a trigger from the hash tables of the sqlite* pointer.
105635 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
105636 Trigger *pTrigger;
105637 Hash *pHash;
105639 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
105640 pHash = &(db->aDb[iDb].pSchema->trigHash);
105641 pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
105642 if( ALWAYS(pTrigger) ){
105643 if( pTrigger->pSchema==pTrigger->pTabSchema ){
105644 Table *pTab = tableOfTrigger(pTrigger);
105645 Trigger **pp;
105646 for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
105647 *pp = (*pp)->pNext;
105649 sqlite3DeleteTrigger(db, pTrigger);
105650 db->flags |= SQLITE_InternChanges;
105655 ** pEList is the SET clause of an UPDATE statement. Each entry
105656 ** in pEList is of the format <id>=<expr>. If any of the entries
105657 ** in pEList have an <id> which matches an identifier in pIdList,
105658 ** then return TRUE. If pIdList==NULL, then it is considered a
105659 ** wildcard that matches anything. Likewise if pEList==NULL then
105660 ** it matches anything so always return true. Return false only
105661 ** if there is no match.
105663 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
105664 int e;
105665 if( pIdList==0 || NEVER(pEList==0) ) return 1;
105666 for(e=0; e<pEList->nExpr; e++){
105667 if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
105669 return 0;
105673 ** Return a list of all triggers on table pTab if there exists at least
105674 ** one trigger that must be fired when an operation of type 'op' is
105675 ** performed on the table, and, if that operation is an UPDATE, if at
105676 ** least one of the columns in pChanges is being modified.
105678 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
105679 Parse *pParse, /* Parse context */
105680 Table *pTab, /* The table the contains the triggers */
105681 int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
105682 ExprList *pChanges, /* Columns that change in an UPDATE statement */
105683 int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
105685 int mask = 0;
105686 Trigger *pList = 0;
105687 Trigger *p;
105689 if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
105690 pList = sqlite3TriggerList(pParse, pTab);
105692 assert( pList==0 || IsVirtual(pTab)==0 );
105693 for(p=pList; p; p=p->pNext){
105694 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
105695 mask |= p->tr_tm;
105698 if( pMask ){
105699 *pMask = mask;
105701 return (mask ? pList : 0);
105705 ** Convert the pStep->target token into a SrcList and return a pointer
105706 ** to that SrcList.
105708 ** This routine adds a specific database name, if needed, to the target when
105709 ** forming the SrcList. This prevents a trigger in one database from
105710 ** referring to a target in another database. An exception is when the
105711 ** trigger is in TEMP in which case it can refer to any other database it
105712 ** wants.
105714 static SrcList *targetSrcList(
105715 Parse *pParse, /* The parsing context */
105716 TriggerStep *pStep /* The trigger containing the target token */
105718 int iDb; /* Index of the database to use */
105719 SrcList *pSrc; /* SrcList to be returned */
105721 pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
105722 if( pSrc ){
105723 assert( pSrc->nSrc>0 );
105724 assert( pSrc->a!=0 );
105725 iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
105726 if( iDb==0 || iDb>=2 ){
105727 sqlite3 *db = pParse->db;
105728 assert( iDb<pParse->db->nDb );
105729 pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
105732 return pSrc;
105736 ** Generate VDBE code for the statements inside the body of a single
105737 ** trigger.
105739 static int codeTriggerProgram(
105740 Parse *pParse, /* The parser context */
105741 TriggerStep *pStepList, /* List of statements inside the trigger body */
105742 int orconf /* Conflict algorithm. (OE_Abort, etc) */
105744 TriggerStep *pStep;
105745 Vdbe *v = pParse->pVdbe;
105746 sqlite3 *db = pParse->db;
105748 assert( pParse->pTriggerTab && pParse->pToplevel );
105749 assert( pStepList );
105750 assert( v!=0 );
105751 for(pStep=pStepList; pStep; pStep=pStep->pNext){
105752 /* Figure out the ON CONFLICT policy that will be used for this step
105753 ** of the trigger program. If the statement that caused this trigger
105754 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
105755 ** the ON CONFLICT policy that was specified as part of the trigger
105756 ** step statement. Example:
105758 ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
105759 ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
105760 ** END;
105762 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
105763 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
105765 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
105767 /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
105768 ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
105769 ** that it is not safe to refactor constants (this happens after the
105770 ** start of the first loop in the SQL statement is coded - at that
105771 ** point code may be conditionally executed, so it is no longer safe to
105772 ** initialize constant register values). */
105773 assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
105774 pParse->cookieGoto = 0;
105776 switch( pStep->op ){
105777 case TK_UPDATE: {
105778 sqlite3Update(pParse,
105779 targetSrcList(pParse, pStep),
105780 sqlite3ExprListDup(db, pStep->pExprList, 0),
105781 sqlite3ExprDup(db, pStep->pWhere, 0),
105782 pParse->eOrconf
105784 break;
105786 case TK_INSERT: {
105787 sqlite3Insert(pParse,
105788 targetSrcList(pParse, pStep),
105789 sqlite3SelectDup(db, pStep->pSelect, 0),
105790 sqlite3IdListDup(db, pStep->pIdList),
105791 pParse->eOrconf
105793 break;
105795 case TK_DELETE: {
105796 sqlite3DeleteFrom(pParse,
105797 targetSrcList(pParse, pStep),
105798 sqlite3ExprDup(db, pStep->pWhere, 0)
105800 break;
105802 default: assert( pStep->op==TK_SELECT ); {
105803 SelectDest sDest;
105804 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
105805 sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
105806 sqlite3Select(pParse, pSelect, &sDest);
105807 sqlite3SelectDelete(db, pSelect);
105808 break;
105811 if( pStep->op!=TK_SELECT ){
105812 sqlite3VdbeAddOp0(v, OP_ResetCount);
105816 return 0;
105819 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
105821 ** This function is used to add VdbeComment() annotations to a VDBE
105822 ** program. It is not used in production code, only for debugging.
105824 static const char *onErrorText(int onError){
105825 switch( onError ){
105826 case OE_Abort: return "abort";
105827 case OE_Rollback: return "rollback";
105828 case OE_Fail: return "fail";
105829 case OE_Replace: return "replace";
105830 case OE_Ignore: return "ignore";
105831 case OE_Default: return "default";
105833 return "n/a";
105835 #endif
105838 ** Parse context structure pFrom has just been used to create a sub-vdbe
105839 ** (trigger program). If an error has occurred, transfer error information
105840 ** from pFrom to pTo.
105842 static void transferParseError(Parse *pTo, Parse *pFrom){
105843 assert( pFrom->zErrMsg==0 || pFrom->nErr );
105844 assert( pTo->zErrMsg==0 || pTo->nErr );
105845 if( pTo->nErr==0 ){
105846 pTo->zErrMsg = pFrom->zErrMsg;
105847 pTo->nErr = pFrom->nErr;
105848 }else{
105849 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
105854 ** Create and populate a new TriggerPrg object with a sub-program
105855 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
105857 static TriggerPrg *codeRowTrigger(
105858 Parse *pParse, /* Current parse context */
105859 Trigger *pTrigger, /* Trigger to code */
105860 Table *pTab, /* The table pTrigger is attached to */
105861 int orconf /* ON CONFLICT policy to code trigger program with */
105863 Parse *pTop = sqlite3ParseToplevel(pParse);
105864 sqlite3 *db = pParse->db; /* Database handle */
105865 TriggerPrg *pPrg; /* Value to return */
105866 Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
105867 Vdbe *v; /* Temporary VM */
105868 NameContext sNC; /* Name context for sub-vdbe */
105869 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
105870 Parse *pSubParse; /* Parse context for sub-vdbe */
105871 int iEndTrigger = 0; /* Label to jump to if WHEN is false */
105873 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
105874 assert( pTop->pVdbe );
105876 /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
105877 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
105878 ** list of the top-level Parse object sooner rather than later. */
105879 pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
105880 if( !pPrg ) return 0;
105881 pPrg->pNext = pTop->pTriggerPrg;
105882 pTop->pTriggerPrg = pPrg;
105883 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
105884 if( !pProgram ) return 0;
105885 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
105886 pPrg->pTrigger = pTrigger;
105887 pPrg->orconf = orconf;
105888 pPrg->aColmask[0] = 0xffffffff;
105889 pPrg->aColmask[1] = 0xffffffff;
105891 /* Allocate and populate a new Parse context to use for coding the
105892 ** trigger sub-program. */
105893 pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
105894 if( !pSubParse ) return 0;
105895 memset(&sNC, 0, sizeof(sNC));
105896 sNC.pParse = pSubParse;
105897 pSubParse->db = db;
105898 pSubParse->pTriggerTab = pTab;
105899 pSubParse->pToplevel = pTop;
105900 pSubParse->zAuthContext = pTrigger->zName;
105901 pSubParse->eTriggerOp = pTrigger->op;
105902 pSubParse->nQueryLoop = pParse->nQueryLoop;
105904 v = sqlite3GetVdbe(pSubParse);
105905 if( v ){
105906 VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
105907 pTrigger->zName, onErrorText(orconf),
105908 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
105909 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
105910 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
105911 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
105912 pTab->zName
105914 #ifndef SQLITE_OMIT_TRACE
105915 sqlite3VdbeChangeP4(v, -1,
105916 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
105918 #endif
105920 /* If one was specified, code the WHEN clause. If it evaluates to false
105921 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
105922 ** OP_Halt inserted at the end of the program. */
105923 if( pTrigger->pWhen ){
105924 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
105925 if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
105926 && db->mallocFailed==0
105928 iEndTrigger = sqlite3VdbeMakeLabel(v);
105929 sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
105931 sqlite3ExprDelete(db, pWhen);
105934 /* Code the trigger program into the sub-vdbe. */
105935 codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
105937 /* Insert an OP_Halt at the end of the sub-program. */
105938 if( iEndTrigger ){
105939 sqlite3VdbeResolveLabel(v, iEndTrigger);
105941 sqlite3VdbeAddOp0(v, OP_Halt);
105942 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
105944 transferParseError(pParse, pSubParse);
105945 if( db->mallocFailed==0 ){
105946 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
105948 pProgram->nMem = pSubParse->nMem;
105949 pProgram->nCsr = pSubParse->nTab;
105950 pProgram->nOnce = pSubParse->nOnce;
105951 pProgram->token = (void *)pTrigger;
105952 pPrg->aColmask[0] = pSubParse->oldmask;
105953 pPrg->aColmask[1] = pSubParse->newmask;
105954 sqlite3VdbeDelete(v);
105957 assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
105958 assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
105959 sqlite3ParserReset(pSubParse);
105960 sqlite3StackFree(db, pSubParse);
105962 return pPrg;
105966 ** Return a pointer to a TriggerPrg object containing the sub-program for
105967 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
105968 ** TriggerPrg object exists, a new object is allocated and populated before
105969 ** being returned.
105971 static TriggerPrg *getRowTrigger(
105972 Parse *pParse, /* Current parse context */
105973 Trigger *pTrigger, /* Trigger to code */
105974 Table *pTab, /* The table trigger pTrigger is attached to */
105975 int orconf /* ON CONFLICT algorithm. */
105977 Parse *pRoot = sqlite3ParseToplevel(pParse);
105978 TriggerPrg *pPrg;
105980 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
105982 /* It may be that this trigger has already been coded (or is in the
105983 ** process of being coded). If this is the case, then an entry with
105984 ** a matching TriggerPrg.pTrigger field will be present somewhere
105985 ** in the Parse.pTriggerPrg list. Search for such an entry. */
105986 for(pPrg=pRoot->pTriggerPrg;
105987 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
105988 pPrg=pPrg->pNext
105991 /* If an existing TriggerPrg could not be located, create a new one. */
105992 if( !pPrg ){
105993 pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
105996 return pPrg;
106000 ** Generate code for the trigger program associated with trigger p on
106001 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
106002 ** function are the same as those described in the header function for
106003 ** sqlite3CodeRowTrigger()
106005 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
106006 Parse *pParse, /* Parse context */
106007 Trigger *p, /* Trigger to code */
106008 Table *pTab, /* The table to code triggers from */
106009 int reg, /* Reg array containing OLD.* and NEW.* values */
106010 int orconf, /* ON CONFLICT policy */
106011 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
106013 Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
106014 TriggerPrg *pPrg;
106015 pPrg = getRowTrigger(pParse, p, pTab, orconf);
106016 assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
106018 /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
106019 ** is a pointer to the sub-vdbe containing the trigger program. */
106020 if( pPrg ){
106021 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
106023 sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
106024 sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
106025 VdbeComment(
106026 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
106028 /* Set the P5 operand of the OP_Program instruction to non-zero if
106029 ** recursive invocation of this trigger program is disallowed. Recursive
106030 ** invocation is disallowed if (a) the sub-program is really a trigger,
106031 ** not a foreign key action, and (b) the flag to enable recursive triggers
106032 ** is clear. */
106033 sqlite3VdbeChangeP5(v, (u8)bRecursive);
106038 ** This is called to code the required FOR EACH ROW triggers for an operation
106039 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
106040 ** is given by the op parameter. The tr_tm parameter determines whether the
106041 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
106042 ** parameter pChanges is passed the list of columns being modified.
106044 ** If there are no triggers that fire at the specified time for the specified
106045 ** operation on pTab, this function is a no-op.
106047 ** The reg argument is the address of the first in an array of registers
106048 ** that contain the values substituted for the new.* and old.* references
106049 ** in the trigger program. If N is the number of columns in table pTab
106050 ** (a copy of pTab->nCol), then registers are populated as follows:
106052 ** Register Contains
106053 ** ------------------------------------------------------
106054 ** reg+0 OLD.rowid
106055 ** reg+1 OLD.* value of left-most column of pTab
106056 ** ... ...
106057 ** reg+N OLD.* value of right-most column of pTab
106058 ** reg+N+1 NEW.rowid
106059 ** reg+N+2 OLD.* value of left-most column of pTab
106060 ** ... ...
106061 ** reg+N+N+1 NEW.* value of right-most column of pTab
106063 ** For ON DELETE triggers, the registers containing the NEW.* values will
106064 ** never be accessed by the trigger program, so they are not allocated or
106065 ** populated by the caller (there is no data to populate them with anyway).
106066 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
106067 ** are never accessed, and so are not allocated by the caller. So, for an
106068 ** ON INSERT trigger, the value passed to this function as parameter reg
106069 ** is not a readable register, although registers (reg+N) through
106070 ** (reg+N+N+1) are.
106072 ** Parameter orconf is the default conflict resolution algorithm for the
106073 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
106074 ** is the instruction that control should jump to if a trigger program
106075 ** raises an IGNORE exception.
106077 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
106078 Parse *pParse, /* Parse context */
106079 Trigger *pTrigger, /* List of triggers on table pTab */
106080 int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
106081 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
106082 int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
106083 Table *pTab, /* The table to code triggers from */
106084 int reg, /* The first in an array of registers (see above) */
106085 int orconf, /* ON CONFLICT policy */
106086 int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
106088 Trigger *p; /* Used to iterate through pTrigger list */
106090 assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
106091 assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
106092 assert( (op==TK_UPDATE)==(pChanges!=0) );
106094 for(p=pTrigger; p; p=p->pNext){
106096 /* Sanity checking: The schema for the trigger and for the table are
106097 ** always defined. The trigger must be in the same schema as the table
106098 ** or else it must be a TEMP trigger. */
106099 assert( p->pSchema!=0 );
106100 assert( p->pTabSchema!=0 );
106101 assert( p->pSchema==p->pTabSchema
106102 || p->pSchema==pParse->db->aDb[1].pSchema );
106104 /* Determine whether we should code this trigger */
106105 if( p->op==op
106106 && p->tr_tm==tr_tm
106107 && checkColumnOverlap(p->pColumns, pChanges)
106109 sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
106115 ** Triggers may access values stored in the old.* or new.* pseudo-table.
106116 ** This function returns a 32-bit bitmask indicating which columns of the
106117 ** old.* or new.* tables actually are used by triggers. This information
106118 ** may be used by the caller, for example, to avoid having to load the entire
106119 ** old.* record into memory when executing an UPDATE or DELETE command.
106121 ** Bit 0 of the returned mask is set if the left-most column of the
106122 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
106123 ** the second leftmost column value is required, and so on. If there
106124 ** are more than 32 columns in the table, and at least one of the columns
106125 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
106127 ** It is not possible to determine if the old.rowid or new.rowid column is
106128 ** accessed by triggers. The caller must always assume that it is.
106130 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
106131 ** applies to the old.* table. If 1, the new.* table.
106133 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
106134 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
106135 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
106136 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
106137 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
106139 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
106140 Parse *pParse, /* Parse context */
106141 Trigger *pTrigger, /* List of triggers on table pTab */
106142 ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
106143 int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
106144 int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
106145 Table *pTab, /* The table to code triggers from */
106146 int orconf /* Default ON CONFLICT policy for trigger steps */
106148 const int op = pChanges ? TK_UPDATE : TK_DELETE;
106149 u32 mask = 0;
106150 Trigger *p;
106152 assert( isNew==1 || isNew==0 );
106153 for(p=pTrigger; p; p=p->pNext){
106154 if( p->op==op && (tr_tm&p->tr_tm)
106155 && checkColumnOverlap(p->pColumns,pChanges)
106157 TriggerPrg *pPrg;
106158 pPrg = getRowTrigger(pParse, p, pTab, orconf);
106159 if( pPrg ){
106160 mask |= pPrg->aColmask[isNew];
106165 return mask;
106168 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
106170 /************** End of trigger.c *********************************************/
106171 /************** Begin file update.c ******************************************/
106173 ** 2001 September 15
106175 ** The author disclaims copyright to this source code. In place of
106176 ** a legal notice, here is a blessing:
106178 ** May you do good and not evil.
106179 ** May you find forgiveness for yourself and forgive others.
106180 ** May you share freely, never taking more than you give.
106182 *************************************************************************
106183 ** This file contains C code routines that are called by the parser
106184 ** to handle UPDATE statements.
106187 #ifndef SQLITE_OMIT_VIRTUALTABLE
106188 /* Forward declaration */
106189 static void updateVirtualTable(
106190 Parse *pParse, /* The parsing context */
106191 SrcList *pSrc, /* The virtual table to be modified */
106192 Table *pTab, /* The virtual table */
106193 ExprList *pChanges, /* The columns to change in the UPDATE statement */
106194 Expr *pRowidExpr, /* Expression used to recompute the rowid */
106195 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
106196 Expr *pWhere, /* WHERE clause of the UPDATE statement */
106197 int onError /* ON CONFLICT strategy */
106199 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106202 ** The most recently coded instruction was an OP_Column to retrieve the
106203 ** i-th column of table pTab. This routine sets the P4 parameter of the
106204 ** OP_Column to the default value, if any.
106206 ** The default value of a column is specified by a DEFAULT clause in the
106207 ** column definition. This was either supplied by the user when the table
106208 ** was created, or added later to the table definition by an ALTER TABLE
106209 ** command. If the latter, then the row-records in the table btree on disk
106210 ** may not contain a value for the column and the default value, taken
106211 ** from the P4 parameter of the OP_Column instruction, is returned instead.
106212 ** If the former, then all row-records are guaranteed to include a value
106213 ** for the column and the P4 value is not required.
106215 ** Column definitions created by an ALTER TABLE command may only have
106216 ** literal default values specified: a number, null or a string. (If a more
106217 ** complicated default expression value was provided, it is evaluated
106218 ** when the ALTER TABLE is executed and one of the literal values written
106219 ** into the sqlite_master table.)
106221 ** Therefore, the P4 parameter is only required if the default value for
106222 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
106223 ** function is capable of transforming these types of expressions into
106224 ** sqlite3_value objects.
106226 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
106227 ** on register iReg. This is used when an equivalent integer value is
106228 ** stored in place of an 8-byte floating point value in order to save
106229 ** space.
106231 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
106232 assert( pTab!=0 );
106233 if( !pTab->pSelect ){
106234 sqlite3_value *pValue = 0;
106235 u8 enc = ENC(sqlite3VdbeDb(v));
106236 Column *pCol = &pTab->aCol[i];
106237 VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
106238 assert( i<pTab->nCol );
106239 sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
106240 pCol->affinity, &pValue);
106241 if( pValue ){
106242 sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
106244 #ifndef SQLITE_OMIT_FLOATING_POINT
106245 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
106246 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
106248 #endif
106253 ** Process an UPDATE statement.
106255 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
106256 ** \_______/ \________/ \______/ \________________/
106257 * onError pTabList pChanges pWhere
106259 SQLITE_PRIVATE void sqlite3Update(
106260 Parse *pParse, /* The parser context */
106261 SrcList *pTabList, /* The table in which we should change things */
106262 ExprList *pChanges, /* Things to be changed */
106263 Expr *pWhere, /* The WHERE clause. May be null */
106264 int onError /* How to handle constraint errors */
106266 int i, j; /* Loop counters */
106267 Table *pTab; /* The table to be updated */
106268 int addrTop = 0; /* VDBE instruction address of the start of the loop */
106269 WhereInfo *pWInfo; /* Information about the WHERE clause */
106270 Vdbe *v; /* The virtual database engine */
106271 Index *pIdx; /* For looping over indices */
106272 Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
106273 int nIdx; /* Number of indices that need updating */
106274 int iBaseCur; /* Base cursor number */
106275 int iDataCur; /* Cursor for the canonical data btree */
106276 int iIdxCur; /* Cursor for the first index */
106277 sqlite3 *db; /* The database structure */
106278 int *aRegIdx = 0; /* One register assigned to each index to be updated */
106279 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
106280 ** an expression for the i-th column of the table.
106281 ** aXRef[i]==-1 if the i-th column is not changed. */
106282 u8 *aToOpen; /* 1 for tables and indices to be opened */
106283 u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
106284 u8 chngRowid; /* Rowid changed in a normal table */
106285 u8 chngKey; /* Either chngPk or chngRowid */
106286 Expr *pRowidExpr = 0; /* Expression defining the new record number */
106287 AuthContext sContext; /* The authorization context */
106288 NameContext sNC; /* The name-context to resolve expressions in */
106289 int iDb; /* Database containing the table being updated */
106290 int okOnePass; /* True for one-pass algorithm without the FIFO */
106291 int hasFK; /* True if foreign key processing is required */
106292 int labelBreak; /* Jump here to break out of UPDATE loop */
106293 int labelContinue; /* Jump here to continue next step of UPDATE loop */
106295 #ifndef SQLITE_OMIT_TRIGGER
106296 int isView; /* True when updating a view (INSTEAD OF trigger) */
106297 Trigger *pTrigger; /* List of triggers on pTab, if required */
106298 int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
106299 #endif
106300 int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
106301 int iEph = 0; /* Ephemeral table holding all primary key values */
106302 int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
106303 int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
106305 /* Register Allocations */
106306 int regRowCount = 0; /* A count of rows changed */
106307 int regOldRowid; /* The old rowid */
106308 int regNewRowid; /* The new rowid */
106309 int regNew; /* Content of the NEW.* table in triggers */
106310 int regOld = 0; /* Content of OLD.* table in triggers */
106311 int regRowSet = 0; /* Rowset of rows to be updated */
106312 int regKey = 0; /* composite PRIMARY KEY value */
106314 memset(&sContext, 0, sizeof(sContext));
106315 db = pParse->db;
106316 if( pParse->nErr || db->mallocFailed ){
106317 goto update_cleanup;
106319 assert( pTabList->nSrc==1 );
106321 /* Locate the table which we want to update.
106323 pTab = sqlite3SrcListLookup(pParse, pTabList);
106324 if( pTab==0 ) goto update_cleanup;
106325 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
106327 /* Figure out if we have any triggers and if the table being
106328 ** updated is a view.
106330 #ifndef SQLITE_OMIT_TRIGGER
106331 pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
106332 isView = pTab->pSelect!=0;
106333 assert( pTrigger || tmask==0 );
106334 #else
106335 # define pTrigger 0
106336 # define isView 0
106337 # define tmask 0
106338 #endif
106339 #ifdef SQLITE_OMIT_VIEW
106340 # undef isView
106341 # define isView 0
106342 #endif
106344 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
106345 goto update_cleanup;
106347 if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
106348 goto update_cleanup;
106351 /* Allocate a cursors for the main database table and for all indices.
106352 ** The index cursors might not be used, but if they are used they
106353 ** need to occur right after the database cursor. So go ahead and
106354 ** allocate enough space, just in case.
106356 pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
106357 iIdxCur = iDataCur+1;
106358 pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
106359 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
106360 if( pIdx->autoIndex==2 && pPk!=0 ){
106361 iDataCur = pParse->nTab;
106362 pTabList->a[0].iCursor = iDataCur;
106364 pParse->nTab++;
106367 /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
106368 ** Initialize aXRef[] and aToOpen[] to their default values.
106370 aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
106371 if( aXRef==0 ) goto update_cleanup;
106372 aRegIdx = aXRef+pTab->nCol;
106373 aToOpen = (u8*)(aRegIdx+nIdx);
106374 memset(aToOpen, 1, nIdx+1);
106375 aToOpen[nIdx+1] = 0;
106376 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
106378 /* Initialize the name-context */
106379 memset(&sNC, 0, sizeof(sNC));
106380 sNC.pParse = pParse;
106381 sNC.pSrcList = pTabList;
106383 /* Resolve the column names in all the expressions of the
106384 ** of the UPDATE statement. Also find the column index
106385 ** for each column to be updated in the pChanges array. For each
106386 ** column to be updated, make sure we have authorization to change
106387 ** that column.
106389 chngRowid = chngPk = 0;
106390 for(i=0; i<pChanges->nExpr; i++){
106391 if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
106392 goto update_cleanup;
106394 for(j=0; j<pTab->nCol; j++){
106395 if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
106396 if( j==pTab->iPKey ){
106397 chngRowid = 1;
106398 pRowidExpr = pChanges->a[i].pExpr;
106399 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
106400 chngPk = 1;
106402 aXRef[j] = i;
106403 break;
106406 if( j>=pTab->nCol ){
106407 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
106408 j = -1;
106409 chngRowid = 1;
106410 pRowidExpr = pChanges->a[i].pExpr;
106411 }else{
106412 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
106413 pParse->checkSchema = 1;
106414 goto update_cleanup;
106417 #ifndef SQLITE_OMIT_AUTHORIZATION
106419 int rc;
106420 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
106421 j<0 ? "ROWID" : pTab->aCol[j].zName,
106422 db->aDb[iDb].zName);
106423 if( rc==SQLITE_DENY ){
106424 goto update_cleanup;
106425 }else if( rc==SQLITE_IGNORE ){
106426 aXRef[j] = -1;
106429 #endif
106431 assert( (chngRowid & chngPk)==0 );
106432 assert( chngRowid==0 || chngRowid==1 );
106433 assert( chngPk==0 || chngPk==1 );
106434 chngKey = chngRowid + chngPk;
106436 /* The SET expressions are not actually used inside the WHERE loop.
106437 ** So reset the colUsed mask
106439 pTabList->a[0].colUsed = 0;
106441 hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
106443 /* There is one entry in the aRegIdx[] array for each index on the table
106444 ** being updated. Fill in aRegIdx[] with a register number that will hold
106445 ** the key for accessing each index.
106447 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
106448 int reg;
106449 if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
106450 reg = ++pParse->nMem;
106451 }else{
106452 reg = 0;
106453 for(i=0; i<pIdx->nKeyCol; i++){
106454 if( aXRef[pIdx->aiColumn[i]]>=0 ){
106455 reg = ++pParse->nMem;
106456 break;
106460 if( reg==0 ) aToOpen[j+1] = 0;
106461 aRegIdx[j] = reg;
106464 /* Begin generating code. */
106465 v = sqlite3GetVdbe(pParse);
106466 if( v==0 ) goto update_cleanup;
106467 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
106468 sqlite3BeginWriteOperation(pParse, 1, iDb);
106470 #ifndef SQLITE_OMIT_VIRTUALTABLE
106471 /* Virtual tables must be handled separately */
106472 if( IsVirtual(pTab) ){
106473 updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
106474 pWhere, onError);
106475 pWhere = 0;
106476 pTabList = 0;
106477 goto update_cleanup;
106479 #endif
106481 /* Allocate required registers. */
106482 regRowSet = ++pParse->nMem;
106483 regOldRowid = regNewRowid = ++pParse->nMem;
106484 if( chngPk || pTrigger || hasFK ){
106485 regOld = pParse->nMem + 1;
106486 pParse->nMem += pTab->nCol;
106488 if( chngKey || pTrigger || hasFK ){
106489 regNewRowid = ++pParse->nMem;
106491 regNew = pParse->nMem + 1;
106492 pParse->nMem += pTab->nCol;
106494 /* Start the view context. */
106495 if( isView ){
106496 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
106499 /* If we are trying to update a view, realize that view into
106500 ** a ephemeral table.
106502 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
106503 if( isView ){
106504 sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
106506 #endif
106508 /* Resolve the column names in all the expressions in the
106509 ** WHERE clause.
106511 if( sqlite3ResolveExprNames(&sNC, pWhere) ){
106512 goto update_cleanup;
106515 /* Begin the database scan
106517 if( HasRowid(pTab) ){
106518 sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
106519 pWInfo = sqlite3WhereBegin(
106520 pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
106522 if( pWInfo==0 ) goto update_cleanup;
106523 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
106525 /* Remember the rowid of every item to be updated.
106527 sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
106528 if( !okOnePass ){
106529 sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
106532 /* End the database scan loop.
106534 sqlite3WhereEnd(pWInfo);
106535 }else{
106536 int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
106537 i16 nPk; /* Number of components of the PRIMARY KEY */
106538 int addrOpen; /* Address of the OpenEphemeral instruction */
106540 assert( pPk!=0 );
106541 nPk = pPk->nKeyCol;
106542 iPk = pParse->nMem+1;
106543 pParse->nMem += nPk;
106544 regKey = ++pParse->nMem;
106545 iEph = pParse->nTab++;
106546 sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
106547 addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
106548 sqlite3VdbeSetP4KeyInfo(pParse, pPk);
106549 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
106550 WHERE_ONEPASS_DESIRED, iIdxCur);
106551 if( pWInfo==0 ) goto update_cleanup;
106552 okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
106553 for(i=0; i<nPk; i++){
106554 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
106555 iPk+i);
106557 if( okOnePass ){
106558 sqlite3VdbeChangeToNoop(v, addrOpen);
106559 nKey = nPk;
106560 regKey = iPk;
106561 }else{
106562 sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
106563 sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT);
106564 sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
106566 sqlite3WhereEnd(pWInfo);
106569 /* Initialize the count of updated rows
106571 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
106572 regRowCount = ++pParse->nMem;
106573 sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
106576 labelBreak = sqlite3VdbeMakeLabel(v);
106577 if( !isView ){
106579 ** Open every index that needs updating. Note that if any
106580 ** index could potentially invoke a REPLACE conflict resolution
106581 ** action, then we need to open all indices because we might need
106582 ** to be deleting some records.
106584 if( onError==OE_Replace ){
106585 memset(aToOpen, 1, nIdx+1);
106586 }else{
106587 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106588 if( pIdx->onError==OE_Replace ){
106589 memset(aToOpen, 1, nIdx+1);
106590 break;
106594 if( okOnePass ){
106595 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
106596 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
106598 sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
106599 0, 0);
106602 /* Top of the update loop */
106603 if( okOnePass ){
106604 if( aToOpen[iDataCur-iBaseCur] ){
106605 assert( pPk!=0 );
106606 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
106608 labelContinue = labelBreak;
106609 sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
106610 }else if( pPk ){
106611 labelContinue = sqlite3VdbeMakeLabel(v);
106612 sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak);
106613 addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
106614 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
106615 }else{
106616 labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
106617 regOldRowid);
106618 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
106621 /* If the record number will change, set register regNewRowid to
106622 ** contain the new value. If the record number is not being modified,
106623 ** then regNewRowid is the same register as regOldRowid, which is
106624 ** already populated. */
106625 assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
106626 if( chngRowid ){
106627 sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
106628 sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
106631 /* Compute the old pre-UPDATE content of the row being changed, if that
106632 ** information is needed */
106633 if( chngPk || hasFK || pTrigger ){
106634 u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
106635 oldmask |= sqlite3TriggerColmask(pParse,
106636 pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
106638 for(i=0; i<pTab->nCol; i++){
106639 if( oldmask==0xffffffff
106640 || (i<32 && (oldmask & MASKBIT32(i))!=0)
106641 || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
106643 testcase( oldmask!=0xffffffff && i==31 );
106644 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
106645 }else{
106646 sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
106649 if( chngRowid==0 && pPk==0 ){
106650 sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
106654 /* Populate the array of registers beginning at regNew with the new
106655 ** row data. This array is used to check constaints, create the new
106656 ** table and index records, and as the values for any new.* references
106657 ** made by triggers.
106659 ** If there are one or more BEFORE triggers, then do not populate the
106660 ** registers associated with columns that are (a) not modified by
106661 ** this UPDATE statement and (b) not accessed by new.* references. The
106662 ** values for registers not modified by the UPDATE must be reloaded from
106663 ** the database after the BEFORE triggers are fired anyway (as the trigger
106664 ** may have modified them). So not loading those that are not going to
106665 ** be used eliminates some redundant opcodes.
106667 newmask = sqlite3TriggerColmask(
106668 pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
106670 /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
106671 for(i=0; i<pTab->nCol; i++){
106672 if( i==pTab->iPKey ){
106673 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
106674 }else{
106675 j = aXRef[i];
106676 if( j>=0 ){
106677 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
106678 }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
106679 /* This branch loads the value of a column that will not be changed
106680 ** into a register. This is done if there are no BEFORE triggers, or
106681 ** if there are one or more BEFORE triggers that use this value via
106682 ** a new.* reference in a trigger program.
106684 testcase( i==31 );
106685 testcase( i==32 );
106686 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
106687 }else{
106688 sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
106693 /* Fire any BEFORE UPDATE triggers. This happens before constraints are
106694 ** verified. One could argue that this is wrong.
106696 if( tmask&TRIGGER_BEFORE ){
106697 sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
106698 sqlite3TableAffinityStr(v, pTab);
106699 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
106700 TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
106702 /* The row-trigger may have deleted the row being updated. In this
106703 ** case, jump to the next row. No updates or AFTER triggers are
106704 ** required. This behavior - what happens when the row being updated
106705 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
106706 ** documentation.
106708 if( pPk ){
106709 sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
106710 }else{
106711 sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
106714 /* If it did not delete it, the row-trigger may still have modified
106715 ** some of the columns of the row being updated. Load the values for
106716 ** all columns not modified by the update statement into their
106717 ** registers in case this has happened.
106719 for(i=0; i<pTab->nCol; i++){
106720 if( aXRef[i]<0 && i!=pTab->iPKey ){
106721 sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
106726 if( !isView ){
106727 int j1 = 0; /* Address of jump instruction */
106728 int bReplace = 0; /* True if REPLACE conflict resolution might happen */
106730 /* Do constraint checks. */
106731 assert( regOldRowid>0 );
106732 sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
106733 regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
106735 /* Do FK constraint checks. */
106736 if( hasFK ){
106737 sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
106740 /* Delete the index entries associated with the current record. */
106741 if( bReplace || chngKey ){
106742 if( pPk ){
106743 j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
106744 }else{
106745 j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
106748 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
106750 /* If changing the record number, delete the old record. */
106751 if( hasFK || chngKey || pPk!=0 ){
106752 sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
106754 if( bReplace || chngKey ){
106755 sqlite3VdbeJumpHere(v, j1);
106758 if( hasFK ){
106759 sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
106762 /* Insert the new index entries and the new record. */
106763 sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
106764 regNewRowid, aRegIdx, 1, 0, 0);
106766 /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
106767 ** handle rows (possibly in other tables) that refer via a foreign key
106768 ** to the row just updated. */
106769 if( hasFK ){
106770 sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
106774 /* Increment the row counter
106776 if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
106777 sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
106780 sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
106781 TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
106783 /* Repeat the above with the next record to be updated, until
106784 ** all record selected by the WHERE clause have been updated.
106786 if( okOnePass ){
106787 /* Nothing to do at end-of-loop for a single-pass */
106788 }else if( pPk ){
106789 sqlite3VdbeResolveLabel(v, labelContinue);
106790 sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop);
106791 }else{
106792 sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
106794 sqlite3VdbeResolveLabel(v, labelBreak);
106796 /* Close all tables */
106797 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
106798 assert( aRegIdx );
106799 if( aToOpen[i+1] ){
106800 sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
106803 if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
106805 /* Update the sqlite_sequence table by storing the content of the
106806 ** maximum rowid counter values recorded while inserting into
106807 ** autoincrement tables.
106809 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
106810 sqlite3AutoincrementEnd(pParse);
106814 ** Return the number of rows that were changed. If this routine is
106815 ** generating code because of a call to sqlite3NestedParse(), do not
106816 ** invoke the callback function.
106818 if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
106819 sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
106820 sqlite3VdbeSetNumCols(v, 1);
106821 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
106824 update_cleanup:
106825 sqlite3AuthContextPop(&sContext);
106826 sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
106827 sqlite3SrcListDelete(db, pTabList);
106828 sqlite3ExprListDelete(db, pChanges);
106829 sqlite3ExprDelete(db, pWhere);
106830 return;
106832 /* Make sure "isView" and other macros defined above are undefined. Otherwise
106833 ** thely may interfere with compilation of other functions in this file
106834 ** (or in another file, if this file becomes part of the amalgamation). */
106835 #ifdef isView
106836 #undef isView
106837 #endif
106838 #ifdef pTrigger
106839 #undef pTrigger
106840 #endif
106842 #ifndef SQLITE_OMIT_VIRTUALTABLE
106844 ** Generate code for an UPDATE of a virtual table.
106846 ** The strategy is that we create an ephemerial table that contains
106847 ** for each row to be changed:
106849 ** (A) The original rowid of that row.
106850 ** (B) The revised rowid for the row. (note1)
106851 ** (C) The content of every column in the row.
106853 ** Then we loop over this ephemeral table and for each row in
106854 ** the ephermeral table call VUpdate.
106856 ** When finished, drop the ephemeral table.
106858 ** (note1) Actually, if we know in advance that (A) is always the same
106859 ** as (B) we only store (A), then duplicate (A) when pulling
106860 ** it out of the ephemeral table before calling VUpdate.
106862 static void updateVirtualTable(
106863 Parse *pParse, /* The parsing context */
106864 SrcList *pSrc, /* The virtual table to be modified */
106865 Table *pTab, /* The virtual table */
106866 ExprList *pChanges, /* The columns to change in the UPDATE statement */
106867 Expr *pRowid, /* Expression used to recompute the rowid */
106868 int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
106869 Expr *pWhere, /* WHERE clause of the UPDATE statement */
106870 int onError /* ON CONFLICT strategy */
106872 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
106873 ExprList *pEList = 0; /* The result set of the SELECT statement */
106874 Select *pSelect = 0; /* The SELECT statement */
106875 Expr *pExpr; /* Temporary expression */
106876 int ephemTab; /* Table holding the result of the SELECT */
106877 int i; /* Loop counter */
106878 int addr; /* Address of top of loop */
106879 int iReg; /* First register in set passed to OP_VUpdate */
106880 sqlite3 *db = pParse->db; /* Database connection */
106881 const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
106882 SelectDest dest;
106884 /* Construct the SELECT statement that will find the new values for
106885 ** all updated rows.
106887 pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
106888 if( pRowid ){
106889 pEList = sqlite3ExprListAppend(pParse, pEList,
106890 sqlite3ExprDup(db, pRowid, 0));
106892 assert( pTab->iPKey<0 );
106893 for(i=0; i<pTab->nCol; i++){
106894 if( aXRef[i]>=0 ){
106895 pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
106896 }else{
106897 pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
106899 pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
106901 pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
106903 /* Create the ephemeral table into which the update results will
106904 ** be stored.
106906 assert( v );
106907 ephemTab = pParse->nTab++;
106908 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
106909 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
106911 /* fill the ephemeral table
106913 sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
106914 sqlite3Select(pParse, pSelect, &dest);
106916 /* Generate code to scan the ephemeral table and call VUpdate. */
106917 iReg = ++pParse->nMem;
106918 pParse->nMem += pTab->nCol+1;
106919 addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
106920 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
106921 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
106922 for(i=0; i<pTab->nCol; i++){
106923 sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
106925 sqlite3VtabMakeWritable(pParse, pTab);
106926 sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
106927 sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
106928 sqlite3MayAbort(pParse);
106929 sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
106930 sqlite3VdbeJumpHere(v, addr);
106931 sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
106933 /* Cleanup */
106934 sqlite3SelectDelete(db, pSelect);
106936 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106938 /************** End of update.c **********************************************/
106939 /************** Begin file vacuum.c ******************************************/
106941 ** 2003 April 6
106943 ** The author disclaims copyright to this source code. In place of
106944 ** a legal notice, here is a blessing:
106946 ** May you do good and not evil.
106947 ** May you find forgiveness for yourself and forgive others.
106948 ** May you share freely, never taking more than you give.
106950 *************************************************************************
106951 ** This file contains code used to implement the VACUUM command.
106953 ** Most of the code in this file may be omitted by defining the
106954 ** SQLITE_OMIT_VACUUM macro.
106957 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
106959 ** Finalize a prepared statement. If there was an error, store the
106960 ** text of the error message in *pzErrMsg. Return the result code.
106962 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
106963 int rc;
106964 rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
106965 if( rc ){
106966 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
106968 return rc;
106972 ** Execute zSql on database db. Return an error code.
106974 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
106975 sqlite3_stmt *pStmt;
106976 VVA_ONLY( int rc; )
106977 if( !zSql ){
106978 return SQLITE_NOMEM;
106980 if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
106981 sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
106982 return sqlite3_errcode(db);
106984 VVA_ONLY( rc = ) sqlite3_step(pStmt);
106985 assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
106986 return vacuumFinalize(db, pStmt, pzErrMsg);
106990 ** Execute zSql on database db. The statement returns exactly
106991 ** one column. Execute this as SQL on the same database.
106993 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
106994 sqlite3_stmt *pStmt;
106995 int rc;
106997 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
106998 if( rc!=SQLITE_OK ) return rc;
107000 while( SQLITE_ROW==sqlite3_step(pStmt) ){
107001 rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
107002 if( rc!=SQLITE_OK ){
107003 vacuumFinalize(db, pStmt, pzErrMsg);
107004 return rc;
107008 return vacuumFinalize(db, pStmt, pzErrMsg);
107012 ** The VACUUM command is used to clean up the database,
107013 ** collapse free space, etc. It is modelled after the VACUUM command
107014 ** in PostgreSQL. The VACUUM command works as follows:
107016 ** (1) Create a new transient database file
107017 ** (2) Copy all content from the database being vacuumed into
107018 ** the new transient database file
107019 ** (3) Copy content from the transient database back into the
107020 ** original database.
107022 ** The transient database requires temporary disk space approximately
107023 ** equal to the size of the original database. The copy operation of
107024 ** step (3) requires additional temporary disk space approximately equal
107025 ** to the size of the original database for the rollback journal.
107026 ** Hence, temporary disk space that is approximately 2x the size of the
107027 ** orginal database is required. Every page of the database is written
107028 ** approximately 3 times: Once for step (2) and twice for step (3).
107029 ** Two writes per page are required in step (3) because the original
107030 ** database content must be written into the rollback journal prior to
107031 ** overwriting the database with the vacuumed content.
107033 ** Only 1x temporary space and only 1x writes would be required if
107034 ** the copy of step (3) were replace by deleting the original database
107035 ** and renaming the transient database as the original. But that will
107036 ** not work if other processes are attached to the original database.
107037 ** And a power loss in between deleting the original and renaming the
107038 ** transient would cause the database file to appear to be deleted
107039 ** following reboot.
107041 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
107042 Vdbe *v = sqlite3GetVdbe(pParse);
107043 if( v ){
107044 sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
107045 sqlite3VdbeUsesBtree(v, 0);
107047 return;
107051 ** This routine implements the OP_Vacuum opcode of the VDBE.
107053 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
107054 int rc = SQLITE_OK; /* Return code from service routines */
107055 Btree *pMain; /* The database being vacuumed */
107056 Btree *pTemp; /* The temporary database we vacuum into */
107057 char *zSql = 0; /* SQL statements */
107058 int saved_flags; /* Saved value of the db->flags */
107059 int saved_nChange; /* Saved value of db->nChange */
107060 int saved_nTotalChange; /* Saved value of db->nTotalChange */
107061 void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
107062 Db *pDb = 0; /* Database to detach at end of vacuum */
107063 int isMemDb; /* True if vacuuming a :memory: database */
107064 int nRes; /* Bytes of reserved space at the end of each page */
107065 int nDb; /* Number of attached databases */
107067 if( !db->autoCommit ){
107068 sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
107069 return SQLITE_ERROR;
107071 if( db->nVdbeActive>1 ){
107072 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
107073 return SQLITE_ERROR;
107076 /* Save the current value of the database flags so that it can be
107077 ** restored before returning. Then set the writable-schema flag, and
107078 ** disable CHECK and foreign key constraints. */
107079 saved_flags = db->flags;
107080 saved_nChange = db->nChange;
107081 saved_nTotalChange = db->nTotalChange;
107082 saved_xTrace = db->xTrace;
107083 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
107084 db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
107085 db->xTrace = 0;
107087 pMain = db->aDb[0].pBt;
107088 isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
107090 /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
107091 ** can be set to 'off' for this file, as it is not recovered if a crash
107092 ** occurs anyway. The integrity of the database is maintained by a
107093 ** (possibly synchronous) transaction opened on the main database before
107094 ** sqlite3BtreeCopyFile() is called.
107096 ** An optimisation would be to use a non-journaled pager.
107097 ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
107098 ** that actually made the VACUUM run slower. Very little journalling
107099 ** actually occurs when doing a vacuum since the vacuum_db is initially
107100 ** empty. Only the journal header is written. Apparently it takes more
107101 ** time to parse and run the PRAGMA to turn journalling off than it does
107102 ** to write the journal header file.
107104 nDb = db->nDb;
107105 if( sqlite3TempInMemory(db) ){
107106 zSql = "ATTACH ':memory:' AS vacuum_db;";
107107 }else{
107108 zSql = "ATTACH '' AS vacuum_db;";
107110 rc = execSql(db, pzErrMsg, zSql);
107111 if( db->nDb>nDb ){
107112 pDb = &db->aDb[db->nDb-1];
107113 assert( strcmp(pDb->zName,"vacuum_db")==0 );
107115 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107116 pTemp = db->aDb[db->nDb-1].pBt;
107118 /* The call to execSql() to attach the temp database has left the file
107119 ** locked (as there was more than one active statement when the transaction
107120 ** to read the schema was concluded. Unlock it here so that this doesn't
107121 ** cause problems for the call to BtreeSetPageSize() below. */
107122 sqlite3BtreeCommit(pTemp);
107124 nRes = sqlite3BtreeGetReserve(pMain);
107126 /* A VACUUM cannot change the pagesize of an encrypted database. */
107127 #ifdef SQLITE_HAS_CODEC
107128 if( db->nextPagesize ){
107129 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
107130 int nKey;
107131 char *zKey;
107132 sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
107133 if( nKey ) db->nextPagesize = 0;
107135 #endif
107137 rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
107138 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107140 /* Begin a transaction and take an exclusive lock on the main database
107141 ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
107142 ** to ensure that we do not try to change the page-size on a WAL database.
107144 rc = execSql(db, pzErrMsg, "BEGIN;");
107145 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107146 rc = sqlite3BtreeBeginTrans(pMain, 2);
107147 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107149 /* Do not attempt to change the page size for a WAL database */
107150 if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
107151 ==PAGER_JOURNALMODE_WAL ){
107152 db->nextPagesize = 0;
107155 if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
107156 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
107157 || NEVER(db->mallocFailed)
107159 rc = SQLITE_NOMEM;
107160 goto end_of_vacuum;
107163 #ifndef SQLITE_OMIT_AUTOVACUUM
107164 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
107165 sqlite3BtreeGetAutoVacuum(pMain));
107166 #endif
107168 /* Query the schema of the main database. Create a mirror schema
107169 ** in the temporary database.
107171 rc = execExecSql(db, pzErrMsg,
107172 "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
107173 " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
107174 " AND coalesce(rootpage,1)>0"
107176 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107177 rc = execExecSql(db, pzErrMsg,
107178 "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
107179 " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
107180 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107181 rc = execExecSql(db, pzErrMsg,
107182 "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
107183 " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
107184 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107186 /* Loop through the tables in the main database. For each, do
107187 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
107188 ** the contents to the temporary database.
107190 rc = execExecSql(db, pzErrMsg,
107191 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
107192 "|| ' SELECT * FROM main.' || quote(name) || ';'"
107193 "FROM main.sqlite_master "
107194 "WHERE type = 'table' AND name!='sqlite_sequence' "
107195 " AND coalesce(rootpage,1)>0"
107197 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107199 /* Copy over the sequence table
107201 rc = execExecSql(db, pzErrMsg,
107202 "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
107203 "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
107205 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107206 rc = execExecSql(db, pzErrMsg,
107207 "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
107208 "|| ' SELECT * FROM main.' || quote(name) || ';' "
107209 "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
107211 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107214 /* Copy the triggers, views, and virtual tables from the main database
107215 ** over to the temporary database. None of these objects has any
107216 ** associated storage, so all we have to do is copy their entries
107217 ** from the SQLITE_MASTER table.
107219 rc = execSql(db, pzErrMsg,
107220 "INSERT INTO vacuum_db.sqlite_master "
107221 " SELECT type, name, tbl_name, rootpage, sql"
107222 " FROM main.sqlite_master"
107223 " WHERE type='view' OR type='trigger'"
107224 " OR (type='table' AND rootpage=0)"
107226 if( rc ) goto end_of_vacuum;
107228 /* At this point, there is a write transaction open on both the
107229 ** vacuum database and the main database. Assuming no error occurs,
107230 ** both transactions are closed by this block - the main database
107231 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
107232 ** call to sqlite3BtreeCommit().
107235 u32 meta;
107236 int i;
107238 /* This array determines which meta meta values are preserved in the
107239 ** vacuum. Even entries are the meta value number and odd entries
107240 ** are an increment to apply to the meta value after the vacuum.
107241 ** The increment is used to increase the schema cookie so that other
107242 ** connections to the same database will know to reread the schema.
107244 static const unsigned char aCopy[] = {
107245 BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
107246 BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
107247 BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
107248 BTREE_USER_VERSION, 0, /* Preserve the user version */
107249 BTREE_APPLICATION_ID, 0, /* Preserve the application id */
107252 assert( 1==sqlite3BtreeIsInTrans(pTemp) );
107253 assert( 1==sqlite3BtreeIsInTrans(pMain) );
107255 /* Copy Btree meta values */
107256 for(i=0; i<ArraySize(aCopy); i+=2){
107257 /* GetMeta() and UpdateMeta() cannot fail in this context because
107258 ** we already have page 1 loaded into cache and marked dirty. */
107259 sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
107260 rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
107261 if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
107264 rc = sqlite3BtreeCopyFile(pMain, pTemp);
107265 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107266 rc = sqlite3BtreeCommit(pTemp);
107267 if( rc!=SQLITE_OK ) goto end_of_vacuum;
107268 #ifndef SQLITE_OMIT_AUTOVACUUM
107269 sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
107270 #endif
107273 assert( rc==SQLITE_OK );
107274 rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
107276 end_of_vacuum:
107277 /* Restore the original value of db->flags */
107278 db->flags = saved_flags;
107279 db->nChange = saved_nChange;
107280 db->nTotalChange = saved_nTotalChange;
107281 db->xTrace = saved_xTrace;
107282 sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
107284 /* Currently there is an SQL level transaction open on the vacuum
107285 ** database. No locks are held on any other files (since the main file
107286 ** was committed at the btree level). So it safe to end the transaction
107287 ** by manually setting the autoCommit flag to true and detaching the
107288 ** vacuum database. The vacuum_db journal file is deleted when the pager
107289 ** is closed by the DETACH.
107291 db->autoCommit = 1;
107293 if( pDb ){
107294 sqlite3BtreeClose(pDb->pBt);
107295 pDb->pBt = 0;
107296 pDb->pSchema = 0;
107299 /* This both clears the schemas and reduces the size of the db->aDb[]
107300 ** array. */
107301 sqlite3ResetAllSchemasOfConnection(db);
107303 return rc;
107306 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
107308 /************** End of vacuum.c **********************************************/
107309 /************** Begin file vtab.c ********************************************/
107311 ** 2006 June 10
107313 ** The author disclaims copyright to this source code. In place of
107314 ** a legal notice, here is a blessing:
107316 ** May you do good and not evil.
107317 ** May you find forgiveness for yourself and forgive others.
107318 ** May you share freely, never taking more than you give.
107320 *************************************************************************
107321 ** This file contains code used to help implement virtual tables.
107323 #ifndef SQLITE_OMIT_VIRTUALTABLE
107326 ** Before a virtual table xCreate() or xConnect() method is invoked, the
107327 ** sqlite3.pVtabCtx member variable is set to point to an instance of
107328 ** this struct allocated on the stack. It is used by the implementation of
107329 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
107330 ** are invoked only from within xCreate and xConnect methods.
107332 struct VtabCtx {
107333 VTable *pVTable; /* The virtual table being constructed */
107334 Table *pTab; /* The Table object to which the virtual table belongs */
107338 ** The actual function that does the work of creating a new module.
107339 ** This function implements the sqlite3_create_module() and
107340 ** sqlite3_create_module_v2() interfaces.
107342 static int createModule(
107343 sqlite3 *db, /* Database in which module is registered */
107344 const char *zName, /* Name assigned to this module */
107345 const sqlite3_module *pModule, /* The definition of the module */
107346 void *pAux, /* Context pointer for xCreate/xConnect */
107347 void (*xDestroy)(void *) /* Module destructor function */
107349 int rc = SQLITE_OK;
107350 int nName;
107352 sqlite3_mutex_enter(db->mutex);
107353 nName = sqlite3Strlen30(zName);
107354 if( sqlite3HashFind(&db->aModule, zName, nName) ){
107355 rc = SQLITE_MISUSE_BKPT;
107356 }else{
107357 Module *pMod;
107358 pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
107359 if( pMod ){
107360 Module *pDel;
107361 char *zCopy = (char *)(&pMod[1]);
107362 memcpy(zCopy, zName, nName+1);
107363 pMod->zName = zCopy;
107364 pMod->pModule = pModule;
107365 pMod->pAux = pAux;
107366 pMod->xDestroy = xDestroy;
107367 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
107368 assert( pDel==0 || pDel==pMod );
107369 if( pDel ){
107370 db->mallocFailed = 1;
107371 sqlite3DbFree(db, pDel);
107375 rc = sqlite3ApiExit(db, rc);
107376 if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
107378 sqlite3_mutex_leave(db->mutex);
107379 return rc;
107384 ** External API function used to create a new virtual-table module.
107386 SQLITE_API int sqlite3_create_module(
107387 sqlite3 *db, /* Database in which module is registered */
107388 const char *zName, /* Name assigned to this module */
107389 const sqlite3_module *pModule, /* The definition of the module */
107390 void *pAux /* Context pointer for xCreate/xConnect */
107392 return createModule(db, zName, pModule, pAux, 0);
107396 ** External API function used to create a new virtual-table module.
107398 SQLITE_API int sqlite3_create_module_v2(
107399 sqlite3 *db, /* Database in which module is registered */
107400 const char *zName, /* Name assigned to this module */
107401 const sqlite3_module *pModule, /* The definition of the module */
107402 void *pAux, /* Context pointer for xCreate/xConnect */
107403 void (*xDestroy)(void *) /* Module destructor function */
107405 return createModule(db, zName, pModule, pAux, xDestroy);
107409 ** Lock the virtual table so that it cannot be disconnected.
107410 ** Locks nest. Every lock should have a corresponding unlock.
107411 ** If an unlock is omitted, resources leaks will occur.
107413 ** If a disconnect is attempted while a virtual table is locked,
107414 ** the disconnect is deferred until all locks have been removed.
107416 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
107417 pVTab->nRef++;
107422 ** pTab is a pointer to a Table structure representing a virtual-table.
107423 ** Return a pointer to the VTable object used by connection db to access
107424 ** this virtual-table, if one has been created, or NULL otherwise.
107426 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
107427 VTable *pVtab;
107428 assert( IsVirtual(pTab) );
107429 for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
107430 return pVtab;
107434 ** Decrement the ref-count on a virtual table object. When the ref-count
107435 ** reaches zero, call the xDisconnect() method to delete the object.
107437 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
107438 sqlite3 *db = pVTab->db;
107440 assert( db );
107441 assert( pVTab->nRef>0 );
107442 assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
107444 pVTab->nRef--;
107445 if( pVTab->nRef==0 ){
107446 sqlite3_vtab *p = pVTab->pVtab;
107447 if( p ){
107448 p->pModule->xDisconnect(p);
107450 sqlite3DbFree(db, pVTab);
107455 ** Table p is a virtual table. This function moves all elements in the
107456 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
107457 ** database connections to be disconnected at the next opportunity.
107458 ** Except, if argument db is not NULL, then the entry associated with
107459 ** connection db is left in the p->pVTable list.
107461 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
107462 VTable *pRet = 0;
107463 VTable *pVTable = p->pVTable;
107464 p->pVTable = 0;
107466 /* Assert that the mutex (if any) associated with the BtShared database
107467 ** that contains table p is held by the caller. See header comments
107468 ** above function sqlite3VtabUnlockList() for an explanation of why
107469 ** this makes it safe to access the sqlite3.pDisconnect list of any
107470 ** database connection that may have an entry in the p->pVTable list.
107472 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
107474 while( pVTable ){
107475 sqlite3 *db2 = pVTable->db;
107476 VTable *pNext = pVTable->pNext;
107477 assert( db2 );
107478 if( db2==db ){
107479 pRet = pVTable;
107480 p->pVTable = pRet;
107481 pRet->pNext = 0;
107482 }else{
107483 pVTable->pNext = db2->pDisconnect;
107484 db2->pDisconnect = pVTable;
107486 pVTable = pNext;
107489 assert( !db || pRet );
107490 return pRet;
107494 ** Table *p is a virtual table. This function removes the VTable object
107495 ** for table *p associated with database connection db from the linked
107496 ** list in p->pVTab. It also decrements the VTable ref count. This is
107497 ** used when closing database connection db to free all of its VTable
107498 ** objects without disturbing the rest of the Schema object (which may
107499 ** be being used by other shared-cache connections).
107501 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
107502 VTable **ppVTab;
107504 assert( IsVirtual(p) );
107505 assert( sqlite3BtreeHoldsAllMutexes(db) );
107506 assert( sqlite3_mutex_held(db->mutex) );
107508 for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
107509 if( (*ppVTab)->db==db ){
107510 VTable *pVTab = *ppVTab;
107511 *ppVTab = pVTab->pNext;
107512 sqlite3VtabUnlock(pVTab);
107513 break;
107520 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
107522 ** This function may only be called when the mutexes associated with all
107523 ** shared b-tree databases opened using connection db are held by the
107524 ** caller. This is done to protect the sqlite3.pDisconnect list. The
107525 ** sqlite3.pDisconnect list is accessed only as follows:
107527 ** 1) By this function. In this case, all BtShared mutexes and the mutex
107528 ** associated with the database handle itself must be held.
107530 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
107531 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
107532 ** associated with the database the virtual table is stored in is held
107533 ** or, if the virtual table is stored in a non-sharable database, then
107534 ** the database handle mutex is held.
107536 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
107537 ** by multiple threads. It is thread-safe.
107539 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
107540 VTable *p = db->pDisconnect;
107541 db->pDisconnect = 0;
107543 assert( sqlite3BtreeHoldsAllMutexes(db) );
107544 assert( sqlite3_mutex_held(db->mutex) );
107546 if( p ){
107547 sqlite3ExpirePreparedStatements(db);
107549 VTable *pNext = p->pNext;
107550 sqlite3VtabUnlock(p);
107551 p = pNext;
107552 }while( p );
107557 ** Clear any and all virtual-table information from the Table record.
107558 ** This routine is called, for example, just before deleting the Table
107559 ** record.
107561 ** Since it is a virtual-table, the Table structure contains a pointer
107562 ** to the head of a linked list of VTable structures. Each VTable
107563 ** structure is associated with a single sqlite3* user of the schema.
107564 ** The reference count of the VTable structure associated with database
107565 ** connection db is decremented immediately (which may lead to the
107566 ** structure being xDisconnected and free). Any other VTable structures
107567 ** in the list are moved to the sqlite3.pDisconnect list of the associated
107568 ** database connection.
107570 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
107571 if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
107572 if( p->azModuleArg ){
107573 int i;
107574 for(i=0; i<p->nModuleArg; i++){
107575 if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
107577 sqlite3DbFree(db, p->azModuleArg);
107582 ** Add a new module argument to pTable->azModuleArg[].
107583 ** The string is not copied - the pointer is stored. The
107584 ** string will be freed automatically when the table is
107585 ** deleted.
107587 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
107588 int i = pTable->nModuleArg++;
107589 int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
107590 char **azModuleArg;
107591 azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
107592 if( azModuleArg==0 ){
107593 int j;
107594 for(j=0; j<i; j++){
107595 sqlite3DbFree(db, pTable->azModuleArg[j]);
107597 sqlite3DbFree(db, zArg);
107598 sqlite3DbFree(db, pTable->azModuleArg);
107599 pTable->nModuleArg = 0;
107600 }else{
107601 azModuleArg[i] = zArg;
107602 azModuleArg[i+1] = 0;
107604 pTable->azModuleArg = azModuleArg;
107608 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
107609 ** statement. The module name has been parsed, but the optional list
107610 ** of parameters that follow the module name are still pending.
107612 SQLITE_PRIVATE void sqlite3VtabBeginParse(
107613 Parse *pParse, /* Parsing context */
107614 Token *pName1, /* Name of new table, or database name */
107615 Token *pName2, /* Name of new table or NULL */
107616 Token *pModuleName, /* Name of the module for the virtual table */
107617 int ifNotExists /* No error if the table already exists */
107619 int iDb; /* The database the table is being created in */
107620 Table *pTable; /* The new virtual table */
107621 sqlite3 *db; /* Database connection */
107623 sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
107624 pTable = pParse->pNewTable;
107625 if( pTable==0 ) return;
107626 assert( 0==pTable->pIndex );
107628 db = pParse->db;
107629 iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
107630 assert( iDb>=0 );
107632 pTable->tabFlags |= TF_Virtual;
107633 pTable->nModuleArg = 0;
107634 addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
107635 addModuleArgument(db, pTable, 0);
107636 addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
107637 pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
107639 #ifndef SQLITE_OMIT_AUTHORIZATION
107640 /* Creating a virtual table invokes the authorization callback twice.
107641 ** The first invocation, to obtain permission to INSERT a row into the
107642 ** sqlite_master table, has already been made by sqlite3StartTable().
107643 ** The second call, to obtain permission to create the table, is made now.
107645 if( pTable->azModuleArg ){
107646 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
107647 pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
107649 #endif
107653 ** This routine takes the module argument that has been accumulating
107654 ** in pParse->zArg[] and appends it to the list of arguments on the
107655 ** virtual table currently under construction in pParse->pTable.
107657 static void addArgumentToVtab(Parse *pParse){
107658 if( pParse->sArg.z && pParse->pNewTable ){
107659 const char *z = (const char*)pParse->sArg.z;
107660 int n = pParse->sArg.n;
107661 sqlite3 *db = pParse->db;
107662 addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
107667 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
107668 ** has been completely parsed.
107670 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
107671 Table *pTab = pParse->pNewTable; /* The table being constructed */
107672 sqlite3 *db = pParse->db; /* The database connection */
107674 if( pTab==0 ) return;
107675 addArgumentToVtab(pParse);
107676 pParse->sArg.z = 0;
107677 if( pTab->nModuleArg<1 ) return;
107679 /* If the CREATE VIRTUAL TABLE statement is being entered for the
107680 ** first time (in other words if the virtual table is actually being
107681 ** created now instead of just being read out of sqlite_master) then
107682 ** do additional initialization work and store the statement text
107683 ** in the sqlite_master table.
107685 if( !db->init.busy ){
107686 char *zStmt;
107687 char *zWhere;
107688 int iDb;
107689 Vdbe *v;
107691 /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
107692 if( pEnd ){
107693 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
107695 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
107697 /* A slot for the record has already been allocated in the
107698 ** SQLITE_MASTER table. We just need to update that slot with all
107699 ** the information we've collected.
107701 ** The VM register number pParse->regRowid holds the rowid of an
107702 ** entry in the sqlite_master table tht was created for this vtab
107703 ** by sqlite3StartTable().
107705 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107706 sqlite3NestedParse(pParse,
107707 "UPDATE %Q.%s "
107708 "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
107709 "WHERE rowid=#%d",
107710 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
107711 pTab->zName,
107712 pTab->zName,
107713 zStmt,
107714 pParse->regRowid
107716 sqlite3DbFree(db, zStmt);
107717 v = sqlite3GetVdbe(pParse);
107718 sqlite3ChangeCookie(pParse, iDb);
107720 sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
107721 zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
107722 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
107723 sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
107724 pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
107727 /* If we are rereading the sqlite_master table create the in-memory
107728 ** record of the table. The xConnect() method is not called until
107729 ** the first time the virtual table is used in an SQL statement. This
107730 ** allows a schema that contains virtual tables to be loaded before
107731 ** the required virtual table implementations are registered. */
107732 else {
107733 Table *pOld;
107734 Schema *pSchema = pTab->pSchema;
107735 const char *zName = pTab->zName;
107736 int nName = sqlite3Strlen30(zName);
107737 assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
107738 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
107739 if( pOld ){
107740 db->mallocFailed = 1;
107741 assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
107742 return;
107744 pParse->pNewTable = 0;
107749 ** The parser calls this routine when it sees the first token
107750 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
107752 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
107753 addArgumentToVtab(pParse);
107754 pParse->sArg.z = 0;
107755 pParse->sArg.n = 0;
107759 ** The parser calls this routine for each token after the first token
107760 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
107762 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
107763 Token *pArg = &pParse->sArg;
107764 if( pArg->z==0 ){
107765 pArg->z = p->z;
107766 pArg->n = p->n;
107767 }else{
107768 assert(pArg->z < p->z);
107769 pArg->n = (int)(&p->z[p->n] - pArg->z);
107774 ** Invoke a virtual table constructor (either xCreate or xConnect). The
107775 ** pointer to the function to invoke is passed as the fourth parameter
107776 ** to this procedure.
107778 static int vtabCallConstructor(
107779 sqlite3 *db,
107780 Table *pTab,
107781 Module *pMod,
107782 int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
107783 char **pzErr
107785 VtabCtx sCtx, *pPriorCtx;
107786 VTable *pVTable;
107787 int rc;
107788 const char *const*azArg = (const char *const*)pTab->azModuleArg;
107789 int nArg = pTab->nModuleArg;
107790 char *zErr = 0;
107791 char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
107792 int iDb;
107794 if( !zModuleName ){
107795 return SQLITE_NOMEM;
107798 pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
107799 if( !pVTable ){
107800 sqlite3DbFree(db, zModuleName);
107801 return SQLITE_NOMEM;
107803 pVTable->db = db;
107804 pVTable->pMod = pMod;
107806 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107807 pTab->azModuleArg[1] = db->aDb[iDb].zName;
107809 /* Invoke the virtual table constructor */
107810 assert( &db->pVtabCtx );
107811 assert( xConstruct );
107812 sCtx.pTab = pTab;
107813 sCtx.pVTable = pVTable;
107814 pPriorCtx = db->pVtabCtx;
107815 db->pVtabCtx = &sCtx;
107816 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
107817 db->pVtabCtx = pPriorCtx;
107818 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
107820 if( SQLITE_OK!=rc ){
107821 if( zErr==0 ){
107822 *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
107823 }else {
107824 *pzErr = sqlite3MPrintf(db, "%s", zErr);
107825 sqlite3_free(zErr);
107827 sqlite3DbFree(db, pVTable);
107828 }else if( ALWAYS(pVTable->pVtab) ){
107829 /* Justification of ALWAYS(): A correct vtab constructor must allocate
107830 ** the sqlite3_vtab object if successful. */
107831 pVTable->pVtab->pModule = pMod->pModule;
107832 pVTable->nRef = 1;
107833 if( sCtx.pTab ){
107834 const char *zFormat = "vtable constructor did not declare schema: %s";
107835 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
107836 sqlite3VtabUnlock(pVTable);
107837 rc = SQLITE_ERROR;
107838 }else{
107839 int iCol;
107840 /* If everything went according to plan, link the new VTable structure
107841 ** into the linked list headed by pTab->pVTable. Then loop through the
107842 ** columns of the table to see if any of them contain the token "hidden".
107843 ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
107844 ** the type string. */
107845 pVTable->pNext = pTab->pVTable;
107846 pTab->pVTable = pVTable;
107848 for(iCol=0; iCol<pTab->nCol; iCol++){
107849 char *zType = pTab->aCol[iCol].zType;
107850 int nType;
107851 int i = 0;
107852 if( !zType ) continue;
107853 nType = sqlite3Strlen30(zType);
107854 if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
107855 for(i=0; i<nType; i++){
107856 if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
107857 && (zType[i+7]=='\0' || zType[i+7]==' ')
107860 break;
107864 if( i<nType ){
107865 int j;
107866 int nDel = 6 + (zType[i+6] ? 1 : 0);
107867 for(j=i; (j+nDel)<=nType; j++){
107868 zType[j] = zType[j+nDel];
107870 if( zType[i]=='\0' && i>0 ){
107871 assert(zType[i-1]==' ');
107872 zType[i-1] = '\0';
107874 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
107880 sqlite3DbFree(db, zModuleName);
107881 return rc;
107885 ** This function is invoked by the parser to call the xConnect() method
107886 ** of the virtual table pTab. If an error occurs, an error code is returned
107887 ** and an error left in pParse.
107889 ** This call is a no-op if table pTab is not a virtual table.
107891 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
107892 sqlite3 *db = pParse->db;
107893 const char *zMod;
107894 Module *pMod;
107895 int rc;
107897 assert( pTab );
107898 if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
107899 return SQLITE_OK;
107902 /* Locate the required virtual table module */
107903 zMod = pTab->azModuleArg[0];
107904 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
107906 if( !pMod ){
107907 const char *zModule = pTab->azModuleArg[0];
107908 sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
107909 rc = SQLITE_ERROR;
107910 }else{
107911 char *zErr = 0;
107912 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
107913 if( rc!=SQLITE_OK ){
107914 sqlite3ErrorMsg(pParse, "%s", zErr);
107916 sqlite3DbFree(db, zErr);
107919 return rc;
107922 ** Grow the db->aVTrans[] array so that there is room for at least one
107923 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
107925 static int growVTrans(sqlite3 *db){
107926 const int ARRAY_INCR = 5;
107928 /* Grow the sqlite3.aVTrans array if required */
107929 if( (db->nVTrans%ARRAY_INCR)==0 ){
107930 VTable **aVTrans;
107931 int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
107932 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
107933 if( !aVTrans ){
107934 return SQLITE_NOMEM;
107936 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
107937 db->aVTrans = aVTrans;
107940 return SQLITE_OK;
107944 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
107945 ** have already been reserved using growVTrans().
107947 static void addToVTrans(sqlite3 *db, VTable *pVTab){
107948 /* Add pVtab to the end of sqlite3.aVTrans */
107949 db->aVTrans[db->nVTrans++] = pVTab;
107950 sqlite3VtabLock(pVTab);
107954 ** This function is invoked by the vdbe to call the xCreate method
107955 ** of the virtual table named zTab in database iDb.
107957 ** If an error occurs, *pzErr is set to point an an English language
107958 ** description of the error and an SQLITE_XXX error code is returned.
107959 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
107961 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
107962 int rc = SQLITE_OK;
107963 Table *pTab;
107964 Module *pMod;
107965 const char *zMod;
107967 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
107968 assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
107970 /* Locate the required virtual table module */
107971 zMod = pTab->azModuleArg[0];
107972 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
107974 /* If the module has been registered and includes a Create method,
107975 ** invoke it now. If the module has not been registered, return an
107976 ** error. Otherwise, do nothing.
107978 if( !pMod ){
107979 *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
107980 rc = SQLITE_ERROR;
107981 }else{
107982 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
107985 /* Justification of ALWAYS(): The xConstructor method is required to
107986 ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
107987 if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
107988 rc = growVTrans(db);
107989 if( rc==SQLITE_OK ){
107990 addToVTrans(db, sqlite3GetVTable(db, pTab));
107994 return rc;
107998 ** This function is used to set the schema of a virtual table. It is only
107999 ** valid to call this function from within the xCreate() or xConnect() of a
108000 ** virtual table module.
108002 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
108003 Parse *pParse;
108005 int rc = SQLITE_OK;
108006 Table *pTab;
108007 char *zErr = 0;
108009 sqlite3_mutex_enter(db->mutex);
108010 if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
108011 sqlite3Error(db, SQLITE_MISUSE, 0);
108012 sqlite3_mutex_leave(db->mutex);
108013 return SQLITE_MISUSE_BKPT;
108015 assert( (pTab->tabFlags & TF_Virtual)!=0 );
108017 pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
108018 if( pParse==0 ){
108019 rc = SQLITE_NOMEM;
108020 }else{
108021 pParse->declareVtab = 1;
108022 pParse->db = db;
108023 pParse->nQueryLoop = 1;
108025 if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
108026 && pParse->pNewTable
108027 && !db->mallocFailed
108028 && !pParse->pNewTable->pSelect
108029 && (pParse->pNewTable->tabFlags & TF_Virtual)==0
108031 if( !pTab->aCol ){
108032 pTab->aCol = pParse->pNewTable->aCol;
108033 pTab->nCol = pParse->pNewTable->nCol;
108034 pParse->pNewTable->nCol = 0;
108035 pParse->pNewTable->aCol = 0;
108037 db->pVtabCtx->pTab = 0;
108038 }else{
108039 sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
108040 sqlite3DbFree(db, zErr);
108041 rc = SQLITE_ERROR;
108043 pParse->declareVtab = 0;
108045 if( pParse->pVdbe ){
108046 sqlite3VdbeFinalize(pParse->pVdbe);
108048 sqlite3DeleteTable(db, pParse->pNewTable);
108049 sqlite3ParserReset(pParse);
108050 sqlite3StackFree(db, pParse);
108053 assert( (rc&0xff)==rc );
108054 rc = sqlite3ApiExit(db, rc);
108055 sqlite3_mutex_leave(db->mutex);
108056 return rc;
108060 ** This function is invoked by the vdbe to call the xDestroy method
108061 ** of the virtual table named zTab in database iDb. This occurs
108062 ** when a DROP TABLE is mentioned.
108064 ** This call is a no-op if zTab is not a virtual table.
108066 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
108067 int rc = SQLITE_OK;
108068 Table *pTab;
108070 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
108071 if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
108072 VTable *p = vtabDisconnectAll(db, pTab);
108074 assert( rc==SQLITE_OK );
108075 rc = p->pMod->pModule->xDestroy(p->pVtab);
108077 /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
108078 if( rc==SQLITE_OK ){
108079 assert( pTab->pVTable==p && p->pNext==0 );
108080 p->pVtab = 0;
108081 pTab->pVTable = 0;
108082 sqlite3VtabUnlock(p);
108086 return rc;
108090 ** This function invokes either the xRollback or xCommit method
108091 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
108092 ** called is identified by the second argument, "offset", which is
108093 ** the offset of the method to call in the sqlite3_module structure.
108095 ** The array is cleared after invoking the callbacks.
108097 static void callFinaliser(sqlite3 *db, int offset){
108098 int i;
108099 if( db->aVTrans ){
108100 for(i=0; i<db->nVTrans; i++){
108101 VTable *pVTab = db->aVTrans[i];
108102 sqlite3_vtab *p = pVTab->pVtab;
108103 if( p ){
108104 int (*x)(sqlite3_vtab *);
108105 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
108106 if( x ) x(p);
108108 pVTab->iSavepoint = 0;
108109 sqlite3VtabUnlock(pVTab);
108111 sqlite3DbFree(db, db->aVTrans);
108112 db->nVTrans = 0;
108113 db->aVTrans = 0;
108118 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
108119 ** array. Return the error code for the first error that occurs, or
108120 ** SQLITE_OK if all xSync operations are successful.
108122 ** If an error message is available, leave it in p->zErrMsg.
108124 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
108125 int i;
108126 int rc = SQLITE_OK;
108127 VTable **aVTrans = db->aVTrans;
108129 db->aVTrans = 0;
108130 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
108131 int (*x)(sqlite3_vtab *);
108132 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
108133 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
108134 rc = x(pVtab);
108135 sqlite3VtabImportErrmsg(p, pVtab);
108138 db->aVTrans = aVTrans;
108139 return rc;
108143 ** Invoke the xRollback method of all virtual tables in the
108144 ** sqlite3.aVTrans array. Then clear the array itself.
108146 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
108147 callFinaliser(db, offsetof(sqlite3_module,xRollback));
108148 return SQLITE_OK;
108152 ** Invoke the xCommit method of all virtual tables in the
108153 ** sqlite3.aVTrans array. Then clear the array itself.
108155 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
108156 callFinaliser(db, offsetof(sqlite3_module,xCommit));
108157 return SQLITE_OK;
108161 ** If the virtual table pVtab supports the transaction interface
108162 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
108163 ** not currently open, invoke the xBegin method now.
108165 ** If the xBegin call is successful, place the sqlite3_vtab pointer
108166 ** in the sqlite3.aVTrans array.
108168 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
108169 int rc = SQLITE_OK;
108170 const sqlite3_module *pModule;
108172 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
108173 ** than zero, then this function is being called from within a
108174 ** virtual module xSync() callback. It is illegal to write to
108175 ** virtual module tables in this case, so return SQLITE_LOCKED.
108177 if( sqlite3VtabInSync(db) ){
108178 return SQLITE_LOCKED;
108180 if( !pVTab ){
108181 return SQLITE_OK;
108183 pModule = pVTab->pVtab->pModule;
108185 if( pModule->xBegin ){
108186 int i;
108188 /* If pVtab is already in the aVTrans array, return early */
108189 for(i=0; i<db->nVTrans; i++){
108190 if( db->aVTrans[i]==pVTab ){
108191 return SQLITE_OK;
108195 /* Invoke the xBegin method. If successful, add the vtab to the
108196 ** sqlite3.aVTrans[] array. */
108197 rc = growVTrans(db);
108198 if( rc==SQLITE_OK ){
108199 rc = pModule->xBegin(pVTab->pVtab);
108200 if( rc==SQLITE_OK ){
108201 addToVTrans(db, pVTab);
108205 return rc;
108209 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
108210 ** virtual tables that currently have an open transaction. Pass iSavepoint
108211 ** as the second argument to the virtual table method invoked.
108213 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
108214 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
108215 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
108216 ** an open transaction is invoked.
108218 ** If any virtual table method returns an error code other than SQLITE_OK,
108219 ** processing is abandoned and the error returned to the caller of this
108220 ** function immediately. If all calls to virtual table methods are successful,
108221 ** SQLITE_OK is returned.
108223 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
108224 int rc = SQLITE_OK;
108226 assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
108227 assert( iSavepoint>=0 );
108228 if( db->aVTrans ){
108229 int i;
108230 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
108231 VTable *pVTab = db->aVTrans[i];
108232 const sqlite3_module *pMod = pVTab->pMod->pModule;
108233 if( pVTab->pVtab && pMod->iVersion>=2 ){
108234 int (*xMethod)(sqlite3_vtab *, int);
108235 switch( op ){
108236 case SAVEPOINT_BEGIN:
108237 xMethod = pMod->xSavepoint;
108238 pVTab->iSavepoint = iSavepoint+1;
108239 break;
108240 case SAVEPOINT_ROLLBACK:
108241 xMethod = pMod->xRollbackTo;
108242 break;
108243 default:
108244 xMethod = pMod->xRelease;
108245 break;
108247 if( xMethod && pVTab->iSavepoint>iSavepoint ){
108248 rc = xMethod(pVTab->pVtab, iSavepoint);
108253 return rc;
108257 ** The first parameter (pDef) is a function implementation. The
108258 ** second parameter (pExpr) is the first argument to this function.
108259 ** If pExpr is a column in a virtual table, then let the virtual
108260 ** table implementation have an opportunity to overload the function.
108262 ** This routine is used to allow virtual table implementations to
108263 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
108265 ** Return either the pDef argument (indicating no change) or a
108266 ** new FuncDef structure that is marked as ephemeral using the
108267 ** SQLITE_FUNC_EPHEM flag.
108269 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
108270 sqlite3 *db, /* Database connection for reporting malloc problems */
108271 FuncDef *pDef, /* Function to possibly overload */
108272 int nArg, /* Number of arguments to the function */
108273 Expr *pExpr /* First argument to the function */
108275 Table *pTab;
108276 sqlite3_vtab *pVtab;
108277 sqlite3_module *pMod;
108278 void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
108279 void *pArg = 0;
108280 FuncDef *pNew;
108281 int rc = 0;
108282 char *zLowerName;
108283 unsigned char *z;
108286 /* Check to see the left operand is a column in a virtual table */
108287 if( NEVER(pExpr==0) ) return pDef;
108288 if( pExpr->op!=TK_COLUMN ) return pDef;
108289 pTab = pExpr->pTab;
108290 if( NEVER(pTab==0) ) return pDef;
108291 if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
108292 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
108293 assert( pVtab!=0 );
108294 assert( pVtab->pModule!=0 );
108295 pMod = (sqlite3_module *)pVtab->pModule;
108296 if( pMod->xFindFunction==0 ) return pDef;
108298 /* Call the xFindFunction method on the virtual table implementation
108299 ** to see if the implementation wants to overload this function
108301 zLowerName = sqlite3DbStrDup(db, pDef->zName);
108302 if( zLowerName ){
108303 for(z=(unsigned char*)zLowerName; *z; z++){
108304 *z = sqlite3UpperToLower[*z];
108306 rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
108307 sqlite3DbFree(db, zLowerName);
108309 if( rc==0 ){
108310 return pDef;
108313 /* Create a new ephemeral function definition for the overloaded
108314 ** function */
108315 pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
108316 + sqlite3Strlen30(pDef->zName) + 1);
108317 if( pNew==0 ){
108318 return pDef;
108320 *pNew = *pDef;
108321 pNew->zName = (char *)&pNew[1];
108322 memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
108323 pNew->xFunc = xFunc;
108324 pNew->pUserData = pArg;
108325 pNew->funcFlags |= SQLITE_FUNC_EPHEM;
108326 return pNew;
108330 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
108331 ** array so that an OP_VBegin will get generated for it. Add pTab to the
108332 ** array if it is missing. If pTab is already in the array, this routine
108333 ** is a no-op.
108335 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
108336 Parse *pToplevel = sqlite3ParseToplevel(pParse);
108337 int i, n;
108338 Table **apVtabLock;
108340 assert( IsVirtual(pTab) );
108341 for(i=0; i<pToplevel->nVtabLock; i++){
108342 if( pTab==pToplevel->apVtabLock[i] ) return;
108344 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
108345 apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
108346 if( apVtabLock ){
108347 pToplevel->apVtabLock = apVtabLock;
108348 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
108349 }else{
108350 pToplevel->db->mallocFailed = 1;
108355 ** Return the ON CONFLICT resolution mode in effect for the virtual
108356 ** table update operation currently in progress.
108358 ** The results of this routine are undefined unless it is called from
108359 ** within an xUpdate method.
108361 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
108362 static const unsigned char aMap[] = {
108363 SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
108365 assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
108366 assert( OE_Ignore==4 && OE_Replace==5 );
108367 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
108368 return (int)aMap[db->vtabOnConflict-1];
108372 ** Call from within the xCreate() or xConnect() methods to provide
108373 ** the SQLite core with additional information about the behavior
108374 ** of the virtual table being implemented.
108376 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
108377 va_list ap;
108378 int rc = SQLITE_OK;
108380 sqlite3_mutex_enter(db->mutex);
108382 va_start(ap, op);
108383 switch( op ){
108384 case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
108385 VtabCtx *p = db->pVtabCtx;
108386 if( !p ){
108387 rc = SQLITE_MISUSE_BKPT;
108388 }else{
108389 assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
108390 p->pVTable->bConstraint = (u8)va_arg(ap, int);
108392 break;
108394 default:
108395 rc = SQLITE_MISUSE_BKPT;
108396 break;
108398 va_end(ap);
108400 if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
108401 sqlite3_mutex_leave(db->mutex);
108402 return rc;
108405 #endif /* SQLITE_OMIT_VIRTUALTABLE */
108407 /************** End of vtab.c ************************************************/
108408 /************** Begin file where.c *******************************************/
108410 ** 2001 September 15
108412 ** The author disclaims copyright to this source code. In place of
108413 ** a legal notice, here is a blessing:
108415 ** May you do good and not evil.
108416 ** May you find forgiveness for yourself and forgive others.
108417 ** May you share freely, never taking more than you give.
108419 *************************************************************************
108420 ** This module contains C code that generates VDBE code used to process
108421 ** the WHERE clause of SQL statements. This module is responsible for
108422 ** generating the code that loops through a table looking for applicable
108423 ** rows. Indices are selected and used to speed the search when doing
108424 ** so is applicable. Because this module is responsible for selecting
108425 ** indices, you might also think of this module as the "query optimizer".
108427 /************** Include whereInt.h in the middle of where.c ******************/
108428 /************** Begin file whereInt.h ****************************************/
108430 ** 2013-11-12
108432 ** The author disclaims copyright to this source code. In place of
108433 ** a legal notice, here is a blessing:
108435 ** May you do good and not evil.
108436 ** May you find forgiveness for yourself and forgive others.
108437 ** May you share freely, never taking more than you give.
108439 *************************************************************************
108441 ** This file contains structure and macro definitions for the query
108442 ** planner logic in "where.c". These definitions are broken out into
108443 ** a separate source file for easier editing.
108447 ** Trace output macros
108449 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
108450 /***/ int sqlite3WhereTrace = 0;
108451 #endif
108452 #if defined(SQLITE_DEBUG) \
108453 && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
108454 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
108455 # define WHERETRACE_ENABLED 1
108456 #else
108457 # define WHERETRACE(K,X)
108458 #endif
108460 /* Forward references
108462 typedef struct WhereClause WhereClause;
108463 typedef struct WhereMaskSet WhereMaskSet;
108464 typedef struct WhereOrInfo WhereOrInfo;
108465 typedef struct WhereAndInfo WhereAndInfo;
108466 typedef struct WhereLevel WhereLevel;
108467 typedef struct WhereLoop WhereLoop;
108468 typedef struct WherePath WherePath;
108469 typedef struct WhereTerm WhereTerm;
108470 typedef struct WhereLoopBuilder WhereLoopBuilder;
108471 typedef struct WhereScan WhereScan;
108472 typedef struct WhereOrCost WhereOrCost;
108473 typedef struct WhereOrSet WhereOrSet;
108476 ** This object contains information needed to implement a single nested
108477 ** loop in WHERE clause.
108479 ** Contrast this object with WhereLoop. This object describes the
108480 ** implementation of the loop. WhereLoop describes the algorithm.
108481 ** This object contains a pointer to the WhereLoop algorithm as one of
108482 ** its elements.
108484 ** The WhereInfo object contains a single instance of this object for
108485 ** each term in the FROM clause (which is to say, for each of the
108486 ** nested loops as implemented). The order of WhereLevel objects determines
108487 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
108488 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
108490 struct WhereLevel {
108491 int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
108492 int iTabCur; /* The VDBE cursor used to access the table */
108493 int iIdxCur; /* The VDBE cursor used to access pIdx */
108494 int addrBrk; /* Jump here to break out of the loop */
108495 int addrNxt; /* Jump here to start the next IN combination */
108496 int addrSkip; /* Jump here for next iteration of skip-scan */
108497 int addrCont; /* Jump here to continue with the next loop cycle */
108498 int addrFirst; /* First instruction of interior of the loop */
108499 int addrBody; /* Beginning of the body of this loop */
108500 u8 iFrom; /* Which entry in the FROM clause */
108501 u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
108502 int p1, p2; /* Operands of the opcode used to ends the loop */
108503 union { /* Information that depends on pWLoop->wsFlags */
108504 struct {
108505 int nIn; /* Number of entries in aInLoop[] */
108506 struct InLoop {
108507 int iCur; /* The VDBE cursor used by this IN operator */
108508 int addrInTop; /* Top of the IN loop */
108509 u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
108510 } *aInLoop; /* Information about each nested IN operator */
108511 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
108512 Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
108514 struct WhereLoop *pWLoop; /* The selected WhereLoop object */
108515 Bitmask notReady; /* FROM entries not usable at this level */
108519 ** Each instance of this object represents an algorithm for evaluating one
108520 ** term of a join. Every term of the FROM clause will have at least
108521 ** one corresponding WhereLoop object (unless INDEXED BY constraints
108522 ** prevent a query solution - which is an error) and many terms of the
108523 ** FROM clause will have multiple WhereLoop objects, each describing a
108524 ** potential way of implementing that FROM-clause term, together with
108525 ** dependencies and cost estimates for using the chosen algorithm.
108527 ** Query planning consists of building up a collection of these WhereLoop
108528 ** objects, then computing a particular sequence of WhereLoop objects, with
108529 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
108530 ** and that minimize the overall cost.
108532 struct WhereLoop {
108533 Bitmask prereq; /* Bitmask of other loops that must run first */
108534 Bitmask maskSelf; /* Bitmask identifying table iTab */
108535 #ifdef SQLITE_DEBUG
108536 char cId; /* Symbolic ID of this loop for debugging use */
108537 #endif
108538 u8 iTab; /* Position in FROM clause of table for this loop */
108539 u8 iSortIdx; /* Sorting index number. 0==None */
108540 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
108541 LogEst rRun; /* Cost of running each loop */
108542 LogEst nOut; /* Estimated number of output rows */
108543 union {
108544 struct { /* Information for internal btree tables */
108545 u16 nEq; /* Number of equality constraints */
108546 u16 nSkip; /* Number of initial index columns to skip */
108547 Index *pIndex; /* Index used, or NULL */
108548 } btree;
108549 struct { /* Information for virtual tables */
108550 int idxNum; /* Index number */
108551 u8 needFree; /* True if sqlite3_free(idxStr) is needed */
108552 u8 isOrdered; /* True if satisfies ORDER BY */
108553 u16 omitMask; /* Terms that may be omitted */
108554 char *idxStr; /* Index identifier string */
108555 } vtab;
108557 u32 wsFlags; /* WHERE_* flags describing the plan */
108558 u16 nLTerm; /* Number of entries in aLTerm[] */
108559 /**** whereLoopXfer() copies fields above ***********************/
108560 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
108561 u16 nLSlot; /* Number of slots allocated for aLTerm[] */
108562 WhereTerm **aLTerm; /* WhereTerms used */
108563 WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
108564 WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
108567 /* This object holds the prerequisites and the cost of running a
108568 ** subquery on one operand of an OR operator in the WHERE clause.
108569 ** See WhereOrSet for additional information
108571 struct WhereOrCost {
108572 Bitmask prereq; /* Prerequisites */
108573 LogEst rRun; /* Cost of running this subquery */
108574 LogEst nOut; /* Number of outputs for this subquery */
108577 /* The WhereOrSet object holds a set of possible WhereOrCosts that
108578 ** correspond to the subquery(s) of OR-clause processing. Only the
108579 ** best N_OR_COST elements are retained.
108581 #define N_OR_COST 3
108582 struct WhereOrSet {
108583 u16 n; /* Number of valid a[] entries */
108584 WhereOrCost a[N_OR_COST]; /* Set of best costs */
108588 /* Forward declaration of methods */
108589 static int whereLoopResize(sqlite3*, WhereLoop*, int);
108592 ** Each instance of this object holds a sequence of WhereLoop objects
108593 ** that implement some or all of a query plan.
108595 ** Think of each WhereLoop object as a node in a graph with arcs
108596 ** showing dependencies and costs for travelling between nodes. (That is
108597 ** not a completely accurate description because WhereLoop costs are a
108598 ** vector, not a scalar, and because dependencies are many-to-one, not
108599 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
108600 ** Then a WherePath object is a path through the graph that visits some
108601 ** or all of the WhereLoop objects once.
108603 ** The "solver" works by creating the N best WherePath objects of length
108604 ** 1. Then using those as a basis to compute the N best WherePath objects
108605 ** of length 2. And so forth until the length of WherePaths equals the
108606 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
108607 ** at the end is the choosen query plan.
108609 struct WherePath {
108610 Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
108611 Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
108612 LogEst nRow; /* Estimated number of rows generated by this path */
108613 LogEst rCost; /* Total cost of this path */
108614 u8 isOrdered; /* True if this path satisfies ORDER BY */
108615 u8 isOrderedValid; /* True if the isOrdered field is valid */
108616 WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
108620 ** The query generator uses an array of instances of this structure to
108621 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
108622 ** clause subexpression is separated from the others by AND operators,
108623 ** usually, or sometimes subexpressions separated by OR.
108625 ** All WhereTerms are collected into a single WhereClause structure.
108626 ** The following identity holds:
108628 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
108630 ** When a term is of the form:
108632 ** X <op> <expr>
108634 ** where X is a column name and <op> is one of certain operators,
108635 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
108636 ** cursor number and column number for X. WhereTerm.eOperator records
108637 ** the <op> using a bitmask encoding defined by WO_xxx below. The
108638 ** use of a bitmask encoding for the operator allows us to search
108639 ** quickly for terms that match any of several different operators.
108641 ** A WhereTerm might also be two or more subterms connected by OR:
108643 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
108645 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
108646 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
108647 ** is collected about the OR clause.
108649 ** If a term in the WHERE clause does not match either of the two previous
108650 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
108651 ** to the original subexpression content and wtFlags is set up appropriately
108652 ** but no other fields in the WhereTerm object are meaningful.
108654 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
108655 ** but they do so indirectly. A single WhereMaskSet structure translates
108656 ** cursor number into bits and the translated bit is stored in the prereq
108657 ** fields. The translation is used in order to maximize the number of
108658 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
108659 ** spread out over the non-negative integers. For example, the cursor
108660 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
108661 ** translates these sparse cursor numbers into consecutive integers
108662 ** beginning with 0 in order to make the best possible use of the available
108663 ** bits in the Bitmask. So, in the example above, the cursor numbers
108664 ** would be mapped into integers 0 through 7.
108666 ** The number of terms in a join is limited by the number of bits
108667 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
108668 ** is only able to process joins with 64 or fewer tables.
108670 struct WhereTerm {
108671 Expr *pExpr; /* Pointer to the subexpression that is this term */
108672 int iParent; /* Disable pWC->a[iParent] when this term disabled */
108673 int leftCursor; /* Cursor number of X in "X <op> <expr>" */
108674 union {
108675 int leftColumn; /* Column number of X in "X <op> <expr>" */
108676 WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
108677 WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
108679 LogEst truthProb; /* Probability of truth for this expression */
108680 u16 eOperator; /* A WO_xx value describing <op> */
108681 u8 wtFlags; /* TERM_xxx bit flags. See below */
108682 u8 nChild; /* Number of children that must disable us */
108683 WhereClause *pWC; /* The clause this term is part of */
108684 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
108685 Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
108689 ** Allowed values of WhereTerm.wtFlags
108691 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
108692 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
108693 #define TERM_CODED 0x04 /* This term is already coded */
108694 #define TERM_COPIED 0x08 /* Has a child */
108695 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
108696 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
108697 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
108698 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
108699 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
108700 #else
108701 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
108702 #endif
108705 ** An instance of the WhereScan object is used as an iterator for locating
108706 ** terms in the WHERE clause that are useful to the query planner.
108708 struct WhereScan {
108709 WhereClause *pOrigWC; /* Original, innermost WhereClause */
108710 WhereClause *pWC; /* WhereClause currently being scanned */
108711 char *zCollName; /* Required collating sequence, if not NULL */
108712 char idxaff; /* Must match this affinity, if zCollName!=NULL */
108713 unsigned char nEquiv; /* Number of entries in aEquiv[] */
108714 unsigned char iEquiv; /* Next unused slot in aEquiv[] */
108715 u32 opMask; /* Acceptable operators */
108716 int k; /* Resume scanning at this->pWC->a[this->k] */
108717 int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
108721 ** An instance of the following structure holds all information about a
108722 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
108724 ** Explanation of pOuter: For a WHERE clause of the form
108726 ** a AND ((b AND c) OR (d AND e)) AND f
108728 ** There are separate WhereClause objects for the whole clause and for
108729 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
108730 ** subclauses points to the WhereClause object for the whole clause.
108732 struct WhereClause {
108733 WhereInfo *pWInfo; /* WHERE clause processing context */
108734 WhereClause *pOuter; /* Outer conjunction */
108735 u8 op; /* Split operator. TK_AND or TK_OR */
108736 int nTerm; /* Number of terms */
108737 int nSlot; /* Number of entries in a[] */
108738 WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
108739 #if defined(SQLITE_SMALL_STACK)
108740 WhereTerm aStatic[1]; /* Initial static space for a[] */
108741 #else
108742 WhereTerm aStatic[8]; /* Initial static space for a[] */
108743 #endif
108747 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
108748 ** a dynamically allocated instance of the following structure.
108750 struct WhereOrInfo {
108751 WhereClause wc; /* Decomposition into subterms */
108752 Bitmask indexable; /* Bitmask of all indexable tables in the clause */
108756 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
108757 ** a dynamically allocated instance of the following structure.
108759 struct WhereAndInfo {
108760 WhereClause wc; /* The subexpression broken out */
108764 ** An instance of the following structure keeps track of a mapping
108765 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
108767 ** The VDBE cursor numbers are small integers contained in
108768 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
108769 ** clause, the cursor numbers might not begin with 0 and they might
108770 ** contain gaps in the numbering sequence. But we want to make maximum
108771 ** use of the bits in our bitmasks. This structure provides a mapping
108772 ** from the sparse cursor numbers into consecutive integers beginning
108773 ** with 0.
108775 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
108776 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
108778 ** For example, if the WHERE clause expression used these VDBE
108779 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
108780 ** would map those cursor numbers into bits 0 through 5.
108782 ** Note that the mapping is not necessarily ordered. In the example
108783 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
108784 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
108785 ** does not really matter. What is important is that sparse cursor
108786 ** numbers all get mapped into bit numbers that begin with 0 and contain
108787 ** no gaps.
108789 struct WhereMaskSet {
108790 int n; /* Number of assigned cursor values */
108791 int ix[BMS]; /* Cursor assigned to each bit */
108795 ** This object is a convenience wrapper holding all information needed
108796 ** to construct WhereLoop objects for a particular query.
108798 struct WhereLoopBuilder {
108799 WhereInfo *pWInfo; /* Information about this WHERE */
108800 WhereClause *pWC; /* WHERE clause terms */
108801 ExprList *pOrderBy; /* ORDER BY clause */
108802 WhereLoop *pNew; /* Template WhereLoop */
108803 WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
108804 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
108805 UnpackedRecord *pRec; /* Probe for stat4 (if required) */
108806 int nRecValid; /* Number of valid fields currently in pRec */
108807 #endif
108811 ** The WHERE clause processing routine has two halves. The
108812 ** first part does the start of the WHERE loop and the second
108813 ** half does the tail of the WHERE loop. An instance of
108814 ** this structure is returned by the first half and passed
108815 ** into the second half to give some continuity.
108817 ** An instance of this object holds the complete state of the query
108818 ** planner.
108820 struct WhereInfo {
108821 Parse *pParse; /* Parsing and code generating context */
108822 SrcList *pTabList; /* List of tables in the join */
108823 ExprList *pOrderBy; /* The ORDER BY clause or NULL */
108824 ExprList *pResultSet; /* Result set. DISTINCT operates on these */
108825 WhereLoop *pLoops; /* List of all WhereLoop objects */
108826 Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
108827 LogEst nRowOut; /* Estimated number of output rows */
108828 u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
108829 u8 bOBSat; /* ORDER BY satisfied by indices */
108830 u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
108831 u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
108832 u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
108833 u8 nLevel; /* Number of nested loop */
108834 int iTop; /* The very beginning of the WHERE loop */
108835 int iContinue; /* Jump here to continue with next record */
108836 int iBreak; /* Jump here to break out of the loop */
108837 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
108838 int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
108839 WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
108840 WhereClause sWC; /* Decomposition of the WHERE clause */
108841 WhereLevel a[1]; /* Information about each nest loop in WHERE */
108845 ** Bitmasks for the operators on WhereTerm objects. These are all
108846 ** operators that are of interest to the query planner. An
108847 ** OR-ed combination of these values can be used when searching for
108848 ** particular WhereTerms within a WhereClause.
108850 #define WO_IN 0x001
108851 #define WO_EQ 0x002
108852 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
108853 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
108854 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
108855 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
108856 #define WO_MATCH 0x040
108857 #define WO_ISNULL 0x080
108858 #define WO_OR 0x100 /* Two or more OR-connected terms */
108859 #define WO_AND 0x200 /* Two or more AND-connected terms */
108860 #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
108861 #define WO_NOOP 0x800 /* This term does not restrict search space */
108863 #define WO_ALL 0xfff /* Mask of all possible WO_* values */
108864 #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
108867 ** These are definitions of bits in the WhereLoop.wsFlags field.
108868 ** The particular combination of bits in each WhereLoop help to
108869 ** determine the algorithm that WhereLoop represents.
108871 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
108872 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
108873 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
108874 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
108875 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
108876 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
108877 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
108878 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
108879 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
108880 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
108881 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
108882 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
108883 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
108884 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
108885 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
108886 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
108887 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
108889 /************** End of whereInt.h ********************************************/
108890 /************** Continuing where we left off in where.c **********************/
108893 ** Return the estimated number of output rows from a WHERE clause
108895 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
108896 return sqlite3LogEstToInt(pWInfo->nRowOut);
108900 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
108901 ** WHERE clause returns outputs for DISTINCT processing.
108903 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
108904 return pWInfo->eDistinct;
108908 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
108909 ** Return FALSE if the output needs to be sorted.
108911 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
108912 return pWInfo->bOBSat!=0;
108916 ** Return the VDBE address or label to jump to in order to continue
108917 ** immediately with the next row of a WHERE clause.
108919 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
108920 return pWInfo->iContinue;
108924 ** Return the VDBE address or label to jump to in order to break
108925 ** out of a WHERE loop.
108927 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
108928 return pWInfo->iBreak;
108932 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
108933 ** the rowids returned by a WHERE clause. Return FALSE if doing an
108934 ** UPDATE or DELETE might change subsequent WHERE clause results.
108936 ** If the ONEPASS optimization is used (if this routine returns true)
108937 ** then also write the indices of open cursors used by ONEPASS
108938 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
108939 ** table and iaCur[1] gets the cursor used by an auxiliary index.
108940 ** Either value may be -1, indicating that cursor is not used.
108941 ** Any cursors returned will have been opened for writing.
108943 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
108944 ** unable to use the ONEPASS optimization.
108946 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
108947 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
108948 return pWInfo->okOnePass;
108952 ** Move the content of pSrc into pDest
108954 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
108955 pDest->n = pSrc->n;
108956 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
108960 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
108962 ** The new entry might overwrite an existing entry, or it might be
108963 ** appended, or it might be discarded. Do whatever is the right thing
108964 ** so that pSet keeps the N_OR_COST best entries seen so far.
108966 static int whereOrInsert(
108967 WhereOrSet *pSet, /* The WhereOrSet to be updated */
108968 Bitmask prereq, /* Prerequisites of the new entry */
108969 LogEst rRun, /* Run-cost of the new entry */
108970 LogEst nOut /* Number of outputs for the new entry */
108972 u16 i;
108973 WhereOrCost *p;
108974 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
108975 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
108976 goto whereOrInsert_done;
108978 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
108979 return 0;
108982 if( pSet->n<N_OR_COST ){
108983 p = &pSet->a[pSet->n++];
108984 p->nOut = nOut;
108985 }else{
108986 p = pSet->a;
108987 for(i=1; i<pSet->n; i++){
108988 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
108990 if( p->rRun<=rRun ) return 0;
108992 whereOrInsert_done:
108993 p->prereq = prereq;
108994 p->rRun = rRun;
108995 if( p->nOut>nOut ) p->nOut = nOut;
108996 return 1;
109000 ** Initialize a preallocated WhereClause structure.
109002 static void whereClauseInit(
109003 WhereClause *pWC, /* The WhereClause to be initialized */
109004 WhereInfo *pWInfo /* The WHERE processing context */
109006 pWC->pWInfo = pWInfo;
109007 pWC->pOuter = 0;
109008 pWC->nTerm = 0;
109009 pWC->nSlot = ArraySize(pWC->aStatic);
109010 pWC->a = pWC->aStatic;
109013 /* Forward reference */
109014 static void whereClauseClear(WhereClause*);
109017 ** Deallocate all memory associated with a WhereOrInfo object.
109019 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
109020 whereClauseClear(&p->wc);
109021 sqlite3DbFree(db, p);
109025 ** Deallocate all memory associated with a WhereAndInfo object.
109027 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
109028 whereClauseClear(&p->wc);
109029 sqlite3DbFree(db, p);
109033 ** Deallocate a WhereClause structure. The WhereClause structure
109034 ** itself is not freed. This routine is the inverse of whereClauseInit().
109036 static void whereClauseClear(WhereClause *pWC){
109037 int i;
109038 WhereTerm *a;
109039 sqlite3 *db = pWC->pWInfo->pParse->db;
109040 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
109041 if( a->wtFlags & TERM_DYNAMIC ){
109042 sqlite3ExprDelete(db, a->pExpr);
109044 if( a->wtFlags & TERM_ORINFO ){
109045 whereOrInfoDelete(db, a->u.pOrInfo);
109046 }else if( a->wtFlags & TERM_ANDINFO ){
109047 whereAndInfoDelete(db, a->u.pAndInfo);
109050 if( pWC->a!=pWC->aStatic ){
109051 sqlite3DbFree(db, pWC->a);
109056 ** Add a single new WhereTerm entry to the WhereClause object pWC.
109057 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
109058 ** The index in pWC->a[] of the new WhereTerm is returned on success.
109059 ** 0 is returned if the new WhereTerm could not be added due to a memory
109060 ** allocation error. The memory allocation failure will be recorded in
109061 ** the db->mallocFailed flag so that higher-level functions can detect it.
109063 ** This routine will increase the size of the pWC->a[] array as necessary.
109065 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
109066 ** for freeing the expression p is assumed by the WhereClause object pWC.
109067 ** This is true even if this routine fails to allocate a new WhereTerm.
109069 ** WARNING: This routine might reallocate the space used to store
109070 ** WhereTerms. All pointers to WhereTerms should be invalidated after
109071 ** calling this routine. Such pointers may be reinitialized by referencing
109072 ** the pWC->a[] array.
109074 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
109075 WhereTerm *pTerm;
109076 int idx;
109077 testcase( wtFlags & TERM_VIRTUAL );
109078 if( pWC->nTerm>=pWC->nSlot ){
109079 WhereTerm *pOld = pWC->a;
109080 sqlite3 *db = pWC->pWInfo->pParse->db;
109081 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
109082 if( pWC->a==0 ){
109083 if( wtFlags & TERM_DYNAMIC ){
109084 sqlite3ExprDelete(db, p);
109086 pWC->a = pOld;
109087 return 0;
109089 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
109090 if( pOld!=pWC->aStatic ){
109091 sqlite3DbFree(db, pOld);
109093 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
109095 pTerm = &pWC->a[idx = pWC->nTerm++];
109096 if( p && ExprHasProperty(p, EP_Unlikely) ){
109097 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
109098 }else{
109099 pTerm->truthProb = -1;
109101 pTerm->pExpr = sqlite3ExprSkipCollate(p);
109102 pTerm->wtFlags = wtFlags;
109103 pTerm->pWC = pWC;
109104 pTerm->iParent = -1;
109105 return idx;
109109 ** This routine identifies subexpressions in the WHERE clause where
109110 ** each subexpression is separated by the AND operator or some other
109111 ** operator specified in the op parameter. The WhereClause structure
109112 ** is filled with pointers to subexpressions. For example:
109114 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
109115 ** \________/ \_______________/ \________________/
109116 ** slot[0] slot[1] slot[2]
109118 ** The original WHERE clause in pExpr is unaltered. All this routine
109119 ** does is make slot[] entries point to substructure within pExpr.
109121 ** In the previous sentence and in the diagram, "slot[]" refers to
109122 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
109123 ** all terms of the WHERE clause.
109125 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
109126 pWC->op = op;
109127 if( pExpr==0 ) return;
109128 if( pExpr->op!=op ){
109129 whereClauseInsert(pWC, pExpr, 0);
109130 }else{
109131 whereSplit(pWC, pExpr->pLeft, op);
109132 whereSplit(pWC, pExpr->pRight, op);
109137 ** Initialize a WhereMaskSet object
109139 #define initMaskSet(P) (P)->n=0
109142 ** Return the bitmask for the given cursor number. Return 0 if
109143 ** iCursor is not in the set.
109145 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
109146 int i;
109147 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
109148 for(i=0; i<pMaskSet->n; i++){
109149 if( pMaskSet->ix[i]==iCursor ){
109150 return MASKBIT(i);
109153 return 0;
109157 ** Create a new mask for cursor iCursor.
109159 ** There is one cursor per table in the FROM clause. The number of
109160 ** tables in the FROM clause is limited by a test early in the
109161 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
109162 ** array will never overflow.
109164 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
109165 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
109166 pMaskSet->ix[pMaskSet->n++] = iCursor;
109170 ** These routines walk (recursively) an expression tree and generate
109171 ** a bitmask indicating which tables are used in that expression
109172 ** tree.
109174 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
109175 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
109176 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
109177 Bitmask mask = 0;
109178 if( p==0 ) return 0;
109179 if( p->op==TK_COLUMN ){
109180 mask = getMask(pMaskSet, p->iTable);
109181 return mask;
109183 mask = exprTableUsage(pMaskSet, p->pRight);
109184 mask |= exprTableUsage(pMaskSet, p->pLeft);
109185 if( ExprHasProperty(p, EP_xIsSelect) ){
109186 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
109187 }else{
109188 mask |= exprListTableUsage(pMaskSet, p->x.pList);
109190 return mask;
109192 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
109193 int i;
109194 Bitmask mask = 0;
109195 if( pList ){
109196 for(i=0; i<pList->nExpr; i++){
109197 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
109200 return mask;
109202 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
109203 Bitmask mask = 0;
109204 while( pS ){
109205 SrcList *pSrc = pS->pSrc;
109206 mask |= exprListTableUsage(pMaskSet, pS->pEList);
109207 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
109208 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
109209 mask |= exprTableUsage(pMaskSet, pS->pWhere);
109210 mask |= exprTableUsage(pMaskSet, pS->pHaving);
109211 if( ALWAYS(pSrc!=0) ){
109212 int i;
109213 for(i=0; i<pSrc->nSrc; i++){
109214 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
109215 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
109218 pS = pS->pPrior;
109220 return mask;
109224 ** Return TRUE if the given operator is one of the operators that is
109225 ** allowed for an indexable WHERE clause term. The allowed operators are
109226 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
109228 static int allowedOp(int op){
109229 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
109230 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
109231 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
109232 assert( TK_GE==TK_EQ+4 );
109233 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
109237 ** Swap two objects of type TYPE.
109239 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
109242 ** Commute a comparison operator. Expressions of the form "X op Y"
109243 ** are converted into "Y op X".
109245 ** If left/right precedence rules come into play when determining the
109246 ** collating sequence, then COLLATE operators are adjusted to ensure
109247 ** that the collating sequence does not change. For example:
109248 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
109249 ** the left hand side of a comparison overrides any collation sequence
109250 ** attached to the right. For the same reason the EP_Collate flag
109251 ** is not commuted.
109253 static void exprCommute(Parse *pParse, Expr *pExpr){
109254 u16 expRight = (pExpr->pRight->flags & EP_Collate);
109255 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
109256 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
109257 if( expRight==expLeft ){
109258 /* Either X and Y both have COLLATE operator or neither do */
109259 if( expRight ){
109260 /* Both X and Y have COLLATE operators. Make sure X is always
109261 ** used by clearing the EP_Collate flag from Y. */
109262 pExpr->pRight->flags &= ~EP_Collate;
109263 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
109264 /* Neither X nor Y have COLLATE operators, but X has a non-default
109265 ** collating sequence. So add the EP_Collate marker on X to cause
109266 ** it to be searched first. */
109267 pExpr->pLeft->flags |= EP_Collate;
109270 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
109271 if( pExpr->op>=TK_GT ){
109272 assert( TK_LT==TK_GT+2 );
109273 assert( TK_GE==TK_LE+2 );
109274 assert( TK_GT>TK_EQ );
109275 assert( TK_GT<TK_LE );
109276 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
109277 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
109282 ** Translate from TK_xx operator to WO_xx bitmask.
109284 static u16 operatorMask(int op){
109285 u16 c;
109286 assert( allowedOp(op) );
109287 if( op==TK_IN ){
109288 c = WO_IN;
109289 }else if( op==TK_ISNULL ){
109290 c = WO_ISNULL;
109291 }else{
109292 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
109293 c = (u16)(WO_EQ<<(op-TK_EQ));
109295 assert( op!=TK_ISNULL || c==WO_ISNULL );
109296 assert( op!=TK_IN || c==WO_IN );
109297 assert( op!=TK_EQ || c==WO_EQ );
109298 assert( op!=TK_LT || c==WO_LT );
109299 assert( op!=TK_LE || c==WO_LE );
109300 assert( op!=TK_GT || c==WO_GT );
109301 assert( op!=TK_GE || c==WO_GE );
109302 return c;
109306 ** Advance to the next WhereTerm that matches according to the criteria
109307 ** established when the pScan object was initialized by whereScanInit().
109308 ** Return NULL if there are no more matching WhereTerms.
109310 static WhereTerm *whereScanNext(WhereScan *pScan){
109311 int iCur; /* The cursor on the LHS of the term */
109312 int iColumn; /* The column on the LHS of the term. -1 for IPK */
109313 Expr *pX; /* An expression being tested */
109314 WhereClause *pWC; /* Shorthand for pScan->pWC */
109315 WhereTerm *pTerm; /* The term being tested */
109316 int k = pScan->k; /* Where to start scanning */
109318 while( pScan->iEquiv<=pScan->nEquiv ){
109319 iCur = pScan->aEquiv[pScan->iEquiv-2];
109320 iColumn = pScan->aEquiv[pScan->iEquiv-1];
109321 while( (pWC = pScan->pWC)!=0 ){
109322 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
109323 if( pTerm->leftCursor==iCur
109324 && pTerm->u.leftColumn==iColumn
109325 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
109327 if( (pTerm->eOperator & WO_EQUIV)!=0
109328 && pScan->nEquiv<ArraySize(pScan->aEquiv)
109330 int j;
109331 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
109332 assert( pX->op==TK_COLUMN );
109333 for(j=0; j<pScan->nEquiv; j+=2){
109334 if( pScan->aEquiv[j]==pX->iTable
109335 && pScan->aEquiv[j+1]==pX->iColumn ){
109336 break;
109339 if( j==pScan->nEquiv ){
109340 pScan->aEquiv[j] = pX->iTable;
109341 pScan->aEquiv[j+1] = pX->iColumn;
109342 pScan->nEquiv += 2;
109345 if( (pTerm->eOperator & pScan->opMask)!=0 ){
109346 /* Verify the affinity and collating sequence match */
109347 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
109348 CollSeq *pColl;
109349 Parse *pParse = pWC->pWInfo->pParse;
109350 pX = pTerm->pExpr;
109351 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
109352 continue;
109354 assert(pX->pLeft);
109355 pColl = sqlite3BinaryCompareCollSeq(pParse,
109356 pX->pLeft, pX->pRight);
109357 if( pColl==0 ) pColl = pParse->db->pDfltColl;
109358 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
109359 continue;
109362 if( (pTerm->eOperator & WO_EQ)!=0
109363 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
109364 && pX->iTable==pScan->aEquiv[0]
109365 && pX->iColumn==pScan->aEquiv[1]
109367 continue;
109369 pScan->k = k+1;
109370 return pTerm;
109374 pScan->pWC = pScan->pWC->pOuter;
109375 k = 0;
109377 pScan->pWC = pScan->pOrigWC;
109378 k = 0;
109379 pScan->iEquiv += 2;
109381 return 0;
109385 ** Initialize a WHERE clause scanner object. Return a pointer to the
109386 ** first match. Return NULL if there are no matches.
109388 ** The scanner will be searching the WHERE clause pWC. It will look
109389 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
109390 ** iCur. The <op> must be one of the operators described by opMask.
109392 ** If the search is for X and the WHERE clause contains terms of the
109393 ** form X=Y then this routine might also return terms of the form
109394 ** "Y <op> <expr>". The number of levels of transitivity is limited,
109395 ** but is enough to handle most commonly occurring SQL statements.
109397 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
109398 ** index pIdx.
109400 static WhereTerm *whereScanInit(
109401 WhereScan *pScan, /* The WhereScan object being initialized */
109402 WhereClause *pWC, /* The WHERE clause to be scanned */
109403 int iCur, /* Cursor to scan for */
109404 int iColumn, /* Column to scan for */
109405 u32 opMask, /* Operator(s) to scan for */
109406 Index *pIdx /* Must be compatible with this index */
109408 int j;
109410 /* memset(pScan, 0, sizeof(*pScan)); */
109411 pScan->pOrigWC = pWC;
109412 pScan->pWC = pWC;
109413 if( pIdx && iColumn>=0 ){
109414 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
109415 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
109416 if( NEVER(j>=pIdx->nKeyCol) ) return 0;
109418 pScan->zCollName = pIdx->azColl[j];
109419 }else{
109420 pScan->idxaff = 0;
109421 pScan->zCollName = 0;
109423 pScan->opMask = opMask;
109424 pScan->k = 0;
109425 pScan->aEquiv[0] = iCur;
109426 pScan->aEquiv[1] = iColumn;
109427 pScan->nEquiv = 2;
109428 pScan->iEquiv = 2;
109429 return whereScanNext(pScan);
109433 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
109434 ** where X is a reference to the iColumn of table iCur and <op> is one of
109435 ** the WO_xx operator codes specified by the op parameter.
109436 ** Return a pointer to the term. Return 0 if not found.
109438 ** The term returned might by Y=<expr> if there is another constraint in
109439 ** the WHERE clause that specifies that X=Y. Any such constraints will be
109440 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
109441 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
109442 ** taking up two slots in aEquiv[]. The first slot is for the cursor number
109443 ** and the second is for the column number. There are 22 slots in aEquiv[]
109444 ** so that means we can look for X plus up to 10 other equivalent values.
109445 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
109446 ** and ... and A9=A10 and A10=<expr>.
109448 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
109449 ** then try for the one with no dependencies on <expr> - in other words where
109450 ** <expr> is a constant expression of some kind. Only return entries of
109451 ** the form "X <op> Y" where Y is a column in another table if no terms of
109452 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
109453 ** exist, try to return a term that does not use WO_EQUIV.
109455 static WhereTerm *findTerm(
109456 WhereClause *pWC, /* The WHERE clause to be searched */
109457 int iCur, /* Cursor number of LHS */
109458 int iColumn, /* Column number of LHS */
109459 Bitmask notReady, /* RHS must not overlap with this mask */
109460 u32 op, /* Mask of WO_xx values describing operator */
109461 Index *pIdx /* Must be compatible with this index, if not NULL */
109463 WhereTerm *pResult = 0;
109464 WhereTerm *p;
109465 WhereScan scan;
109467 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
109468 while( p ){
109469 if( (p->prereqRight & notReady)==0 ){
109470 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
109471 return p;
109473 if( pResult==0 ) pResult = p;
109475 p = whereScanNext(&scan);
109477 return pResult;
109480 /* Forward reference */
109481 static void exprAnalyze(SrcList*, WhereClause*, int);
109484 ** Call exprAnalyze on all terms in a WHERE clause.
109486 static void exprAnalyzeAll(
109487 SrcList *pTabList, /* the FROM clause */
109488 WhereClause *pWC /* the WHERE clause to be analyzed */
109490 int i;
109491 for(i=pWC->nTerm-1; i>=0; i--){
109492 exprAnalyze(pTabList, pWC, i);
109496 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
109498 ** Check to see if the given expression is a LIKE or GLOB operator that
109499 ** can be optimized using inequality constraints. Return TRUE if it is
109500 ** so and false if not.
109502 ** In order for the operator to be optimizible, the RHS must be a string
109503 ** literal that does not begin with a wildcard.
109505 static int isLikeOrGlob(
109506 Parse *pParse, /* Parsing and code generating context */
109507 Expr *pExpr, /* Test this expression */
109508 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
109509 int *pisComplete, /* True if the only wildcard is % in the last character */
109510 int *pnoCase /* True if uppercase is equivalent to lowercase */
109512 const char *z = 0; /* String on RHS of LIKE operator */
109513 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
109514 ExprList *pList; /* List of operands to the LIKE operator */
109515 int c; /* One character in z[] */
109516 int cnt; /* Number of non-wildcard prefix characters */
109517 char wc[3]; /* Wildcard characters */
109518 sqlite3 *db = pParse->db; /* Database connection */
109519 sqlite3_value *pVal = 0;
109520 int op; /* Opcode of pRight */
109522 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
109523 return 0;
109525 #ifdef SQLITE_EBCDIC
109526 if( *pnoCase ) return 0;
109527 #endif
109528 pList = pExpr->x.pList;
109529 pLeft = pList->a[1].pExpr;
109530 if( pLeft->op!=TK_COLUMN
109531 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
109532 || IsVirtual(pLeft->pTab)
109534 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
109535 ** be the name of an indexed column with TEXT affinity. */
109536 return 0;
109538 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
109540 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
109541 op = pRight->op;
109542 if( op==TK_VARIABLE ){
109543 Vdbe *pReprepare = pParse->pReprepare;
109544 int iCol = pRight->iColumn;
109545 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
109546 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
109547 z = (char *)sqlite3_value_text(pVal);
109549 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
109550 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
109551 }else if( op==TK_STRING ){
109552 z = pRight->u.zToken;
109554 if( z ){
109555 cnt = 0;
109556 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
109557 cnt++;
109559 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
109560 Expr *pPrefix;
109561 *pisComplete = c==wc[0] && z[cnt+1]==0;
109562 pPrefix = sqlite3Expr(db, TK_STRING, z);
109563 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
109564 *ppPrefix = pPrefix;
109565 if( op==TK_VARIABLE ){
109566 Vdbe *v = pParse->pVdbe;
109567 sqlite3VdbeSetVarmask(v, pRight->iColumn);
109568 if( *pisComplete && pRight->u.zToken[1] ){
109569 /* If the rhs of the LIKE expression is a variable, and the current
109570 ** value of the variable means there is no need to invoke the LIKE
109571 ** function, then no OP_Variable will be added to the program.
109572 ** This causes problems for the sqlite3_bind_parameter_name()
109573 ** API. To workaround them, add a dummy OP_Variable here.
109575 int r1 = sqlite3GetTempReg(pParse);
109576 sqlite3ExprCodeTarget(pParse, pRight, r1);
109577 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
109578 sqlite3ReleaseTempReg(pParse, r1);
109581 }else{
109582 z = 0;
109586 sqlite3ValueFree(pVal);
109587 return (z!=0);
109589 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
109592 #ifndef SQLITE_OMIT_VIRTUALTABLE
109594 ** Check to see if the given expression is of the form
109596 ** column MATCH expr
109598 ** If it is then return TRUE. If not, return FALSE.
109600 static int isMatchOfColumn(
109601 Expr *pExpr /* Test this expression */
109603 ExprList *pList;
109605 if( pExpr->op!=TK_FUNCTION ){
109606 return 0;
109608 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
109609 return 0;
109611 pList = pExpr->x.pList;
109612 if( pList->nExpr!=2 ){
109613 return 0;
109615 if( pList->a[1].pExpr->op != TK_COLUMN ){
109616 return 0;
109618 return 1;
109620 #endif /* SQLITE_OMIT_VIRTUALTABLE */
109623 ** If the pBase expression originated in the ON or USING clause of
109624 ** a join, then transfer the appropriate markings over to derived.
109626 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
109627 if( pDerived ){
109628 pDerived->flags |= pBase->flags & EP_FromJoin;
109629 pDerived->iRightJoinTable = pBase->iRightJoinTable;
109633 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
109635 ** Analyze a term that consists of two or more OR-connected
109636 ** subterms. So in:
109638 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
109639 ** ^^^^^^^^^^^^^^^^^^^^
109641 ** This routine analyzes terms such as the middle term in the above example.
109642 ** A WhereOrTerm object is computed and attached to the term under
109643 ** analysis, regardless of the outcome of the analysis. Hence:
109645 ** WhereTerm.wtFlags |= TERM_ORINFO
109646 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
109648 ** The term being analyzed must have two or more of OR-connected subterms.
109649 ** A single subterm might be a set of AND-connected sub-subterms.
109650 ** Examples of terms under analysis:
109652 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
109653 ** (B) x=expr1 OR expr2=x OR x=expr3
109654 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
109655 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
109656 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
109658 ** CASE 1:
109660 ** If all subterms are of the form T.C=expr for some single column of C and
109661 ** a single table T (as shown in example B above) then create a new virtual
109662 ** term that is an equivalent IN expression. In other words, if the term
109663 ** being analyzed is:
109665 ** x = expr1 OR expr2 = x OR x = expr3
109667 ** then create a new virtual term like this:
109669 ** x IN (expr1,expr2,expr3)
109671 ** CASE 2:
109673 ** If all subterms are indexable by a single table T, then set
109675 ** WhereTerm.eOperator = WO_OR
109676 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
109678 ** A subterm is "indexable" if it is of the form
109679 ** "T.C <op> <expr>" where C is any column of table T and
109680 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
109681 ** A subterm is also indexable if it is an AND of two or more
109682 ** subsubterms at least one of which is indexable. Indexable AND
109683 ** subterms have their eOperator set to WO_AND and they have
109684 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
109686 ** From another point of view, "indexable" means that the subterm could
109687 ** potentially be used with an index if an appropriate index exists.
109688 ** This analysis does not consider whether or not the index exists; that
109689 ** is decided elsewhere. This analysis only looks at whether subterms
109690 ** appropriate for indexing exist.
109692 ** All examples A through E above satisfy case 2. But if a term
109693 ** also statisfies case 1 (such as B) we know that the optimizer will
109694 ** always prefer case 1, so in that case we pretend that case 2 is not
109695 ** satisfied.
109697 ** It might be the case that multiple tables are indexable. For example,
109698 ** (E) above is indexable on tables P, Q, and R.
109700 ** Terms that satisfy case 2 are candidates for lookup by using
109701 ** separate indices to find rowids for each subterm and composing
109702 ** the union of all rowids using a RowSet object. This is similar
109703 ** to "bitmap indices" in other database engines.
109705 ** OTHERWISE:
109707 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
109708 ** zero. This term is not useful for search.
109710 static void exprAnalyzeOrTerm(
109711 SrcList *pSrc, /* the FROM clause */
109712 WhereClause *pWC, /* the complete WHERE clause */
109713 int idxTerm /* Index of the OR-term to be analyzed */
109715 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
109716 Parse *pParse = pWInfo->pParse; /* Parser context */
109717 sqlite3 *db = pParse->db; /* Database connection */
109718 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
109719 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
109720 int i; /* Loop counters */
109721 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
109722 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
109723 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
109724 Bitmask chngToIN; /* Tables that might satisfy case 1 */
109725 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
109728 ** Break the OR clause into its separate subterms. The subterms are
109729 ** stored in a WhereClause structure containing within the WhereOrInfo
109730 ** object that is attached to the original OR clause term.
109732 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
109733 assert( pExpr->op==TK_OR );
109734 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
109735 if( pOrInfo==0 ) return;
109736 pTerm->wtFlags |= TERM_ORINFO;
109737 pOrWc = &pOrInfo->wc;
109738 whereClauseInit(pOrWc, pWInfo);
109739 whereSplit(pOrWc, pExpr, TK_OR);
109740 exprAnalyzeAll(pSrc, pOrWc);
109741 if( db->mallocFailed ) return;
109742 assert( pOrWc->nTerm>=2 );
109745 ** Compute the set of tables that might satisfy cases 1 or 2.
109747 indexable = ~(Bitmask)0;
109748 chngToIN = ~(Bitmask)0;
109749 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
109750 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
109751 WhereAndInfo *pAndInfo;
109752 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
109753 chngToIN = 0;
109754 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
109755 if( pAndInfo ){
109756 WhereClause *pAndWC;
109757 WhereTerm *pAndTerm;
109758 int j;
109759 Bitmask b = 0;
109760 pOrTerm->u.pAndInfo = pAndInfo;
109761 pOrTerm->wtFlags |= TERM_ANDINFO;
109762 pOrTerm->eOperator = WO_AND;
109763 pAndWC = &pAndInfo->wc;
109764 whereClauseInit(pAndWC, pWC->pWInfo);
109765 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
109766 exprAnalyzeAll(pSrc, pAndWC);
109767 pAndWC->pOuter = pWC;
109768 testcase( db->mallocFailed );
109769 if( !db->mallocFailed ){
109770 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
109771 assert( pAndTerm->pExpr );
109772 if( allowedOp(pAndTerm->pExpr->op) ){
109773 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
109777 indexable &= b;
109779 }else if( pOrTerm->wtFlags & TERM_COPIED ){
109780 /* Skip this term for now. We revisit it when we process the
109781 ** corresponding TERM_VIRTUAL term */
109782 }else{
109783 Bitmask b;
109784 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
109785 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
109786 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
109787 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
109789 indexable &= b;
109790 if( (pOrTerm->eOperator & WO_EQ)==0 ){
109791 chngToIN = 0;
109792 }else{
109793 chngToIN &= b;
109799 ** Record the set of tables that satisfy case 2. The set might be
109800 ** empty.
109802 pOrInfo->indexable = indexable;
109803 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
109806 ** chngToIN holds a set of tables that *might* satisfy case 1. But
109807 ** we have to do some additional checking to see if case 1 really
109808 ** is satisfied.
109810 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
109811 ** that there is no possibility of transforming the OR clause into an
109812 ** IN operator because one or more terms in the OR clause contain
109813 ** something other than == on a column in the single table. The 1-bit
109814 ** case means that every term of the OR clause is of the form
109815 ** "table.column=expr" for some single table. The one bit that is set
109816 ** will correspond to the common table. We still need to check to make
109817 ** sure the same column is used on all terms. The 2-bit case is when
109818 ** the all terms are of the form "table1.column=table2.column". It
109819 ** might be possible to form an IN operator with either table1.column
109820 ** or table2.column as the LHS if either is common to every term of
109821 ** the OR clause.
109823 ** Note that terms of the form "table.column1=table.column2" (the
109824 ** same table on both sizes of the ==) cannot be optimized.
109826 if( chngToIN ){
109827 int okToChngToIN = 0; /* True if the conversion to IN is valid */
109828 int iColumn = -1; /* Column index on lhs of IN operator */
109829 int iCursor = -1; /* Table cursor common to all terms */
109830 int j = 0; /* Loop counter */
109832 /* Search for a table and column that appears on one side or the
109833 ** other of the == operator in every subterm. That table and column
109834 ** will be recorded in iCursor and iColumn. There might not be any
109835 ** such table and column. Set okToChngToIN if an appropriate table
109836 ** and column is found but leave okToChngToIN false if not found.
109838 for(j=0; j<2 && !okToChngToIN; j++){
109839 pOrTerm = pOrWc->a;
109840 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
109841 assert( pOrTerm->eOperator & WO_EQ );
109842 pOrTerm->wtFlags &= ~TERM_OR_OK;
109843 if( pOrTerm->leftCursor==iCursor ){
109844 /* This is the 2-bit case and we are on the second iteration and
109845 ** current term is from the first iteration. So skip this term. */
109846 assert( j==1 );
109847 continue;
109849 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
109850 /* This term must be of the form t1.a==t2.b where t2 is in the
109851 ** chngToIN set but t1 is not. This term will be either preceeded
109852 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
109853 ** and use its inversion. */
109854 testcase( pOrTerm->wtFlags & TERM_COPIED );
109855 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
109856 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
109857 continue;
109859 iColumn = pOrTerm->u.leftColumn;
109860 iCursor = pOrTerm->leftCursor;
109861 break;
109863 if( i<0 ){
109864 /* No candidate table+column was found. This can only occur
109865 ** on the second iteration */
109866 assert( j==1 );
109867 assert( IsPowerOfTwo(chngToIN) );
109868 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
109869 break;
109871 testcase( j==1 );
109873 /* We have found a candidate table and column. Check to see if that
109874 ** table and column is common to every term in the OR clause */
109875 okToChngToIN = 1;
109876 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
109877 assert( pOrTerm->eOperator & WO_EQ );
109878 if( pOrTerm->leftCursor!=iCursor ){
109879 pOrTerm->wtFlags &= ~TERM_OR_OK;
109880 }else if( pOrTerm->u.leftColumn!=iColumn ){
109881 okToChngToIN = 0;
109882 }else{
109883 int affLeft, affRight;
109884 /* If the right-hand side is also a column, then the affinities
109885 ** of both right and left sides must be such that no type
109886 ** conversions are required on the right. (Ticket #2249)
109888 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
109889 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
109890 if( affRight!=0 && affRight!=affLeft ){
109891 okToChngToIN = 0;
109892 }else{
109893 pOrTerm->wtFlags |= TERM_OR_OK;
109899 /* At this point, okToChngToIN is true if original pTerm satisfies
109900 ** case 1. In that case, construct a new virtual term that is
109901 ** pTerm converted into an IN operator.
109903 if( okToChngToIN ){
109904 Expr *pDup; /* A transient duplicate expression */
109905 ExprList *pList = 0; /* The RHS of the IN operator */
109906 Expr *pLeft = 0; /* The LHS of the IN operator */
109907 Expr *pNew; /* The complete IN operator */
109909 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
109910 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
109911 assert( pOrTerm->eOperator & WO_EQ );
109912 assert( pOrTerm->leftCursor==iCursor );
109913 assert( pOrTerm->u.leftColumn==iColumn );
109914 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
109915 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
109916 pLeft = pOrTerm->pExpr->pLeft;
109918 assert( pLeft!=0 );
109919 pDup = sqlite3ExprDup(db, pLeft, 0);
109920 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
109921 if( pNew ){
109922 int idxNew;
109923 transferJoinMarkings(pNew, pExpr);
109924 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
109925 pNew->x.pList = pList;
109926 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
109927 testcase( idxNew==0 );
109928 exprAnalyze(pSrc, pWC, idxNew);
109929 pTerm = &pWC->a[idxTerm];
109930 pWC->a[idxNew].iParent = idxTerm;
109931 pTerm->nChild = 1;
109932 }else{
109933 sqlite3ExprListDelete(db, pList);
109935 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
109939 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
109942 ** The input to this routine is an WhereTerm structure with only the
109943 ** "pExpr" field filled in. The job of this routine is to analyze the
109944 ** subexpression and populate all the other fields of the WhereTerm
109945 ** structure.
109947 ** If the expression is of the form "<expr> <op> X" it gets commuted
109948 ** to the standard form of "X <op> <expr>".
109950 ** If the expression is of the form "X <op> Y" where both X and Y are
109951 ** columns, then the original expression is unchanged and a new virtual
109952 ** term of the form "Y <op> X" is added to the WHERE clause and
109953 ** analyzed separately. The original term is marked with TERM_COPIED
109954 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
109955 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
109956 ** is a commuted copy of a prior term.) The original term has nChild=1
109957 ** and the copy has idxParent set to the index of the original term.
109959 static void exprAnalyze(
109960 SrcList *pSrc, /* the FROM clause */
109961 WhereClause *pWC, /* the WHERE clause */
109962 int idxTerm /* Index of the term to be analyzed */
109964 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
109965 WhereTerm *pTerm; /* The term to be analyzed */
109966 WhereMaskSet *pMaskSet; /* Set of table index masks */
109967 Expr *pExpr; /* The expression to be analyzed */
109968 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
109969 Bitmask prereqAll; /* Prerequesites of pExpr */
109970 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
109971 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
109972 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
109973 int noCase = 0; /* LIKE/GLOB distinguishes case */
109974 int op; /* Top-level operator. pExpr->op */
109975 Parse *pParse = pWInfo->pParse; /* Parsing context */
109976 sqlite3 *db = pParse->db; /* Database connection */
109978 if( db->mallocFailed ){
109979 return;
109981 pTerm = &pWC->a[idxTerm];
109982 pMaskSet = &pWInfo->sMaskSet;
109983 pExpr = pTerm->pExpr;
109984 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
109985 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
109986 op = pExpr->op;
109987 if( op==TK_IN ){
109988 assert( pExpr->pRight==0 );
109989 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
109990 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
109991 }else{
109992 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
109994 }else if( op==TK_ISNULL ){
109995 pTerm->prereqRight = 0;
109996 }else{
109997 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
109999 prereqAll = exprTableUsage(pMaskSet, pExpr);
110000 if( ExprHasProperty(pExpr, EP_FromJoin) ){
110001 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
110002 prereqAll |= x;
110003 extraRight = x-1; /* ON clause terms may not be used with an index
110004 ** on left table of a LEFT JOIN. Ticket #3015 */
110006 pTerm->prereqAll = prereqAll;
110007 pTerm->leftCursor = -1;
110008 pTerm->iParent = -1;
110009 pTerm->eOperator = 0;
110010 if( allowedOp(op) ){
110011 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
110012 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
110013 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
110014 if( pLeft->op==TK_COLUMN ){
110015 pTerm->leftCursor = pLeft->iTable;
110016 pTerm->u.leftColumn = pLeft->iColumn;
110017 pTerm->eOperator = operatorMask(op) & opMask;
110019 if( pRight && pRight->op==TK_COLUMN ){
110020 WhereTerm *pNew;
110021 Expr *pDup;
110022 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
110023 if( pTerm->leftCursor>=0 ){
110024 int idxNew;
110025 pDup = sqlite3ExprDup(db, pExpr, 0);
110026 if( db->mallocFailed ){
110027 sqlite3ExprDelete(db, pDup);
110028 return;
110030 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
110031 if( idxNew==0 ) return;
110032 pNew = &pWC->a[idxNew];
110033 pNew->iParent = idxTerm;
110034 pTerm = &pWC->a[idxTerm];
110035 pTerm->nChild = 1;
110036 pTerm->wtFlags |= TERM_COPIED;
110037 if( pExpr->op==TK_EQ
110038 && !ExprHasProperty(pExpr, EP_FromJoin)
110039 && OptimizationEnabled(db, SQLITE_Transitive)
110041 pTerm->eOperator |= WO_EQUIV;
110042 eExtraOp = WO_EQUIV;
110044 }else{
110045 pDup = pExpr;
110046 pNew = pTerm;
110048 exprCommute(pParse, pDup);
110049 pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
110050 pNew->leftCursor = pLeft->iTable;
110051 pNew->u.leftColumn = pLeft->iColumn;
110052 testcase( (prereqLeft | extraRight) != prereqLeft );
110053 pNew->prereqRight = prereqLeft | extraRight;
110054 pNew->prereqAll = prereqAll;
110055 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
110059 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
110060 /* If a term is the BETWEEN operator, create two new virtual terms
110061 ** that define the range that the BETWEEN implements. For example:
110063 ** a BETWEEN b AND c
110065 ** is converted into:
110067 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
110069 ** The two new terms are added onto the end of the WhereClause object.
110070 ** The new terms are "dynamic" and are children of the original BETWEEN
110071 ** term. That means that if the BETWEEN term is coded, the children are
110072 ** skipped. Or, if the children are satisfied by an index, the original
110073 ** BETWEEN term is skipped.
110075 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
110076 ExprList *pList = pExpr->x.pList;
110077 int i;
110078 static const u8 ops[] = {TK_GE, TK_LE};
110079 assert( pList!=0 );
110080 assert( pList->nExpr==2 );
110081 for(i=0; i<2; i++){
110082 Expr *pNewExpr;
110083 int idxNew;
110084 pNewExpr = sqlite3PExpr(pParse, ops[i],
110085 sqlite3ExprDup(db, pExpr->pLeft, 0),
110086 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
110087 transferJoinMarkings(pNewExpr, pExpr);
110088 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
110089 testcase( idxNew==0 );
110090 exprAnalyze(pSrc, pWC, idxNew);
110091 pTerm = &pWC->a[idxTerm];
110092 pWC->a[idxNew].iParent = idxTerm;
110094 pTerm->nChild = 2;
110096 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
110098 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
110099 /* Analyze a term that is composed of two or more subterms connected by
110100 ** an OR operator.
110102 else if( pExpr->op==TK_OR ){
110103 assert( pWC->op==TK_AND );
110104 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
110105 pTerm = &pWC->a[idxTerm];
110107 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
110109 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
110110 /* Add constraints to reduce the search space on a LIKE or GLOB
110111 ** operator.
110113 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
110115 ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
110117 ** The last character of the prefix "abc" is incremented to form the
110118 ** termination condition "abd".
110120 if( pWC->op==TK_AND
110121 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
110123 Expr *pLeft; /* LHS of LIKE/GLOB operator */
110124 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
110125 Expr *pNewExpr1;
110126 Expr *pNewExpr2;
110127 int idxNew1;
110128 int idxNew2;
110129 Token sCollSeqName; /* Name of collating sequence */
110131 pLeft = pExpr->x.pList->a[1].pExpr;
110132 pStr2 = sqlite3ExprDup(db, pStr1, 0);
110133 if( !db->mallocFailed ){
110134 u8 c, *pC; /* Last character before the first wildcard */
110135 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
110136 c = *pC;
110137 if( noCase ){
110138 /* The point is to increment the last character before the first
110139 ** wildcard. But if we increment '@', that will push it into the
110140 ** alphabetic range where case conversions will mess up the
110141 ** inequality. To avoid this, make sure to also run the full
110142 ** LIKE on all candidate expressions by clearing the isComplete flag
110144 if( c=='A'-1 ) isComplete = 0;
110145 c = sqlite3UpperToLower[c];
110147 *pC = c + 1;
110149 sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
110150 sCollSeqName.n = 6;
110151 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
110152 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
110153 sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
110154 pStr1, 0);
110155 transferJoinMarkings(pNewExpr1, pExpr);
110156 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
110157 testcase( idxNew1==0 );
110158 exprAnalyze(pSrc, pWC, idxNew1);
110159 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
110160 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
110161 sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
110162 pStr2, 0);
110163 transferJoinMarkings(pNewExpr2, pExpr);
110164 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
110165 testcase( idxNew2==0 );
110166 exprAnalyze(pSrc, pWC, idxNew2);
110167 pTerm = &pWC->a[idxTerm];
110168 if( isComplete ){
110169 pWC->a[idxNew1].iParent = idxTerm;
110170 pWC->a[idxNew2].iParent = idxTerm;
110171 pTerm->nChild = 2;
110174 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
110176 #ifndef SQLITE_OMIT_VIRTUALTABLE
110177 /* Add a WO_MATCH auxiliary term to the constraint set if the
110178 ** current expression is of the form: column MATCH expr.
110179 ** This information is used by the xBestIndex methods of
110180 ** virtual tables. The native query optimizer does not attempt
110181 ** to do anything with MATCH functions.
110183 if( isMatchOfColumn(pExpr) ){
110184 int idxNew;
110185 Expr *pRight, *pLeft;
110186 WhereTerm *pNewTerm;
110187 Bitmask prereqColumn, prereqExpr;
110189 pRight = pExpr->x.pList->a[0].pExpr;
110190 pLeft = pExpr->x.pList->a[1].pExpr;
110191 prereqExpr = exprTableUsage(pMaskSet, pRight);
110192 prereqColumn = exprTableUsage(pMaskSet, pLeft);
110193 if( (prereqExpr & prereqColumn)==0 ){
110194 Expr *pNewExpr;
110195 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
110196 0, sqlite3ExprDup(db, pRight, 0), 0);
110197 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
110198 testcase( idxNew==0 );
110199 pNewTerm = &pWC->a[idxNew];
110200 pNewTerm->prereqRight = prereqExpr;
110201 pNewTerm->leftCursor = pLeft->iTable;
110202 pNewTerm->u.leftColumn = pLeft->iColumn;
110203 pNewTerm->eOperator = WO_MATCH;
110204 pNewTerm->iParent = idxTerm;
110205 pTerm = &pWC->a[idxTerm];
110206 pTerm->nChild = 1;
110207 pTerm->wtFlags |= TERM_COPIED;
110208 pNewTerm->prereqAll = pTerm->prereqAll;
110211 #endif /* SQLITE_OMIT_VIRTUALTABLE */
110213 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110214 /* When sqlite_stat3 histogram data is available an operator of the
110215 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
110216 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
110217 ** virtual term of that form.
110219 ** Note that the virtual term must be tagged with TERM_VNULL. This
110220 ** TERM_VNULL tag will suppress the not-null check at the beginning
110221 ** of the loop. Without the TERM_VNULL flag, the not-null check at
110222 ** the start of the loop will prevent any results from being returned.
110224 if( pExpr->op==TK_NOTNULL
110225 && pExpr->pLeft->op==TK_COLUMN
110226 && pExpr->pLeft->iColumn>=0
110227 && OptimizationEnabled(db, SQLITE_Stat3)
110229 Expr *pNewExpr;
110230 Expr *pLeft = pExpr->pLeft;
110231 int idxNew;
110232 WhereTerm *pNewTerm;
110234 pNewExpr = sqlite3PExpr(pParse, TK_GT,
110235 sqlite3ExprDup(db, pLeft, 0),
110236 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
110238 idxNew = whereClauseInsert(pWC, pNewExpr,
110239 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
110240 if( idxNew ){
110241 pNewTerm = &pWC->a[idxNew];
110242 pNewTerm->prereqRight = 0;
110243 pNewTerm->leftCursor = pLeft->iTable;
110244 pNewTerm->u.leftColumn = pLeft->iColumn;
110245 pNewTerm->eOperator = WO_GT;
110246 pNewTerm->iParent = idxTerm;
110247 pTerm = &pWC->a[idxTerm];
110248 pTerm->nChild = 1;
110249 pTerm->wtFlags |= TERM_COPIED;
110250 pNewTerm->prereqAll = pTerm->prereqAll;
110253 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
110255 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
110256 ** an index for tables to the left of the join.
110258 pTerm->prereqRight |= extraRight;
110262 ** This function searches pList for a entry that matches the iCol-th column
110263 ** of index pIdx.
110265 ** If such an expression is found, its index in pList->a[] is returned. If
110266 ** no expression is found, -1 is returned.
110268 static int findIndexCol(
110269 Parse *pParse, /* Parse context */
110270 ExprList *pList, /* Expression list to search */
110271 int iBase, /* Cursor for table associated with pIdx */
110272 Index *pIdx, /* Index to match column of */
110273 int iCol /* Column of index to match */
110275 int i;
110276 const char *zColl = pIdx->azColl[iCol];
110278 for(i=0; i<pList->nExpr; i++){
110279 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
110280 if( p->op==TK_COLUMN
110281 && p->iColumn==pIdx->aiColumn[iCol]
110282 && p->iTable==iBase
110284 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
110285 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
110286 return i;
110291 return -1;
110295 ** Return true if the DISTINCT expression-list passed as the third argument
110296 ** is redundant.
110298 ** A DISTINCT list is redundant if the database contains some subset of
110299 ** columns that are unique and non-null.
110301 static int isDistinctRedundant(
110302 Parse *pParse, /* Parsing context */
110303 SrcList *pTabList, /* The FROM clause */
110304 WhereClause *pWC, /* The WHERE clause */
110305 ExprList *pDistinct /* The result set that needs to be DISTINCT */
110307 Table *pTab;
110308 Index *pIdx;
110309 int i;
110310 int iBase;
110312 /* If there is more than one table or sub-select in the FROM clause of
110313 ** this query, then it will not be possible to show that the DISTINCT
110314 ** clause is redundant. */
110315 if( pTabList->nSrc!=1 ) return 0;
110316 iBase = pTabList->a[0].iCursor;
110317 pTab = pTabList->a[0].pTab;
110319 /* If any of the expressions is an IPK column on table iBase, then return
110320 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
110321 ** current SELECT is a correlated sub-query.
110323 for(i=0; i<pDistinct->nExpr; i++){
110324 Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
110325 if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
110328 /* Loop through all indices on the table, checking each to see if it makes
110329 ** the DISTINCT qualifier redundant. It does so if:
110331 ** 1. The index is itself UNIQUE, and
110333 ** 2. All of the columns in the index are either part of the pDistinct
110334 ** list, or else the WHERE clause contains a term of the form "col=X",
110335 ** where X is a constant value. The collation sequences of the
110336 ** comparison and select-list expressions must match those of the index.
110338 ** 3. All of those index columns for which the WHERE clause does not
110339 ** contain a "col=X" term are subject to a NOT NULL constraint.
110341 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
110342 if( pIdx->onError==OE_None ) continue;
110343 for(i=0; i<pIdx->nKeyCol; i++){
110344 i16 iCol = pIdx->aiColumn[i];
110345 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
110346 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
110347 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
110348 break;
110352 if( i==pIdx->nKeyCol ){
110353 /* This index implies that the DISTINCT qualifier is redundant. */
110354 return 1;
110358 return 0;
110363 ** Estimate the logarithm of the input value to base 2.
110365 static LogEst estLog(LogEst N){
110366 LogEst x = sqlite3LogEst(N);
110367 return x>33 ? x - 33 : 0;
110371 ** Two routines for printing the content of an sqlite3_index_info
110372 ** structure. Used for testing and debugging only. If neither
110373 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
110374 ** are no-ops.
110376 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
110377 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
110378 int i;
110379 if( !sqlite3WhereTrace ) return;
110380 for(i=0; i<p->nConstraint; i++){
110381 sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
110383 p->aConstraint[i].iColumn,
110384 p->aConstraint[i].iTermOffset,
110385 p->aConstraint[i].op,
110386 p->aConstraint[i].usable);
110388 for(i=0; i<p->nOrderBy; i++){
110389 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
110391 p->aOrderBy[i].iColumn,
110392 p->aOrderBy[i].desc);
110395 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
110396 int i;
110397 if( !sqlite3WhereTrace ) return;
110398 for(i=0; i<p->nConstraint; i++){
110399 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
110401 p->aConstraintUsage[i].argvIndex,
110402 p->aConstraintUsage[i].omit);
110404 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
110405 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
110406 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
110407 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
110408 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
110410 #else
110411 #define TRACE_IDX_INPUTS(A)
110412 #define TRACE_IDX_OUTPUTS(A)
110413 #endif
110415 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
110417 ** Return TRUE if the WHERE clause term pTerm is of a form where it
110418 ** could be used with an index to access pSrc, assuming an appropriate
110419 ** index existed.
110421 static int termCanDriveIndex(
110422 WhereTerm *pTerm, /* WHERE clause term to check */
110423 struct SrcList_item *pSrc, /* Table we are trying to access */
110424 Bitmask notReady /* Tables in outer loops of the join */
110426 char aff;
110427 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
110428 if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
110429 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
110430 if( pTerm->u.leftColumn<0 ) return 0;
110431 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
110432 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
110433 return 1;
110435 #endif
110438 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
110440 ** Generate code to construct the Index object for an automatic index
110441 ** and to set up the WhereLevel object pLevel so that the code generator
110442 ** makes use of the automatic index.
110444 static void constructAutomaticIndex(
110445 Parse *pParse, /* The parsing context */
110446 WhereClause *pWC, /* The WHERE clause */
110447 struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
110448 Bitmask notReady, /* Mask of cursors that are not available */
110449 WhereLevel *pLevel /* Write new index here */
110451 int nKeyCol; /* Number of columns in the constructed index */
110452 WhereTerm *pTerm; /* A single term of the WHERE clause */
110453 WhereTerm *pWCEnd; /* End of pWC->a[] */
110454 Index *pIdx; /* Object describing the transient index */
110455 Vdbe *v; /* Prepared statement under construction */
110456 int addrInit; /* Address of the initialization bypass jump */
110457 Table *pTable; /* The table being indexed */
110458 int addrTop; /* Top of the index fill loop */
110459 int regRecord; /* Register holding an index record */
110460 int n; /* Column counter */
110461 int i; /* Loop counter */
110462 int mxBitCol; /* Maximum column in pSrc->colUsed */
110463 CollSeq *pColl; /* Collating sequence to on a column */
110464 WhereLoop *pLoop; /* The Loop object */
110465 char *zNotUsed; /* Extra space on the end of pIdx */
110466 Bitmask idxCols; /* Bitmap of columns used for indexing */
110467 Bitmask extraCols; /* Bitmap of additional columns */
110468 u8 sentWarning = 0; /* True if a warnning has been issued */
110470 /* Generate code to skip over the creation and initialization of the
110471 ** transient index on 2nd and subsequent iterations of the loop. */
110472 v = pParse->pVdbe;
110473 assert( v!=0 );
110474 addrInit = sqlite3CodeOnce(pParse);
110476 /* Count the number of columns that will be added to the index
110477 ** and used to match WHERE clause constraints */
110478 nKeyCol = 0;
110479 pTable = pSrc->pTab;
110480 pWCEnd = &pWC->a[pWC->nTerm];
110481 pLoop = pLevel->pWLoop;
110482 idxCols = 0;
110483 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
110484 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
110485 int iCol = pTerm->u.leftColumn;
110486 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
110487 testcase( iCol==BMS );
110488 testcase( iCol==BMS-1 );
110489 if( !sentWarning ){
110490 sqlite3_log(SQLITE_WARNING_AUTOINDEX,
110491 "automatic index on %s(%s)", pTable->zName,
110492 pTable->aCol[iCol].zName);
110493 sentWarning = 1;
110495 if( (idxCols & cMask)==0 ){
110496 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
110497 pLoop->aLTerm[nKeyCol++] = pTerm;
110498 idxCols |= cMask;
110502 assert( nKeyCol>0 );
110503 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
110504 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
110505 | WHERE_AUTO_INDEX;
110507 /* Count the number of additional columns needed to create a
110508 ** covering index. A "covering index" is an index that contains all
110509 ** columns that are needed by the query. With a covering index, the
110510 ** original table never needs to be accessed. Automatic indices must
110511 ** be a covering index because the index will not be updated if the
110512 ** original table changes and the index and table cannot both be used
110513 ** if they go out of sync.
110515 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
110516 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
110517 testcase( pTable->nCol==BMS-1 );
110518 testcase( pTable->nCol==BMS-2 );
110519 for(i=0; i<mxBitCol; i++){
110520 if( extraCols & MASKBIT(i) ) nKeyCol++;
110522 if( pSrc->colUsed & MASKBIT(BMS-1) ){
110523 nKeyCol += pTable->nCol - BMS + 1;
110525 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
110527 /* Construct the Index object to describe this index */
110528 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
110529 if( pIdx==0 ) return;
110530 pLoop->u.btree.pIndex = pIdx;
110531 pIdx->zName = "auto-index";
110532 pIdx->pTable = pTable;
110533 n = 0;
110534 idxCols = 0;
110535 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
110536 if( termCanDriveIndex(pTerm, pSrc, notReady) ){
110537 int iCol = pTerm->u.leftColumn;
110538 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
110539 testcase( iCol==BMS-1 );
110540 testcase( iCol==BMS );
110541 if( (idxCols & cMask)==0 ){
110542 Expr *pX = pTerm->pExpr;
110543 idxCols |= cMask;
110544 pIdx->aiColumn[n] = pTerm->u.leftColumn;
110545 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
110546 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
110551 assert( (u32)n==pLoop->u.btree.nEq );
110553 /* Add additional columns needed to make the automatic index into
110554 ** a covering index */
110555 for(i=0; i<mxBitCol; i++){
110556 if( extraCols & MASKBIT(i) ){
110557 pIdx->aiColumn[n] = i;
110558 pIdx->azColl[n] = "BINARY";
110562 if( pSrc->colUsed & MASKBIT(BMS-1) ){
110563 for(i=BMS-1; i<pTable->nCol; i++){
110564 pIdx->aiColumn[n] = i;
110565 pIdx->azColl[n] = "BINARY";
110569 assert( n==nKeyCol );
110570 pIdx->aiColumn[n] = -1;
110571 pIdx->azColl[n] = "BINARY";
110573 /* Create the automatic index */
110574 assert( pLevel->iIdxCur>=0 );
110575 pLevel->iIdxCur = pParse->nTab++;
110576 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
110577 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
110578 VdbeComment((v, "for %s", pTable->zName));
110580 /* Fill the automatic index with content */
110581 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
110582 regRecord = sqlite3GetTempReg(pParse);
110583 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
110584 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
110585 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
110586 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
110587 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
110588 sqlite3VdbeJumpHere(v, addrTop);
110589 sqlite3ReleaseTempReg(pParse, regRecord);
110591 /* Jump here when skipping the initialization */
110592 sqlite3VdbeJumpHere(v, addrInit);
110594 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
110596 #ifndef SQLITE_OMIT_VIRTUALTABLE
110598 ** Allocate and populate an sqlite3_index_info structure. It is the
110599 ** responsibility of the caller to eventually release the structure
110600 ** by passing the pointer returned by this function to sqlite3_free().
110602 static sqlite3_index_info *allocateIndexInfo(
110603 Parse *pParse,
110604 WhereClause *pWC,
110605 struct SrcList_item *pSrc,
110606 ExprList *pOrderBy
110608 int i, j;
110609 int nTerm;
110610 struct sqlite3_index_constraint *pIdxCons;
110611 struct sqlite3_index_orderby *pIdxOrderBy;
110612 struct sqlite3_index_constraint_usage *pUsage;
110613 WhereTerm *pTerm;
110614 int nOrderBy;
110615 sqlite3_index_info *pIdxInfo;
110617 /* Count the number of possible WHERE clause constraints referring
110618 ** to this virtual table */
110619 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
110620 if( pTerm->leftCursor != pSrc->iCursor ) continue;
110621 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
110622 testcase( pTerm->eOperator & WO_IN );
110623 testcase( pTerm->eOperator & WO_ISNULL );
110624 testcase( pTerm->eOperator & WO_ALL );
110625 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
110626 if( pTerm->wtFlags & TERM_VNULL ) continue;
110627 nTerm++;
110630 /* If the ORDER BY clause contains only columns in the current
110631 ** virtual table then allocate space for the aOrderBy part of
110632 ** the sqlite3_index_info structure.
110634 nOrderBy = 0;
110635 if( pOrderBy ){
110636 int n = pOrderBy->nExpr;
110637 for(i=0; i<n; i++){
110638 Expr *pExpr = pOrderBy->a[i].pExpr;
110639 if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
110641 if( i==n){
110642 nOrderBy = n;
110646 /* Allocate the sqlite3_index_info structure
110648 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
110649 + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
110650 + sizeof(*pIdxOrderBy)*nOrderBy );
110651 if( pIdxInfo==0 ){
110652 sqlite3ErrorMsg(pParse, "out of memory");
110653 return 0;
110656 /* Initialize the structure. The sqlite3_index_info structure contains
110657 ** many fields that are declared "const" to prevent xBestIndex from
110658 ** changing them. We have to do some funky casting in order to
110659 ** initialize those fields.
110661 pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
110662 pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
110663 pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
110664 *(int*)&pIdxInfo->nConstraint = nTerm;
110665 *(int*)&pIdxInfo->nOrderBy = nOrderBy;
110666 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
110667 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
110668 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
110669 pUsage;
110671 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
110672 u8 op;
110673 if( pTerm->leftCursor != pSrc->iCursor ) continue;
110674 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
110675 testcase( pTerm->eOperator & WO_IN );
110676 testcase( pTerm->eOperator & WO_ISNULL );
110677 testcase( pTerm->eOperator & WO_ALL );
110678 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
110679 if( pTerm->wtFlags & TERM_VNULL ) continue;
110680 pIdxCons[j].iColumn = pTerm->u.leftColumn;
110681 pIdxCons[j].iTermOffset = i;
110682 op = (u8)pTerm->eOperator & WO_ALL;
110683 if( op==WO_IN ) op = WO_EQ;
110684 pIdxCons[j].op = op;
110685 /* The direct assignment in the previous line is possible only because
110686 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
110687 ** following asserts verify this fact. */
110688 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
110689 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
110690 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
110691 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
110692 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
110693 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
110694 assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
110697 for(i=0; i<nOrderBy; i++){
110698 Expr *pExpr = pOrderBy->a[i].pExpr;
110699 pIdxOrderBy[i].iColumn = pExpr->iColumn;
110700 pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
110703 return pIdxInfo;
110707 ** The table object reference passed as the second argument to this function
110708 ** must represent a virtual table. This function invokes the xBestIndex()
110709 ** method of the virtual table with the sqlite3_index_info object that
110710 ** comes in as the 3rd argument to this function.
110712 ** If an error occurs, pParse is populated with an error message and a
110713 ** non-zero value is returned. Otherwise, 0 is returned and the output
110714 ** part of the sqlite3_index_info structure is left populated.
110716 ** Whether or not an error is returned, it is the responsibility of the
110717 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
110718 ** that this is required.
110720 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
110721 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
110722 int i;
110723 int rc;
110725 TRACE_IDX_INPUTS(p);
110726 rc = pVtab->pModule->xBestIndex(pVtab, p);
110727 TRACE_IDX_OUTPUTS(p);
110729 if( rc!=SQLITE_OK ){
110730 if( rc==SQLITE_NOMEM ){
110731 pParse->db->mallocFailed = 1;
110732 }else if( !pVtab->zErrMsg ){
110733 sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
110734 }else{
110735 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
110738 sqlite3_free(pVtab->zErrMsg);
110739 pVtab->zErrMsg = 0;
110741 for(i=0; i<p->nConstraint; i++){
110742 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
110743 sqlite3ErrorMsg(pParse,
110744 "table %s: xBestIndex returned an invalid plan", pTab->zName);
110748 return pParse->nErr;
110750 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
110753 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110755 ** Estimate the location of a particular key among all keys in an
110756 ** index. Store the results in aStat as follows:
110758 ** aStat[0] Est. number of rows less than pVal
110759 ** aStat[1] Est. number of rows equal to pVal
110761 ** Return SQLITE_OK on success.
110763 static void whereKeyStats(
110764 Parse *pParse, /* Database connection */
110765 Index *pIdx, /* Index to consider domain of */
110766 UnpackedRecord *pRec, /* Vector of values to consider */
110767 int roundUp, /* Round up if true. Round down if false */
110768 tRowcnt *aStat /* OUT: stats written here */
110770 IndexSample *aSample = pIdx->aSample;
110771 int iCol; /* Index of required stats in anEq[] etc. */
110772 int iMin = 0; /* Smallest sample not yet tested */
110773 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
110774 int iTest; /* Next sample to test */
110775 int res; /* Result of comparison operation */
110777 #ifndef SQLITE_DEBUG
110778 UNUSED_PARAMETER( pParse );
110779 #endif
110780 assert( pRec!=0 );
110781 iCol = pRec->nField - 1;
110782 assert( pIdx->nSample>0 );
110783 assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
110785 iTest = (iMin+i)/2;
110786 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
110787 if( res<0 ){
110788 iMin = iTest+1;
110789 }else{
110790 i = iTest;
110792 }while( res && iMin<i );
110794 #ifdef SQLITE_DEBUG
110795 /* The following assert statements check that the binary search code
110796 ** above found the right answer. This block serves no purpose other
110797 ** than to invoke the asserts. */
110798 if( res==0 ){
110799 /* If (res==0) is true, then sample $i must be equal to pRec */
110800 assert( i<pIdx->nSample );
110801 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
110802 || pParse->db->mallocFailed );
110803 }else{
110804 /* Otherwise, pRec must be smaller than sample $i and larger than
110805 ** sample ($i-1). */
110806 assert( i==pIdx->nSample
110807 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
110808 || pParse->db->mallocFailed );
110809 assert( i==0
110810 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
110811 || pParse->db->mallocFailed );
110813 #endif /* ifdef SQLITE_DEBUG */
110815 /* At this point, aSample[i] is the first sample that is greater than
110816 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
110817 ** than pVal. If aSample[i]==pVal, then res==0.
110819 if( res==0 ){
110820 aStat[0] = aSample[i].anLt[iCol];
110821 aStat[1] = aSample[i].anEq[iCol];
110822 }else{
110823 tRowcnt iLower, iUpper, iGap;
110824 if( i==0 ){
110825 iLower = 0;
110826 iUpper = aSample[0].anLt[iCol];
110827 }else{
110828 iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
110829 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
110831 aStat[1] = (pIdx->nKeyCol>iCol ? pIdx->aAvgEq[iCol] : 1);
110832 if( iLower>=iUpper ){
110833 iGap = 0;
110834 }else{
110835 iGap = iUpper - iLower;
110837 if( roundUp ){
110838 iGap = (iGap*2)/3;
110839 }else{
110840 iGap = iGap/3;
110842 aStat[0] = iLower + iGap;
110845 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
110848 ** This function is used to estimate the number of rows that will be visited
110849 ** by scanning an index for a range of values. The range may have an upper
110850 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
110851 ** and lower bounds are represented by pLower and pUpper respectively. For
110852 ** example, assuming that index p is on t1(a):
110854 ** ... FROM t1 WHERE a > ? AND a < ? ...
110855 ** |_____| |_____|
110856 ** | |
110857 ** pLower pUpper
110859 ** If either of the upper or lower bound is not present, then NULL is passed in
110860 ** place of the corresponding WhereTerm.
110862 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
110863 ** column subject to the range constraint. Or, equivalently, the number of
110864 ** equality constraints optimized by the proposed index scan. For example,
110865 ** assuming index p is on t1(a, b), and the SQL query is:
110867 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
110869 ** then nEq is set to 1 (as the range restricted column, b, is the second
110870 ** left-most column of the index). Or, if the query is:
110872 ** ... FROM t1 WHERE a > ? AND a < ? ...
110874 ** then nEq is set to 0.
110876 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
110877 ** number of rows that the index scan is expected to visit without
110878 ** considering the range constraints. If nEq is 0, this is the number of
110879 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
110880 ** to account for the range contraints pLower and pUpper.
110882 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
110883 ** used, each range inequality reduces the search space by a factor of 4.
110884 ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
110885 ** rows visited by a factor of 16.
110887 static int whereRangeScanEst(
110888 Parse *pParse, /* Parsing & code generating context */
110889 WhereLoopBuilder *pBuilder,
110890 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
110891 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
110892 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
110894 int rc = SQLITE_OK;
110895 int nOut = pLoop->nOut;
110896 LogEst nNew;
110898 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110899 Index *p = pLoop->u.btree.pIndex;
110900 int nEq = pLoop->u.btree.nEq;
110902 if( p->nSample>0
110903 && nEq==pBuilder->nRecValid
110904 && nEq<p->nSampleCol
110905 && OptimizationEnabled(pParse->db, SQLITE_Stat3)
110907 UnpackedRecord *pRec = pBuilder->pRec;
110908 tRowcnt a[2];
110909 u8 aff;
110911 /* Variable iLower will be set to the estimate of the number of rows in
110912 ** the index that are less than the lower bound of the range query. The
110913 ** lower bound being the concatenation of $P and $L, where $P is the
110914 ** key-prefix formed by the nEq values matched against the nEq left-most
110915 ** columns of the index, and $L is the value in pLower.
110917 ** Or, if pLower is NULL or $L cannot be extracted from it (because it
110918 ** is not a simple variable or literal value), the lower bound of the
110919 ** range is $P. Due to a quirk in the way whereKeyStats() works, even
110920 ** if $L is available, whereKeyStats() is called for both ($P) and
110921 ** ($P:$L) and the larger of the two returned values used.
110923 ** Similarly, iUpper is to be set to the estimate of the number of rows
110924 ** less than the upper bound of the range query. Where the upper bound
110925 ** is either ($P) or ($P:$U). Again, even if $U is available, both values
110926 ** of iUpper are requested of whereKeyStats() and the smaller used.
110928 tRowcnt iLower;
110929 tRowcnt iUpper;
110931 if( nEq==p->nKeyCol ){
110932 aff = SQLITE_AFF_INTEGER;
110933 }else{
110934 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
110936 /* Determine iLower and iUpper using ($P) only. */
110937 if( nEq==0 ){
110938 iLower = 0;
110939 iUpper = p->aiRowEst[0];
110940 }else{
110941 /* Note: this call could be optimized away - since the same values must
110942 ** have been requested when testing key $P in whereEqualScanEst(). */
110943 whereKeyStats(pParse, p, pRec, 0, a);
110944 iLower = a[0];
110945 iUpper = a[0] + a[1];
110948 /* If possible, improve on the iLower estimate using ($P:$L). */
110949 if( pLower ){
110950 int bOk; /* True if value is extracted from pExpr */
110951 Expr *pExpr = pLower->pExpr->pRight;
110952 assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
110953 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
110954 if( rc==SQLITE_OK && bOk ){
110955 tRowcnt iNew;
110956 whereKeyStats(pParse, p, pRec, 0, a);
110957 iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
110958 if( iNew>iLower ) iLower = iNew;
110959 nOut--;
110963 /* If possible, improve on the iUpper estimate using ($P:$U). */
110964 if( pUpper ){
110965 int bOk; /* True if value is extracted from pExpr */
110966 Expr *pExpr = pUpper->pExpr->pRight;
110967 assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
110968 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
110969 if( rc==SQLITE_OK && bOk ){
110970 tRowcnt iNew;
110971 whereKeyStats(pParse, p, pRec, 1, a);
110972 iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
110973 if( iNew<iUpper ) iUpper = iNew;
110974 nOut--;
110978 pBuilder->pRec = pRec;
110979 if( rc==SQLITE_OK ){
110980 if( iUpper>iLower ){
110981 nNew = sqlite3LogEst(iUpper - iLower);
110982 }else{
110983 nNew = 10; assert( 10==sqlite3LogEst(2) );
110985 if( nNew<nOut ){
110986 nOut = nNew;
110988 pLoop->nOut = (LogEst)nOut;
110989 WHERETRACE(0x10, ("range scan regions: %u..%u est=%d\n",
110990 (u32)iLower, (u32)iUpper, nOut));
110991 return SQLITE_OK;
110994 #else
110995 UNUSED_PARAMETER(pParse);
110996 UNUSED_PARAMETER(pBuilder);
110997 #endif
110998 assert( pLower || pUpper );
110999 /* TUNING: Each inequality constraint reduces the search space 4-fold.
111000 ** A BETWEEN operator, therefore, reduces the search space 16-fold */
111001 nNew = nOut;
111002 if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
111003 nNew -= 20; assert( 20==sqlite3LogEst(4) );
111004 nOut--;
111006 if( pUpper ){
111007 nNew -= 20; assert( 20==sqlite3LogEst(4) );
111008 nOut--;
111010 if( nNew<10 ) nNew = 10;
111011 if( nNew<nOut ) nOut = nNew;
111012 pLoop->nOut = (LogEst)nOut;
111013 return rc;
111016 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
111018 ** Estimate the number of rows that will be returned based on
111019 ** an equality constraint x=VALUE and where that VALUE occurs in
111020 ** the histogram data. This only works when x is the left-most
111021 ** column of an index and sqlite_stat3 histogram data is available
111022 ** for that index. When pExpr==NULL that means the constraint is
111023 ** "x IS NULL" instead of "x=VALUE".
111025 ** Write the estimated row count into *pnRow and return SQLITE_OK.
111026 ** If unable to make an estimate, leave *pnRow unchanged and return
111027 ** non-zero.
111029 ** This routine can fail if it is unable to load a collating sequence
111030 ** required for string comparison, or if unable to allocate memory
111031 ** for a UTF conversion required for comparison. The error is stored
111032 ** in the pParse structure.
111034 static int whereEqualScanEst(
111035 Parse *pParse, /* Parsing & code generating context */
111036 WhereLoopBuilder *pBuilder,
111037 Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
111038 tRowcnt *pnRow /* Write the revised row estimate here */
111040 Index *p = pBuilder->pNew->u.btree.pIndex;
111041 int nEq = pBuilder->pNew->u.btree.nEq;
111042 UnpackedRecord *pRec = pBuilder->pRec;
111043 u8 aff; /* Column affinity */
111044 int rc; /* Subfunction return code */
111045 tRowcnt a[2]; /* Statistics */
111046 int bOk;
111048 assert( nEq>=1 );
111049 assert( nEq<=(p->nKeyCol+1) );
111050 assert( p->aSample!=0 );
111051 assert( p->nSample>0 );
111052 assert( pBuilder->nRecValid<nEq );
111054 /* If values are not available for all fields of the index to the left
111055 ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
111056 if( pBuilder->nRecValid<(nEq-1) ){
111057 return SQLITE_NOTFOUND;
111060 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
111061 ** below would return the same value. */
111062 if( nEq>p->nKeyCol ){
111063 *pnRow = 1;
111064 return SQLITE_OK;
111067 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
111068 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
111069 pBuilder->pRec = pRec;
111070 if( rc!=SQLITE_OK ) return rc;
111071 if( bOk==0 ) return SQLITE_NOTFOUND;
111072 pBuilder->nRecValid = nEq;
111074 whereKeyStats(pParse, p, pRec, 0, a);
111075 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
111076 *pnRow = a[1];
111078 return rc;
111080 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
111082 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
111084 ** Estimate the number of rows that will be returned based on
111085 ** an IN constraint where the right-hand side of the IN operator
111086 ** is a list of values. Example:
111088 ** WHERE x IN (1,2,3,4)
111090 ** Write the estimated row count into *pnRow and return SQLITE_OK.
111091 ** If unable to make an estimate, leave *pnRow unchanged and return
111092 ** non-zero.
111094 ** This routine can fail if it is unable to load a collating sequence
111095 ** required for string comparison, or if unable to allocate memory
111096 ** for a UTF conversion required for comparison. The error is stored
111097 ** in the pParse structure.
111099 static int whereInScanEst(
111100 Parse *pParse, /* Parsing & code generating context */
111101 WhereLoopBuilder *pBuilder,
111102 ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
111103 tRowcnt *pnRow /* Write the revised row estimate here */
111105 Index *p = pBuilder->pNew->u.btree.pIndex;
111106 int nRecValid = pBuilder->nRecValid;
111107 int rc = SQLITE_OK; /* Subfunction return code */
111108 tRowcnt nEst; /* Number of rows for a single term */
111109 tRowcnt nRowEst = 0; /* New estimate of the number of rows */
111110 int i; /* Loop counter */
111112 assert( p->aSample!=0 );
111113 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
111114 nEst = p->aiRowEst[0];
111115 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
111116 nRowEst += nEst;
111117 pBuilder->nRecValid = nRecValid;
111120 if( rc==SQLITE_OK ){
111121 if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
111122 *pnRow = nRowEst;
111123 WHERETRACE(0x10,("IN row estimate: est=%g\n", nRowEst));
111125 assert( pBuilder->nRecValid==nRecValid );
111126 return rc;
111128 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
111131 ** Disable a term in the WHERE clause. Except, do not disable the term
111132 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
111133 ** or USING clause of that join.
111135 ** Consider the term t2.z='ok' in the following queries:
111137 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
111138 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
111139 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
111141 ** The t2.z='ok' is disabled in the in (2) because it originates
111142 ** in the ON clause. The term is disabled in (3) because it is not part
111143 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
111145 ** Disabling a term causes that term to not be tested in the inner loop
111146 ** of the join. Disabling is an optimization. When terms are satisfied
111147 ** by indices, we disable them to prevent redundant tests in the inner
111148 ** loop. We would get the correct results if nothing were ever disabled,
111149 ** but joins might run a little slower. The trick is to disable as much
111150 ** as we can without disabling too much. If we disabled in (1), we'd get
111151 ** the wrong answer. See ticket #813.
111153 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
111154 if( pTerm
111155 && (pTerm->wtFlags & TERM_CODED)==0
111156 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
111157 && (pLevel->notReady & pTerm->prereqAll)==0
111159 pTerm->wtFlags |= TERM_CODED;
111160 if( pTerm->iParent>=0 ){
111161 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
111162 if( (--pOther->nChild)==0 ){
111163 disableTerm(pLevel, pOther);
111170 ** Code an OP_Affinity opcode to apply the column affinity string zAff
111171 ** to the n registers starting at base.
111173 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
111174 ** beginning and end of zAff are ignored. If all entries in zAff are
111175 ** SQLITE_AFF_NONE, then no code gets generated.
111177 ** This routine makes its own copy of zAff so that the caller is free
111178 ** to modify zAff after this routine returns.
111180 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
111181 Vdbe *v = pParse->pVdbe;
111182 if( zAff==0 ){
111183 assert( pParse->db->mallocFailed );
111184 return;
111186 assert( v!=0 );
111188 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
111189 ** and end of the affinity string.
111191 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
111193 base++;
111194 zAff++;
111196 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
111200 /* Code the OP_Affinity opcode if there is anything left to do. */
111201 if( n>0 ){
111202 sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
111203 sqlite3VdbeChangeP4(v, -1, zAff, n);
111204 sqlite3ExprCacheAffinityChange(pParse, base, n);
111210 ** Generate code for a single equality term of the WHERE clause. An equality
111211 ** term can be either X=expr or X IN (...). pTerm is the term to be
111212 ** coded.
111214 ** The current value for the constraint is left in register iReg.
111216 ** For a constraint of the form X=expr, the expression is evaluated and its
111217 ** result is left on the stack. For constraints of the form X IN (...)
111218 ** this routine sets up a loop that will iterate over all values of X.
111220 static int codeEqualityTerm(
111221 Parse *pParse, /* The parsing context */
111222 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
111223 WhereLevel *pLevel, /* The level of the FROM clause we are working on */
111224 int iEq, /* Index of the equality term within this level */
111225 int bRev, /* True for reverse-order IN operations */
111226 int iTarget /* Attempt to leave results in this register */
111228 Expr *pX = pTerm->pExpr;
111229 Vdbe *v = pParse->pVdbe;
111230 int iReg; /* Register holding results */
111232 assert( iTarget>0 );
111233 if( pX->op==TK_EQ ){
111234 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
111235 }else if( pX->op==TK_ISNULL ){
111236 iReg = iTarget;
111237 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
111238 #ifndef SQLITE_OMIT_SUBQUERY
111239 }else{
111240 int eType;
111241 int iTab;
111242 struct InLoop *pIn;
111243 WhereLoop *pLoop = pLevel->pWLoop;
111245 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
111246 && pLoop->u.btree.pIndex!=0
111247 && pLoop->u.btree.pIndex->aSortOrder[iEq]
111249 testcase( iEq==0 );
111250 testcase( bRev );
111251 bRev = !bRev;
111253 assert( pX->op==TK_IN );
111254 iReg = iTarget;
111255 eType = sqlite3FindInIndex(pParse, pX, 0);
111256 if( eType==IN_INDEX_INDEX_DESC ){
111257 testcase( bRev );
111258 bRev = !bRev;
111260 iTab = pX->iTable;
111261 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
111262 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
111263 pLoop->wsFlags |= WHERE_IN_ABLE;
111264 if( pLevel->u.in.nIn==0 ){
111265 pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
111267 pLevel->u.in.nIn++;
111268 pLevel->u.in.aInLoop =
111269 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
111270 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
111271 pIn = pLevel->u.in.aInLoop;
111272 if( pIn ){
111273 pIn += pLevel->u.in.nIn - 1;
111274 pIn->iCur = iTab;
111275 if( eType==IN_INDEX_ROWID ){
111276 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
111277 }else{
111278 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
111280 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
111281 sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
111282 }else{
111283 pLevel->u.in.nIn = 0;
111285 #endif
111287 disableTerm(pLevel, pTerm);
111288 return iReg;
111292 ** Generate code that will evaluate all == and IN constraints for an
111293 ** index scan.
111295 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
111296 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
111297 ** The index has as many as three equality constraints, but in this
111298 ** example, the third "c" value is an inequality. So only two
111299 ** constraints are coded. This routine will generate code to evaluate
111300 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
111301 ** in consecutive registers and the index of the first register is returned.
111303 ** In the example above nEq==2. But this subroutine works for any value
111304 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
111305 ** The only thing it does is allocate the pLevel->iMem memory cell and
111306 ** compute the affinity string.
111308 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
111309 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
111310 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
111311 ** occurs after the nEq quality constraints.
111313 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
111314 ** the index of the first memory cell in that range. The code that
111315 ** calls this routine will use that memory range to store keys for
111316 ** start and termination conditions of the loop.
111317 ** key value of the loop. If one or more IN operators appear, then
111318 ** this routine allocates an additional nEq memory cells for internal
111319 ** use.
111321 ** Before returning, *pzAff is set to point to a buffer containing a
111322 ** copy of the column affinity string of the index allocated using
111323 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
111324 ** with equality constraints that use NONE affinity are set to
111325 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
111327 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
111328 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
111330 ** In the example above, the index on t1(a) has TEXT affinity. But since
111331 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
111332 ** no conversion should be attempted before using a t2.b value as part of
111333 ** a key to search the index. Hence the first byte in the returned affinity
111334 ** string in this example would be set to SQLITE_AFF_NONE.
111336 static int codeAllEqualityTerms(
111337 Parse *pParse, /* Parsing context */
111338 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
111339 int bRev, /* Reverse the order of IN operators */
111340 int nExtraReg, /* Number of extra registers to allocate */
111341 char **pzAff /* OUT: Set to point to affinity string */
111343 u16 nEq; /* The number of == or IN constraints to code */
111344 u16 nSkip; /* Number of left-most columns to skip */
111345 Vdbe *v = pParse->pVdbe; /* The vm under construction */
111346 Index *pIdx; /* The index being used for this loop */
111347 WhereTerm *pTerm; /* A single constraint term */
111348 WhereLoop *pLoop; /* The WhereLoop object */
111349 int j; /* Loop counter */
111350 int regBase; /* Base register */
111351 int nReg; /* Number of registers to allocate */
111352 char *zAff; /* Affinity string to return */
111354 /* This module is only called on query plans that use an index. */
111355 pLoop = pLevel->pWLoop;
111356 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
111357 nEq = pLoop->u.btree.nEq;
111358 nSkip = pLoop->u.btree.nSkip;
111359 pIdx = pLoop->u.btree.pIndex;
111360 assert( pIdx!=0 );
111362 /* Figure out how many memory cells we will need then allocate them.
111364 regBase = pParse->nMem + 1;
111365 nReg = pLoop->u.btree.nEq + nExtraReg;
111366 pParse->nMem += nReg;
111368 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
111369 if( !zAff ){
111370 pParse->db->mallocFailed = 1;
111373 if( nSkip ){
111374 int iIdxCur = pLevel->iIdxCur;
111375 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
111376 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
111377 j = sqlite3VdbeAddOp0(v, OP_Goto);
111378 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLt:OP_SeekGt),
111379 iIdxCur, 0, regBase, nSkip);
111380 sqlite3VdbeJumpHere(v, j);
111381 for(j=0; j<nSkip; j++){
111382 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
111383 assert( pIdx->aiColumn[j]>=0 );
111384 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
111388 /* Evaluate the equality constraints
111390 assert( zAff==0 || (int)strlen(zAff)>=nEq );
111391 for(j=nSkip; j<nEq; j++){
111392 int r1;
111393 pTerm = pLoop->aLTerm[j];
111394 assert( pTerm!=0 );
111395 /* The following testcase is true for indices with redundant columns.
111396 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
111397 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
111398 testcase( pTerm->wtFlags & TERM_VIRTUAL );
111399 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
111400 if( r1!=regBase+j ){
111401 if( nReg==1 ){
111402 sqlite3ReleaseTempReg(pParse, regBase);
111403 regBase = r1;
111404 }else{
111405 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
111408 testcase( pTerm->eOperator & WO_ISNULL );
111409 testcase( pTerm->eOperator & WO_IN );
111410 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
111411 Expr *pRight = pTerm->pExpr->pRight;
111412 sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
111413 if( zAff ){
111414 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
111415 zAff[j] = SQLITE_AFF_NONE;
111417 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
111418 zAff[j] = SQLITE_AFF_NONE;
111423 *pzAff = zAff;
111424 return regBase;
111427 #ifndef SQLITE_OMIT_EXPLAIN
111429 ** This routine is a helper for explainIndexRange() below
111431 ** pStr holds the text of an expression that we are building up one term
111432 ** at a time. This routine adds a new term to the end of the expression.
111433 ** Terms are separated by AND so add the "AND" text for second and subsequent
111434 ** terms only.
111436 static void explainAppendTerm(
111437 StrAccum *pStr, /* The text expression being built */
111438 int iTerm, /* Index of this term. First is zero */
111439 const char *zColumn, /* Name of the column */
111440 const char *zOp /* Name of the operator */
111442 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
111443 sqlite3StrAccumAppendAll(pStr, zColumn);
111444 sqlite3StrAccumAppend(pStr, zOp, 1);
111445 sqlite3StrAccumAppend(pStr, "?", 1);
111449 ** Argument pLevel describes a strategy for scanning table pTab. This
111450 ** function returns a pointer to a string buffer containing a description
111451 ** of the subset of table rows scanned by the strategy in the form of an
111452 ** SQL expression. Or, if all rows are scanned, NULL is returned.
111454 ** For example, if the query:
111456 ** SELECT * FROM t1 WHERE a=1 AND b>2;
111458 ** is run and there is an index on (a, b), then this function returns a
111459 ** string similar to:
111461 ** "a=? AND b>?"
111463 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
111464 ** It is the responsibility of the caller to free the buffer when it is
111465 ** no longer required.
111467 static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
111468 Index *pIndex = pLoop->u.btree.pIndex;
111469 u16 nEq = pLoop->u.btree.nEq;
111470 u16 nSkip = pLoop->u.btree.nSkip;
111471 int i, j;
111472 Column *aCol = pTab->aCol;
111473 i16 *aiColumn = pIndex->aiColumn;
111474 StrAccum txt;
111476 if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
111477 return 0;
111479 sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
111480 txt.db = db;
111481 sqlite3StrAccumAppend(&txt, " (", 2);
111482 for(i=0; i<nEq; i++){
111483 char *z = (i==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[i]].zName;
111484 if( i>=nSkip ){
111485 explainAppendTerm(&txt, i, z, "=");
111486 }else{
111487 if( i ) sqlite3StrAccumAppend(&txt, " AND ", 5);
111488 sqlite3StrAccumAppend(&txt, "ANY(", 4);
111489 sqlite3StrAccumAppendAll(&txt, z);
111490 sqlite3StrAccumAppend(&txt, ")", 1);
111494 j = i;
111495 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
111496 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
111497 explainAppendTerm(&txt, i++, z, ">");
111499 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
111500 char *z = (j==pIndex->nKeyCol ) ? "rowid" : aCol[aiColumn[j]].zName;
111501 explainAppendTerm(&txt, i, z, "<");
111503 sqlite3StrAccumAppend(&txt, ")", 1);
111504 return sqlite3StrAccumFinish(&txt);
111508 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
111509 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
111510 ** record is added to the output to describe the table scan strategy in
111511 ** pLevel.
111513 static void explainOneScan(
111514 Parse *pParse, /* Parse context */
111515 SrcList *pTabList, /* Table list this loop refers to */
111516 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
111517 int iLevel, /* Value for "level" column of output */
111518 int iFrom, /* Value for "from" column of output */
111519 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
111521 #ifndef SQLITE_DEBUG
111522 if( pParse->explain==2 )
111523 #endif
111525 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
111526 Vdbe *v = pParse->pVdbe; /* VM being constructed */
111527 sqlite3 *db = pParse->db; /* Database handle */
111528 char *zMsg; /* Text to add to EQP output */
111529 int iId = pParse->iSelectId; /* Select id (left-most output column) */
111530 int isSearch; /* True for a SEARCH. False for SCAN. */
111531 WhereLoop *pLoop; /* The controlling WhereLoop object */
111532 u32 flags; /* Flags that describe this loop */
111534 pLoop = pLevel->pWLoop;
111535 flags = pLoop->wsFlags;
111536 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
111538 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
111539 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
111540 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
111542 zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
111543 if( pItem->pSelect ){
111544 zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
111545 }else{
111546 zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
111549 if( pItem->zAlias ){
111550 zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
111552 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
111553 && ALWAYS(pLoop->u.btree.pIndex!=0)
111555 char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
111556 zMsg = sqlite3MAppendf(db, zMsg,
111557 ((flags & WHERE_AUTO_INDEX) ?
111558 "%s USING AUTOMATIC %sINDEX%.0s%s" :
111559 "%s USING %sINDEX %s%s"),
111560 zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
111561 pLoop->u.btree.pIndex->zName, zWhere);
111562 sqlite3DbFree(db, zWhere);
111563 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
111564 zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
111566 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
111567 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
111568 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
111569 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
111570 }else if( flags&WHERE_BTM_LIMIT ){
111571 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
111572 }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
111573 zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
111576 #ifndef SQLITE_OMIT_VIRTUALTABLE
111577 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
111578 zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
111579 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
111581 #endif
111582 zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
111583 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
111586 #else
111587 # define explainOneScan(u,v,w,x,y,z)
111588 #endif /* SQLITE_OMIT_EXPLAIN */
111592 ** Generate code for the start of the iLevel-th loop in the WHERE clause
111593 ** implementation described by pWInfo.
111595 static Bitmask codeOneLoopStart(
111596 WhereInfo *pWInfo, /* Complete information about the WHERE clause */
111597 int iLevel, /* Which level of pWInfo->a[] should be coded */
111598 Bitmask notReady /* Which tables are currently available */
111600 int j, k; /* Loop counters */
111601 int iCur; /* The VDBE cursor for the table */
111602 int addrNxt; /* Where to jump to continue with the next IN case */
111603 int omitTable; /* True if we use the index only */
111604 int bRev; /* True if we need to scan in reverse order */
111605 WhereLevel *pLevel; /* The where level to be coded */
111606 WhereLoop *pLoop; /* The WhereLoop object being coded */
111607 WhereClause *pWC; /* Decomposition of the entire WHERE clause */
111608 WhereTerm *pTerm; /* A WHERE clause term */
111609 Parse *pParse; /* Parsing context */
111610 sqlite3 *db; /* Database connection */
111611 Vdbe *v; /* The prepared stmt under constructions */
111612 struct SrcList_item *pTabItem; /* FROM clause term being coded */
111613 int addrBrk; /* Jump here to break out of the loop */
111614 int addrCont; /* Jump here to continue with next cycle */
111615 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
111616 int iReleaseReg = 0; /* Temp register to free before returning */
111618 pParse = pWInfo->pParse;
111619 v = pParse->pVdbe;
111620 pWC = &pWInfo->sWC;
111621 db = pParse->db;
111622 pLevel = &pWInfo->a[iLevel];
111623 pLoop = pLevel->pWLoop;
111624 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
111625 iCur = pTabItem->iCursor;
111626 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
111627 bRev = (pWInfo->revMask>>iLevel)&1;
111628 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
111629 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
111630 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
111632 /* Create labels for the "break" and "continue" instructions
111633 ** for the current loop. Jump to addrBrk to break out of a loop.
111634 ** Jump to cont to go immediately to the next iteration of the
111635 ** loop.
111637 ** When there is an IN operator, we also have a "addrNxt" label that
111638 ** means to continue with the next IN value combination. When
111639 ** there are no IN operators in the constraints, the "addrNxt" label
111640 ** is the same as "addrBrk".
111642 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
111643 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
111645 /* If this is the right table of a LEFT OUTER JOIN, allocate and
111646 ** initialize a memory cell that records if this table matches any
111647 ** row of the left table of the join.
111649 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
111650 pLevel->iLeftJoin = ++pParse->nMem;
111651 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
111652 VdbeComment((v, "init LEFT JOIN no-match flag"));
111655 /* Special case of a FROM clause subquery implemented as a co-routine */
111656 if( pTabItem->viaCoroutine ){
111657 int regYield = pTabItem->regReturn;
111658 sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
111659 pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
111660 VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
111661 sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
111662 pLevel->op = OP_Goto;
111663 }else
111665 #ifndef SQLITE_OMIT_VIRTUALTABLE
111666 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
111667 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
111668 ** to access the data.
111670 int iReg; /* P3 Value for OP_VFilter */
111671 int addrNotFound;
111672 int nConstraint = pLoop->nLTerm;
111674 sqlite3ExprCachePush(pParse);
111675 iReg = sqlite3GetTempRange(pParse, nConstraint+2);
111676 addrNotFound = pLevel->addrBrk;
111677 for(j=0; j<nConstraint; j++){
111678 int iTarget = iReg+j+2;
111679 pTerm = pLoop->aLTerm[j];
111680 if( pTerm==0 ) continue;
111681 if( pTerm->eOperator & WO_IN ){
111682 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
111683 addrNotFound = pLevel->addrNxt;
111684 }else{
111685 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
111688 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
111689 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
111690 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
111691 pLoop->u.vtab.idxStr,
111692 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
111693 pLoop->u.vtab.needFree = 0;
111694 for(j=0; j<nConstraint && j<16; j++){
111695 if( (pLoop->u.vtab.omitMask>>j)&1 ){
111696 disableTerm(pLevel, pLoop->aLTerm[j]);
111699 pLevel->op = OP_VNext;
111700 pLevel->p1 = iCur;
111701 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
111702 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
111703 sqlite3ExprCachePop(pParse, 1);
111704 }else
111705 #endif /* SQLITE_OMIT_VIRTUALTABLE */
111707 if( (pLoop->wsFlags & WHERE_IPK)!=0
111708 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
111710 /* Case 2: We can directly reference a single row using an
111711 ** equality comparison against the ROWID field. Or
111712 ** we reference multiple rows using a "rowid IN (...)"
111713 ** construct.
111715 assert( pLoop->u.btree.nEq==1 );
111716 iReleaseReg = sqlite3GetTempReg(pParse);
111717 pTerm = pLoop->aLTerm[0];
111718 assert( pTerm!=0 );
111719 assert( pTerm->pExpr!=0 );
111720 assert( omitTable==0 );
111721 testcase( pTerm->wtFlags & TERM_VIRTUAL );
111722 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
111723 addrNxt = pLevel->addrNxt;
111724 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
111725 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
111726 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
111727 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
111728 VdbeComment((v, "pk"));
111729 pLevel->op = OP_Noop;
111730 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
111731 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
111733 /* Case 3: We have an inequality comparison against the ROWID field.
111735 int testOp = OP_Noop;
111736 int start;
111737 int memEndValue = 0;
111738 WhereTerm *pStart, *pEnd;
111740 assert( omitTable==0 );
111741 j = 0;
111742 pStart = pEnd = 0;
111743 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
111744 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
111745 assert( pStart!=0 || pEnd!=0 );
111746 if( bRev ){
111747 pTerm = pStart;
111748 pStart = pEnd;
111749 pEnd = pTerm;
111751 if( pStart ){
111752 Expr *pX; /* The expression that defines the start bound */
111753 int r1, rTemp; /* Registers for holding the start boundary */
111755 /* The following constant maps TK_xx codes into corresponding
111756 ** seek opcodes. It depends on a particular ordering of TK_xx
111758 const u8 aMoveOp[] = {
111759 /* TK_GT */ OP_SeekGt,
111760 /* TK_LE */ OP_SeekLe,
111761 /* TK_LT */ OP_SeekLt,
111762 /* TK_GE */ OP_SeekGe
111764 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
111765 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
111766 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
111768 assert( (pStart->wtFlags & TERM_VNULL)==0 );
111769 testcase( pStart->wtFlags & TERM_VIRTUAL );
111770 pX = pStart->pExpr;
111771 assert( pX!=0 );
111772 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
111773 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
111774 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
111775 VdbeComment((v, "pk"));
111776 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
111777 sqlite3ReleaseTempReg(pParse, rTemp);
111778 disableTerm(pLevel, pStart);
111779 }else{
111780 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
111782 if( pEnd ){
111783 Expr *pX;
111784 pX = pEnd->pExpr;
111785 assert( pX!=0 );
111786 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
111787 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
111788 testcase( pEnd->wtFlags & TERM_VIRTUAL );
111789 memEndValue = ++pParse->nMem;
111790 sqlite3ExprCode(pParse, pX->pRight, memEndValue);
111791 if( pX->op==TK_LT || pX->op==TK_GT ){
111792 testOp = bRev ? OP_Le : OP_Ge;
111793 }else{
111794 testOp = bRev ? OP_Lt : OP_Gt;
111796 disableTerm(pLevel, pEnd);
111798 start = sqlite3VdbeCurrentAddr(v);
111799 pLevel->op = bRev ? OP_Prev : OP_Next;
111800 pLevel->p1 = iCur;
111801 pLevel->p2 = start;
111802 assert( pLevel->p5==0 );
111803 if( testOp!=OP_Noop ){
111804 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
111805 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
111806 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
111807 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
111808 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
111810 }else if( pLoop->wsFlags & WHERE_INDEXED ){
111811 /* Case 4: A scan using an index.
111813 ** The WHERE clause may contain zero or more equality
111814 ** terms ("==" or "IN" operators) that refer to the N
111815 ** left-most columns of the index. It may also contain
111816 ** inequality constraints (>, <, >= or <=) on the indexed
111817 ** column that immediately follows the N equalities. Only
111818 ** the right-most column can be an inequality - the rest must
111819 ** use the "==" and "IN" operators. For example, if the
111820 ** index is on (x,y,z), then the following clauses are all
111821 ** optimized:
111823 ** x=5
111824 ** x=5 AND y=10
111825 ** x=5 AND y<10
111826 ** x=5 AND y>5 AND y<10
111827 ** x=5 AND y=5 AND z<=10
111829 ** The z<10 term of the following cannot be used, only
111830 ** the x=5 term:
111832 ** x=5 AND z<10
111834 ** N may be zero if there are inequality constraints.
111835 ** If there are no inequality constraints, then N is at
111836 ** least one.
111838 ** This case is also used when there are no WHERE clause
111839 ** constraints but an index is selected anyway, in order
111840 ** to force the output order to conform to an ORDER BY.
111842 static const u8 aStartOp[] = {
111845 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
111846 OP_Last, /* 3: (!start_constraints && startEq && bRev) */
111847 OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
111848 OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
111849 OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
111850 OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
111852 static const u8 aEndOp[] = {
111853 OP_Noop, /* 0: (!end_constraints) */
111854 OP_IdxGE, /* 1: (end_constraints && !bRev) */
111855 OP_IdxLT /* 2: (end_constraints && bRev) */
111857 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
111858 int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
111859 int regBase; /* Base register holding constraint values */
111860 int r1; /* Temp register */
111861 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
111862 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
111863 int startEq; /* True if range start uses ==, >= or <= */
111864 int endEq; /* True if range end uses ==, >= or <= */
111865 int start_constraints; /* Start of range is constrained */
111866 int nConstraint; /* Number of constraint terms */
111867 Index *pIdx; /* The index we will be using */
111868 int iIdxCur; /* The VDBE cursor for the index */
111869 int nExtraReg = 0; /* Number of extra registers needed */
111870 int op; /* Instruction opcode */
111871 char *zStartAff; /* Affinity for start of range constraint */
111872 char cEndAff = 0; /* Affinity for end of range constraint */
111874 pIdx = pLoop->u.btree.pIndex;
111875 iIdxCur = pLevel->iIdxCur;
111876 assert( nEq>=pLoop->u.btree.nSkip );
111878 /* If this loop satisfies a sort order (pOrderBy) request that
111879 ** was passed to this function to implement a "SELECT min(x) ..."
111880 ** query, then the caller will only allow the loop to run for
111881 ** a single iteration. This means that the first row returned
111882 ** should not have a NULL value stored in 'x'. If column 'x' is
111883 ** the first one after the nEq equality constraints in the index,
111884 ** this requires some special handling.
111886 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
111887 && (pWInfo->bOBSat!=0)
111888 && (pIdx->nKeyCol>nEq)
111890 assert( pLoop->u.btree.nSkip==0 );
111891 isMinQuery = 1;
111892 nExtraReg = 1;
111895 /* Find any inequality constraint terms for the start and end
111896 ** of the range.
111898 j = nEq;
111899 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
111900 pRangeStart = pLoop->aLTerm[j++];
111901 nExtraReg = 1;
111903 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
111904 pRangeEnd = pLoop->aLTerm[j++];
111905 nExtraReg = 1;
111908 /* Generate code to evaluate all constraint terms using == or IN
111909 ** and store the values of those terms in an array of registers
111910 ** starting at regBase.
111912 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
111913 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
111914 if( zStartAff ) cEndAff = zStartAff[nEq];
111915 addrNxt = pLevel->addrNxt;
111917 /* If we are doing a reverse order scan on an ascending index, or
111918 ** a forward order scan on a descending index, interchange the
111919 ** start and end terms (pRangeStart and pRangeEnd).
111921 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
111922 || (bRev && pIdx->nKeyCol==nEq)
111924 SWAP(WhereTerm *, pRangeEnd, pRangeStart);
111927 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
111928 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
111929 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
111930 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
111931 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
111932 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
111933 start_constraints = pRangeStart || nEq>0;
111935 /* Seek the index cursor to the start of the range. */
111936 nConstraint = nEq;
111937 if( pRangeStart ){
111938 Expr *pRight = pRangeStart->pExpr->pRight;
111939 sqlite3ExprCode(pParse, pRight, regBase+nEq);
111940 if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
111941 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
111943 if( zStartAff ){
111944 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
111945 /* Since the comparison is to be performed with no conversions
111946 ** applied to the operands, set the affinity to apply to pRight to
111947 ** SQLITE_AFF_NONE. */
111948 zStartAff[nEq] = SQLITE_AFF_NONE;
111950 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
111951 zStartAff[nEq] = SQLITE_AFF_NONE;
111954 nConstraint++;
111955 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
111956 }else if( isMinQuery ){
111957 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
111958 nConstraint++;
111959 startEq = 0;
111960 start_constraints = 1;
111962 codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
111963 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
111964 assert( op!=0 );
111965 testcase( op==OP_Rewind );
111966 testcase( op==OP_Last );
111967 testcase( op==OP_SeekGt );
111968 testcase( op==OP_SeekGe );
111969 testcase( op==OP_SeekLe );
111970 testcase( op==OP_SeekLt );
111971 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
111973 /* Load the value for the inequality constraint at the end of the
111974 ** range (if any).
111976 nConstraint = nEq;
111977 if( pRangeEnd ){
111978 Expr *pRight = pRangeEnd->pExpr->pRight;
111979 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
111980 sqlite3ExprCode(pParse, pRight, regBase+nEq);
111981 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
111982 sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
111984 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
111985 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
111987 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
111989 nConstraint++;
111990 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
111992 sqlite3DbFree(db, zStartAff);
111994 /* Top of the loop body */
111995 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
111997 /* Check if the index cursor is past the end of the range. */
111998 op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
111999 testcase( op==OP_Noop );
112000 testcase( op==OP_IdxGE );
112001 testcase( op==OP_IdxLT );
112002 if( op!=OP_Noop ){
112003 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
112004 sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
112007 /* If there are inequality constraints, check that the value
112008 ** of the table column that the inequality contrains is not NULL.
112009 ** If it is, jump to the next iteration of the loop.
112011 r1 = sqlite3GetTempReg(pParse);
112012 testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
112013 testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
112014 if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
112015 && (j = pIdx->aiColumn[nEq])>=0
112016 && pIdx->pTable->aCol[j].notNull==0
112017 && (nEq || (pLoop->wsFlags & WHERE_BTM_LIMIT)==0)
112019 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
112020 VdbeComment((v, "%s", pIdx->pTable->aCol[j].zName));
112021 sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
112023 sqlite3ReleaseTempReg(pParse, r1);
112025 /* Seek the table cursor, if required */
112026 disableTerm(pLevel, pRangeStart);
112027 disableTerm(pLevel, pRangeEnd);
112028 if( omitTable ){
112029 /* pIdx is a covering index. No need to access the main table. */
112030 }else if( HasRowid(pIdx->pTable) ){
112031 iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
112032 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
112033 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
112034 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
112035 }else{
112036 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
112037 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
112038 for(j=0; j<pPk->nKeyCol; j++){
112039 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
112040 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
112042 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
112043 iRowidReg, pPk->nKeyCol);
112046 /* Record the instruction used to terminate the loop. Disable
112047 ** WHERE clause terms made redundant by the index range scan.
112049 if( pLoop->wsFlags & WHERE_ONEROW ){
112050 pLevel->op = OP_Noop;
112051 }else if( bRev ){
112052 pLevel->op = OP_Prev;
112053 }else{
112054 pLevel->op = OP_Next;
112056 pLevel->p1 = iIdxCur;
112057 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
112058 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
112059 }else{
112060 assert( pLevel->p5==0 );
112062 }else
112064 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
112065 if( pLoop->wsFlags & WHERE_MULTI_OR ){
112066 /* Case 5: Two or more separately indexed terms connected by OR
112068 ** Example:
112070 ** CREATE TABLE t1(a,b,c,d);
112071 ** CREATE INDEX i1 ON t1(a);
112072 ** CREATE INDEX i2 ON t1(b);
112073 ** CREATE INDEX i3 ON t1(c);
112075 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
112077 ** In the example, there are three indexed terms connected by OR.
112078 ** The top of the loop looks like this:
112080 ** Null 1 # Zero the rowset in reg 1
112082 ** Then, for each indexed term, the following. The arguments to
112083 ** RowSetTest are such that the rowid of the current row is inserted
112084 ** into the RowSet. If it is already present, control skips the
112085 ** Gosub opcode and jumps straight to the code generated by WhereEnd().
112087 ** sqlite3WhereBegin(<term>)
112088 ** RowSetTest # Insert rowid into rowset
112089 ** Gosub 2 A
112090 ** sqlite3WhereEnd()
112092 ** Following the above, code to terminate the loop. Label A, the target
112093 ** of the Gosub above, jumps to the instruction right after the Goto.
112095 ** Null 1 # Zero the rowset in reg 1
112096 ** Goto B # The loop is finished.
112098 ** A: <loop body> # Return data, whatever.
112100 ** Return 2 # Jump back to the Gosub
112102 ** B: <after the loop>
112105 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
112106 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
112107 Index *pCov = 0; /* Potential covering index (or NULL) */
112108 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
112110 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
112111 int regRowset = 0; /* Register for RowSet object */
112112 int regRowid = 0; /* Register holding rowid */
112113 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
112114 int iRetInit; /* Address of regReturn init */
112115 int untestedTerms = 0; /* Some terms not completely tested */
112116 int ii; /* Loop counter */
112117 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
112119 pTerm = pLoop->aLTerm[0];
112120 assert( pTerm!=0 );
112121 assert( pTerm->eOperator & WO_OR );
112122 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
112123 pOrWc = &pTerm->u.pOrInfo->wc;
112124 pLevel->op = OP_Return;
112125 pLevel->p1 = regReturn;
112127 /* Set up a new SrcList in pOrTab containing the table being scanned
112128 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
112129 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
112131 if( pWInfo->nLevel>1 ){
112132 int nNotReady; /* The number of notReady tables */
112133 struct SrcList_item *origSrc; /* Original list of tables */
112134 nNotReady = pWInfo->nLevel - iLevel - 1;
112135 pOrTab = sqlite3StackAllocRaw(db,
112136 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
112137 if( pOrTab==0 ) return notReady;
112138 pOrTab->nAlloc = (u8)(nNotReady + 1);
112139 pOrTab->nSrc = pOrTab->nAlloc;
112140 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
112141 origSrc = pWInfo->pTabList->a;
112142 for(k=1; k<=nNotReady; k++){
112143 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
112145 }else{
112146 pOrTab = pWInfo->pTabList;
112149 /* Initialize the rowset register to contain NULL. An SQL NULL is
112150 ** equivalent to an empty rowset.
112152 ** Also initialize regReturn to contain the address of the instruction
112153 ** immediately following the OP_Return at the bottom of the loop. This
112154 ** is required in a few obscure LEFT JOIN cases where control jumps
112155 ** over the top of the loop into the body of it. In this case the
112156 ** correct response for the end-of-loop code (the OP_Return) is to
112157 ** fall through to the next instruction, just as an OP_Next does if
112158 ** called on an uninitialized cursor.
112160 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
112161 regRowset = ++pParse->nMem;
112162 regRowid = ++pParse->nMem;
112163 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
112165 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
112167 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
112168 ** Then for every term xN, evaluate as the subexpression: xN AND z
112169 ** That way, terms in y that are factored into the disjunction will
112170 ** be picked up by the recursive calls to sqlite3WhereBegin() below.
112172 ** Actually, each subexpression is converted to "xN AND w" where w is
112173 ** the "interesting" terms of z - terms that did not originate in the
112174 ** ON or USING clause of a LEFT JOIN, and terms that are usable as
112175 ** indices.
112177 ** This optimization also only applies if the (x1 OR x2 OR ...) term
112178 ** is not contained in the ON clause of a LEFT JOIN.
112179 ** See ticket http://www.sqlite.org/src/info/f2369304e4
112181 if( pWC->nTerm>1 ){
112182 int iTerm;
112183 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
112184 Expr *pExpr = pWC->a[iTerm].pExpr;
112185 if( &pWC->a[iTerm] == pTerm ) continue;
112186 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
112187 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
112188 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
112189 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
112190 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
112191 pExpr = sqlite3ExprDup(db, pExpr, 0);
112192 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
112194 if( pAndExpr ){
112195 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
112199 for(ii=0; ii<pOrWc->nTerm; ii++){
112200 WhereTerm *pOrTerm = &pOrWc->a[ii];
112201 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
112202 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
112203 Expr *pOrExpr = pOrTerm->pExpr;
112204 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
112205 pAndExpr->pLeft = pOrExpr;
112206 pOrExpr = pAndExpr;
112208 /* Loop through table entries that match term pOrTerm. */
112209 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
112210 WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
112211 WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
112212 assert( pSubWInfo || pParse->nErr || db->mallocFailed );
112213 if( pSubWInfo ){
112214 WhereLoop *pSubLoop;
112215 explainOneScan(
112216 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
112218 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
112219 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
112220 int r;
112221 r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
112222 regRowid, 0);
112223 sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
112224 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
112226 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
112228 /* The pSubWInfo->untestedTerms flag means that this OR term
112229 ** contained one or more AND term from a notReady table. The
112230 ** terms from the notReady table could not be tested and will
112231 ** need to be tested later.
112233 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
112235 /* If all of the OR-connected terms are optimized using the same
112236 ** index, and the index is opened using the same cursor number
112237 ** by each call to sqlite3WhereBegin() made by this loop, it may
112238 ** be possible to use that index as a covering index.
112240 ** If the call to sqlite3WhereBegin() above resulted in a scan that
112241 ** uses an index, and this is either the first OR-connected term
112242 ** processed or the index is the same as that used by all previous
112243 ** terms, set pCov to the candidate covering index. Otherwise, set
112244 ** pCov to NULL to indicate that no candidate covering index will
112245 ** be available.
112247 pSubLoop = pSubWInfo->a[0].pWLoop;
112248 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
112249 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
112250 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
112252 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
112253 pCov = pSubLoop->u.btree.pIndex;
112254 }else{
112255 pCov = 0;
112258 /* Finish the loop through table entries that match term pOrTerm. */
112259 sqlite3WhereEnd(pSubWInfo);
112263 pLevel->u.pCovidx = pCov;
112264 if( pCov ) pLevel->iIdxCur = iCovCur;
112265 if( pAndExpr ){
112266 pAndExpr->pLeft = 0;
112267 sqlite3ExprDelete(db, pAndExpr);
112269 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
112270 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
112271 sqlite3VdbeResolveLabel(v, iLoopBody);
112273 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
112274 if( !untestedTerms ) disableTerm(pLevel, pTerm);
112275 }else
112276 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
112279 /* Case 6: There is no usable index. We must do a complete
112280 ** scan of the entire table.
112282 static const u8 aStep[] = { OP_Next, OP_Prev };
112283 static const u8 aStart[] = { OP_Rewind, OP_Last };
112284 assert( bRev==0 || bRev==1 );
112285 if( pTabItem->isRecursive ){
112286 /* Tables marked isRecursive have only a single row that is stored in
112287 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
112288 pLevel->op = OP_Noop;
112289 }else{
112290 pLevel->op = aStep[bRev];
112291 pLevel->p1 = iCur;
112292 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
112293 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
112297 /* Insert code to test every subexpression that can be completely
112298 ** computed using the current set of tables.
112300 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
112301 Expr *pE;
112302 testcase( pTerm->wtFlags & TERM_VIRTUAL );
112303 testcase( pTerm->wtFlags & TERM_CODED );
112304 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
112305 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
112306 testcase( pWInfo->untestedTerms==0
112307 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
112308 pWInfo->untestedTerms = 1;
112309 continue;
112311 pE = pTerm->pExpr;
112312 assert( pE!=0 );
112313 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
112314 continue;
112316 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
112317 pTerm->wtFlags |= TERM_CODED;
112320 /* Insert code to test for implied constraints based on transitivity
112321 ** of the "==" operator.
112323 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
112324 ** and we are coding the t1 loop and the t2 loop has not yet coded,
112325 ** then we cannot use the "t1.a=t2.b" constraint, but we can code
112326 ** the implied "t1.a=123" constraint.
112328 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
112329 Expr *pE, *pEAlt;
112330 WhereTerm *pAlt;
112331 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
112332 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
112333 if( pTerm->leftCursor!=iCur ) continue;
112334 if( pLevel->iLeftJoin ) continue;
112335 pE = pTerm->pExpr;
112336 assert( !ExprHasProperty(pE, EP_FromJoin) );
112337 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
112338 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
112339 if( pAlt==0 ) continue;
112340 if( pAlt->wtFlags & (TERM_CODED) ) continue;
112341 testcase( pAlt->eOperator & WO_EQ );
112342 testcase( pAlt->eOperator & WO_IN );
112343 VdbeModuleComment((v, "begin transitive constraint"));
112344 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
112345 if( pEAlt ){
112346 *pEAlt = *pAlt->pExpr;
112347 pEAlt->pLeft = pE->pLeft;
112348 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
112349 sqlite3StackFree(db, pEAlt);
112353 /* For a LEFT OUTER JOIN, generate code that will record the fact that
112354 ** at least one row of the right table has matched the left table.
112356 if( pLevel->iLeftJoin ){
112357 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
112358 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
112359 VdbeComment((v, "record LEFT JOIN hit"));
112360 sqlite3ExprCacheClear(pParse);
112361 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
112362 testcase( pTerm->wtFlags & TERM_VIRTUAL );
112363 testcase( pTerm->wtFlags & TERM_CODED );
112364 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
112365 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
112366 assert( pWInfo->untestedTerms );
112367 continue;
112369 assert( pTerm->pExpr );
112370 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
112371 pTerm->wtFlags |= TERM_CODED;
112374 sqlite3ReleaseTempReg(pParse, iReleaseReg);
112376 return pLevel->notReady;
112379 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
112381 ** Generate "Explanation" text for a WhereTerm.
112383 static void whereExplainTerm(Vdbe *v, WhereTerm *pTerm){
112384 char zType[4];
112385 memcpy(zType, "...", 4);
112386 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
112387 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
112388 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
112389 sqlite3ExplainPrintf(v, "%s ", zType);
112390 sqlite3ExplainExpr(v, pTerm->pExpr);
112392 #endif /* WHERETRACE_ENABLED && SQLITE_ENABLE_TREE_EXPLAIN */
112395 #ifdef WHERETRACE_ENABLED
112397 ** Print a WhereLoop object for debugging purposes
112399 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
112400 WhereInfo *pWInfo = pWC->pWInfo;
112401 int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
112402 struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
112403 Table *pTab = pItem->pTab;
112404 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
112405 p->iTab, nb, p->maskSelf, nb, p->prereq);
112406 sqlite3DebugPrintf(" %12s",
112407 pItem->zAlias ? pItem->zAlias : pTab->zName);
112408 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
112409 const char *zName;
112410 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
112411 if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
112412 int i = sqlite3Strlen30(zName) - 1;
112413 while( zName[i]!='_' ) i--;
112414 zName += i;
112416 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
112417 }else{
112418 sqlite3DebugPrintf("%20s","");
112420 }else{
112421 char *z;
112422 if( p->u.vtab.idxStr ){
112423 z = sqlite3_mprintf("(%d,\"%s\",%x)",
112424 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
112425 }else{
112426 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
112428 sqlite3DebugPrintf(" %-19s", z);
112429 sqlite3_free(z);
112431 sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
112432 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
112433 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
112434 /* If the 0x100 bit of wheretracing is set, then show all of the constraint
112435 ** expressions in the WhereLoop.aLTerm[] array.
112437 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ /* WHERETRACE 0x100 */
112438 int i;
112439 Vdbe *v = pWInfo->pParse->pVdbe;
112440 sqlite3ExplainBegin(v);
112441 for(i=0; i<p->nLTerm; i++){
112442 WhereTerm *pTerm = p->aLTerm[i];
112443 if( pTerm==0 ) continue;
112444 sqlite3ExplainPrintf(v, " (%d) #%-2d ", i+1, (int)(pTerm-pWC->a));
112445 sqlite3ExplainPush(v);
112446 whereExplainTerm(v, pTerm);
112447 sqlite3ExplainPop(v);
112448 sqlite3ExplainNL(v);
112450 sqlite3ExplainFinish(v);
112451 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
112453 #endif
112455 #endif
112458 ** Convert bulk memory into a valid WhereLoop that can be passed
112459 ** to whereLoopClear harmlessly.
112461 static void whereLoopInit(WhereLoop *p){
112462 p->aLTerm = p->aLTermSpace;
112463 p->nLTerm = 0;
112464 p->nLSlot = ArraySize(p->aLTermSpace);
112465 p->wsFlags = 0;
112469 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
112471 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
112472 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
112473 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
112474 sqlite3_free(p->u.vtab.idxStr);
112475 p->u.vtab.needFree = 0;
112476 p->u.vtab.idxStr = 0;
112477 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
112478 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
112479 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
112480 sqlite3DbFree(db, p->u.btree.pIndex);
112481 p->u.btree.pIndex = 0;
112487 ** Deallocate internal memory used by a WhereLoop object
112489 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
112490 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
112491 whereLoopClearUnion(db, p);
112492 whereLoopInit(p);
112496 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
112498 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
112499 WhereTerm **paNew;
112500 if( p->nLSlot>=n ) return SQLITE_OK;
112501 n = (n+7)&~7;
112502 paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
112503 if( paNew==0 ) return SQLITE_NOMEM;
112504 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
112505 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
112506 p->aLTerm = paNew;
112507 p->nLSlot = n;
112508 return SQLITE_OK;
112512 ** Transfer content from the second pLoop into the first.
112514 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
112515 whereLoopClearUnion(db, pTo);
112516 if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
112517 memset(&pTo->u, 0, sizeof(pTo->u));
112518 return SQLITE_NOMEM;
112520 memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
112521 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
112522 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
112523 pFrom->u.vtab.needFree = 0;
112524 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
112525 pFrom->u.btree.pIndex = 0;
112527 return SQLITE_OK;
112531 ** Delete a WhereLoop object
112533 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
112534 whereLoopClear(db, p);
112535 sqlite3DbFree(db, p);
112539 ** Free a WhereInfo structure
112541 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
112542 if( ALWAYS(pWInfo) ){
112543 whereClauseClear(&pWInfo->sWC);
112544 while( pWInfo->pLoops ){
112545 WhereLoop *p = pWInfo->pLoops;
112546 pWInfo->pLoops = p->pNextLoop;
112547 whereLoopDelete(db, p);
112549 sqlite3DbFree(db, pWInfo);
112554 ** Insert or replace a WhereLoop entry using the template supplied.
112556 ** An existing WhereLoop entry might be overwritten if the new template
112557 ** is better and has fewer dependencies. Or the template will be ignored
112558 ** and no insert will occur if an existing WhereLoop is faster and has
112559 ** fewer dependencies than the template. Otherwise a new WhereLoop is
112560 ** added based on the template.
112562 ** If pBuilder->pOrSet is not NULL then we only care about only the
112563 ** prerequisites and rRun and nOut costs of the N best loops. That
112564 ** information is gathered in the pBuilder->pOrSet object. This special
112565 ** processing mode is used only for OR clause processing.
112567 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
112568 ** still might overwrite similar loops with the new template if the
112569 ** template is better. Loops may be overwritten if the following
112570 ** conditions are met:
112572 ** (1) They have the same iTab.
112573 ** (2) They have the same iSortIdx.
112574 ** (3) The template has same or fewer dependencies than the current loop
112575 ** (4) The template has the same or lower cost than the current loop
112576 ** (5) The template uses more terms of the same index but has no additional
112577 ** dependencies
112579 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
112580 WhereLoop **ppPrev, *p, *pNext = 0;
112581 WhereInfo *pWInfo = pBuilder->pWInfo;
112582 sqlite3 *db = pWInfo->pParse->db;
112584 /* If pBuilder->pOrSet is defined, then only keep track of the costs
112585 ** and prereqs.
112587 if( pBuilder->pOrSet!=0 ){
112588 #if WHERETRACE_ENABLED
112589 u16 n = pBuilder->pOrSet->n;
112590 int x =
112591 #endif
112592 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
112593 pTemplate->nOut);
112594 #if WHERETRACE_ENABLED /* 0x8 */
112595 if( sqlite3WhereTrace & 0x8 ){
112596 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
112597 whereLoopPrint(pTemplate, pBuilder->pWC);
112599 #endif
112600 return SQLITE_OK;
112603 /* Search for an existing WhereLoop to overwrite, or which takes
112604 ** priority over pTemplate.
112606 for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
112607 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
112608 /* If either the iTab or iSortIdx values for two WhereLoop are different
112609 ** then those WhereLoops need to be considered separately. Neither is
112610 ** a candidate to replace the other. */
112611 continue;
112613 /* In the current implementation, the rSetup value is either zero
112614 ** or the cost of building an automatic index (NlogN) and the NlogN
112615 ** is the same for compatible WhereLoops. */
112616 assert( p->rSetup==0 || pTemplate->rSetup==0
112617 || p->rSetup==pTemplate->rSetup );
112619 /* whereLoopAddBtree() always generates and inserts the automatic index
112620 ** case first. Hence compatible candidate WhereLoops never have a larger
112621 ** rSetup. Call this SETUP-INVARIANT */
112622 assert( p->rSetup>=pTemplate->rSetup );
112624 if( (p->prereq & pTemplate->prereq)==p->prereq
112625 && p->rSetup<=pTemplate->rSetup
112626 && p->rRun<=pTemplate->rRun
112627 && p->nOut<=pTemplate->nOut
112629 /* This branch taken when p is equal or better than pTemplate in
112630 ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
112631 ** (4) number of output rows. */
112632 assert( p->rSetup==pTemplate->rSetup );
112633 if( p->prereq==pTemplate->prereq
112634 && p->nLTerm<pTemplate->nLTerm
112635 && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
112636 && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
112637 || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
112639 /* Overwrite an existing WhereLoop with an similar one that uses
112640 ** more terms of the index */
112641 pNext = p->pNextLoop;
112642 break;
112643 }else{
112644 /* pTemplate is not helpful.
112645 ** Return without changing or adding anything */
112646 goto whereLoopInsert_noop;
112649 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
112650 && p->rRun>=pTemplate->rRun
112651 && p->nOut>=pTemplate->nOut
112653 /* Overwrite an existing WhereLoop with a better one: one that is
112654 ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
112655 ** or (4) number of output rows, and is no worse in any of those
112656 ** categories. */
112657 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
112658 pNext = p->pNextLoop;
112659 break;
112663 /* If we reach this point it means that either p[] should be overwritten
112664 ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
112665 ** WhereLoop and insert it.
112667 #if WHERETRACE_ENABLED /* 0x8 */
112668 if( sqlite3WhereTrace & 0x8 ){
112669 if( p!=0 ){
112670 sqlite3DebugPrintf("ins-del: ");
112671 whereLoopPrint(p, pBuilder->pWC);
112673 sqlite3DebugPrintf("ins-new: ");
112674 whereLoopPrint(pTemplate, pBuilder->pWC);
112676 #endif
112677 if( p==0 ){
112678 p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
112679 if( p==0 ) return SQLITE_NOMEM;
112680 whereLoopInit(p);
112682 whereLoopXfer(db, p, pTemplate);
112683 p->pNextLoop = pNext;
112684 *ppPrev = p;
112685 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
112686 Index *pIndex = p->u.btree.pIndex;
112687 if( pIndex && pIndex->tnum==0 ){
112688 p->u.btree.pIndex = 0;
112691 return SQLITE_OK;
112693 /* Jump here if the insert is a no-op */
112694 whereLoopInsert_noop:
112695 #if WHERETRACE_ENABLED /* 0x8 */
112696 if( sqlite3WhereTrace & 0x8 ){
112697 sqlite3DebugPrintf("ins-noop: ");
112698 whereLoopPrint(pTemplate, pBuilder->pWC);
112700 #endif
112701 return SQLITE_OK;
112705 ** Adjust the WhereLoop.nOut value downward to account for terms of the
112706 ** WHERE clause that reference the loop but which are not used by an
112707 ** index.
112709 ** In the current implementation, the first extra WHERE clause term reduces
112710 ** the number of output rows by a factor of 10 and each additional term
112711 ** reduces the number of output rows by sqrt(2).
112713 static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
112714 WhereTerm *pTerm, *pX;
112715 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
112716 int i, j;
112718 if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
112719 return;
112721 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
112722 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
112723 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
112724 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
112725 for(j=pLoop->nLTerm-1; j>=0; j--){
112726 pX = pLoop->aLTerm[j];
112727 if( pX==0 ) continue;
112728 if( pX==pTerm ) break;
112729 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
112731 if( j<0 ) pLoop->nOut += pTerm->truthProb;
112736 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
112737 ** Try to match one more.
112739 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
112740 ** INTEGER PRIMARY KEY.
112742 static int whereLoopAddBtreeIndex(
112743 WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
112744 struct SrcList_item *pSrc, /* FROM clause term being analyzed */
112745 Index *pProbe, /* An index on pSrc */
112746 LogEst nInMul /* log(Number of iterations due to IN) */
112748 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
112749 Parse *pParse = pWInfo->pParse; /* Parsing context */
112750 sqlite3 *db = pParse->db; /* Database connection malloc context */
112751 WhereLoop *pNew; /* Template WhereLoop under construction */
112752 WhereTerm *pTerm; /* A WhereTerm under consideration */
112753 int opMask; /* Valid operators for constraints */
112754 WhereScan scan; /* Iterator for WHERE terms */
112755 Bitmask saved_prereq; /* Original value of pNew->prereq */
112756 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
112757 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
112758 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
112759 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
112760 LogEst saved_nOut; /* Original value of pNew->nOut */
112761 int iCol; /* Index of the column in the table */
112762 int rc = SQLITE_OK; /* Return code */
112763 LogEst nRowEst; /* Estimated index selectivity */
112764 LogEst rLogSize; /* Logarithm of table size */
112765 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
112767 pNew = pBuilder->pNew;
112768 if( db->mallocFailed ) return SQLITE_NOMEM;
112770 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
112771 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
112772 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
112773 opMask = WO_LT|WO_LE;
112774 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
112775 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
112776 }else{
112777 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
112779 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
112781 assert( pNew->u.btree.nEq<=pProbe->nKeyCol );
112782 if( pNew->u.btree.nEq < pProbe->nKeyCol ){
112783 iCol = pProbe->aiColumn[pNew->u.btree.nEq];
112784 nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
112785 if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
112786 }else{
112787 iCol = -1;
112788 nRowEst = 0;
112790 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
112791 opMask, pProbe);
112792 saved_nEq = pNew->u.btree.nEq;
112793 saved_nSkip = pNew->u.btree.nSkip;
112794 saved_nLTerm = pNew->nLTerm;
112795 saved_wsFlags = pNew->wsFlags;
112796 saved_prereq = pNew->prereq;
112797 saved_nOut = pNew->nOut;
112798 pNew->rSetup = 0;
112799 rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
112801 /* Consider using a skip-scan if there are no WHERE clause constraints
112802 ** available for the left-most terms of the index, and if the average
112803 ** number of repeats in the left-most terms is at least 18. The magic
112804 ** number 18 was found by experimentation to be the payoff point where
112805 ** skip-scan become faster than a full-scan.
112807 if( pTerm==0
112808 && saved_nEq==saved_nSkip
112809 && saved_nEq+1<pProbe->nKeyCol
112810 && pProbe->aiRowEst[saved_nEq+1]>=18 /* TUNING: Minimum for skip-scan */
112811 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
112813 LogEst nIter;
112814 pNew->u.btree.nEq++;
112815 pNew->u.btree.nSkip++;
112816 pNew->aLTerm[pNew->nLTerm++] = 0;
112817 pNew->wsFlags |= WHERE_SKIPSCAN;
112818 nIter = sqlite3LogEst(pProbe->aiRowEst[0]/pProbe->aiRowEst[saved_nEq+1]);
112819 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter);
112821 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
112822 int nIn = 0;
112823 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112824 int nRecValid = pBuilder->nRecValid;
112825 #endif
112826 if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
112827 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
112829 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
112831 if( pTerm->prereqRight & pNew->maskSelf ) continue;
112833 assert( pNew->nOut==saved_nOut );
112835 pNew->wsFlags = saved_wsFlags;
112836 pNew->u.btree.nEq = saved_nEq;
112837 pNew->nLTerm = saved_nLTerm;
112838 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
112839 pNew->aLTerm[pNew->nLTerm++] = pTerm;
112840 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
112841 pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
112842 if( pTerm->eOperator & WO_IN ){
112843 Expr *pExpr = pTerm->pExpr;
112844 pNew->wsFlags |= WHERE_COLUMN_IN;
112845 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
112846 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
112847 nIn = 46; assert( 46==sqlite3LogEst(25) );
112848 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
112849 /* "x IN (value, value, ...)" */
112850 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
112852 pNew->rRun += nIn;
112853 pNew->u.btree.nEq++;
112854 pNew->nOut = nRowEst + nInMul + nIn;
112855 }else if( pTerm->eOperator & (WO_EQ) ){
112856 assert(
112857 (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN|WHERE_SKIPSCAN))!=0
112858 || nInMul==0
112860 pNew->wsFlags |= WHERE_COLUMN_EQ;
112861 if( iCol<0
112862 || (pProbe->onError!=OE_None && nInMul==0
112863 && pNew->u.btree.nEq==pProbe->nKeyCol-1)
112865 assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
112866 pNew->wsFlags |= WHERE_ONEROW;
112868 pNew->u.btree.nEq++;
112869 pNew->nOut = nRowEst + nInMul;
112870 }else if( pTerm->eOperator & (WO_ISNULL) ){
112871 pNew->wsFlags |= WHERE_COLUMN_NULL;
112872 pNew->u.btree.nEq++;
112873 /* TUNING: IS NULL selects 2 rows */
112874 nIn = 10; assert( 10==sqlite3LogEst(2) );
112875 pNew->nOut = nRowEst + nInMul + nIn;
112876 }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
112877 testcase( pTerm->eOperator & WO_GT );
112878 testcase( pTerm->eOperator & WO_GE );
112879 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
112880 pBtm = pTerm;
112881 pTop = 0;
112882 }else{
112883 assert( pTerm->eOperator & (WO_LT|WO_LE) );
112884 testcase( pTerm->eOperator & WO_LT );
112885 testcase( pTerm->eOperator & WO_LE );
112886 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
112887 pTop = pTerm;
112888 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
112889 pNew->aLTerm[pNew->nLTerm-2] : 0;
112891 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
112892 /* Adjust nOut and rRun for STAT3 range values */
112893 assert( pNew->nOut==saved_nOut );
112894 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
112896 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112897 if( nInMul==0
112898 && pProbe->nSample
112899 && pNew->u.btree.nEq<=pProbe->nSampleCol
112900 && OptimizationEnabled(db, SQLITE_Stat3)
112902 Expr *pExpr = pTerm->pExpr;
112903 tRowcnt nOut = 0;
112904 if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
112905 testcase( pTerm->eOperator & WO_EQ );
112906 testcase( pTerm->eOperator & WO_ISNULL );
112907 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
112908 }else if( (pTerm->eOperator & WO_IN)
112909 && !ExprHasProperty(pExpr, EP_xIsSelect) ){
112910 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
112912 assert( nOut==0 || rc==SQLITE_OK );
112913 if( nOut ){
112914 pNew->nOut = sqlite3LogEst(nOut);
112915 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
112918 #endif
112919 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
112920 /* Each row involves a step of the index, then a binary search of
112921 ** the main table */
112922 pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
112924 /* Step cost for each output row */
112925 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
112926 whereLoopOutputAdjust(pBuilder->pWC, pNew);
112927 rc = whereLoopInsert(pBuilder, pNew);
112928 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
112929 && pNew->u.btree.nEq<(pProbe->nKeyCol + (pProbe->zName!=0))
112931 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
112933 pNew->nOut = saved_nOut;
112934 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
112935 pBuilder->nRecValid = nRecValid;
112936 #endif
112938 pNew->prereq = saved_prereq;
112939 pNew->u.btree.nEq = saved_nEq;
112940 pNew->u.btree.nSkip = saved_nSkip;
112941 pNew->wsFlags = saved_wsFlags;
112942 pNew->nOut = saved_nOut;
112943 pNew->nLTerm = saved_nLTerm;
112944 return rc;
112948 ** Return True if it is possible that pIndex might be useful in
112949 ** implementing the ORDER BY clause in pBuilder.
112951 ** Return False if pBuilder does not contain an ORDER BY clause or
112952 ** if there is no way for pIndex to be useful in implementing that
112953 ** ORDER BY clause.
112955 static int indexMightHelpWithOrderBy(
112956 WhereLoopBuilder *pBuilder,
112957 Index *pIndex,
112958 int iCursor
112960 ExprList *pOB;
112961 int ii, jj;
112963 if( pIndex->bUnordered ) return 0;
112964 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
112965 for(ii=0; ii<pOB->nExpr; ii++){
112966 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
112967 if( pExpr->op!=TK_COLUMN ) return 0;
112968 if( pExpr->iTable==iCursor ){
112969 for(jj=0; jj<pIndex->nKeyCol; jj++){
112970 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
112974 return 0;
112978 ** Return a bitmask where 1s indicate that the corresponding column of
112979 ** the table is used by an index. Only the first 63 columns are considered.
112981 static Bitmask columnsInIndex(Index *pIdx){
112982 Bitmask m = 0;
112983 int j;
112984 for(j=pIdx->nColumn-1; j>=0; j--){
112985 int x = pIdx->aiColumn[j];
112986 if( x>=0 ){
112987 testcase( x==BMS-1 );
112988 testcase( x==BMS-2 );
112989 if( x<BMS-1 ) m |= MASKBIT(x);
112992 return m;
112995 /* Check to see if a partial index with pPartIndexWhere can be used
112996 ** in the current query. Return true if it can be and false if not.
112998 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
112999 int i;
113000 WhereTerm *pTerm;
113001 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
113002 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
113004 return 0;
113008 ** Add all WhereLoop objects for a single table of the join where the table
113009 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
113010 ** a b-tree table, not a virtual table.
113012 static int whereLoopAddBtree(
113013 WhereLoopBuilder *pBuilder, /* WHERE clause information */
113014 Bitmask mExtra /* Extra prerequesites for using this table */
113016 WhereInfo *pWInfo; /* WHERE analysis context */
113017 Index *pProbe; /* An index we are evaluating */
113018 Index sPk; /* A fake index object for the primary key */
113019 tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
113020 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
113021 SrcList *pTabList; /* The FROM clause */
113022 struct SrcList_item *pSrc; /* The FROM clause btree term to add */
113023 WhereLoop *pNew; /* Template WhereLoop object */
113024 int rc = SQLITE_OK; /* Return code */
113025 int iSortIdx = 1; /* Index number */
113026 int b; /* A boolean value */
113027 LogEst rSize; /* number of rows in the table */
113028 LogEst rLogSize; /* Logarithm of the number of rows in the table */
113029 WhereClause *pWC; /* The parsed WHERE clause */
113030 Table *pTab; /* Table being queried */
113032 pNew = pBuilder->pNew;
113033 pWInfo = pBuilder->pWInfo;
113034 pTabList = pWInfo->pTabList;
113035 pSrc = pTabList->a + pNew->iTab;
113036 pTab = pSrc->pTab;
113037 pWC = pBuilder->pWC;
113038 assert( !IsVirtual(pSrc->pTab) );
113040 if( pSrc->pIndex ){
113041 /* An INDEXED BY clause specifies a particular index to use */
113042 pProbe = pSrc->pIndex;
113043 }else if( !HasRowid(pTab) ){
113044 pProbe = pTab->pIndex;
113045 }else{
113046 /* There is no INDEXED BY clause. Create a fake Index object in local
113047 ** variable sPk to represent the rowid primary key index. Make this
113048 ** fake index the first in a chain of Index objects with all of the real
113049 ** indices to follow */
113050 Index *pFirst; /* First of real indices on the table */
113051 memset(&sPk, 0, sizeof(Index));
113052 sPk.nKeyCol = 1;
113053 sPk.aiColumn = &aiColumnPk;
113054 sPk.aiRowEst = aiRowEstPk;
113055 sPk.onError = OE_Replace;
113056 sPk.pTable = pTab;
113057 aiRowEstPk[0] = pTab->nRowEst;
113058 aiRowEstPk[1] = 1;
113059 pFirst = pSrc->pTab->pIndex;
113060 if( pSrc->notIndexed==0 ){
113061 /* The real indices of the table are only considered if the
113062 ** NOT INDEXED qualifier is omitted from the FROM clause */
113063 sPk.pNext = pFirst;
113065 pProbe = &sPk;
113067 rSize = sqlite3LogEst(pTab->nRowEst);
113068 rLogSize = estLog(rSize);
113070 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
113071 /* Automatic indexes */
113072 if( !pBuilder->pOrSet
113073 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
113074 && pSrc->pIndex==0
113075 && !pSrc->viaCoroutine
113076 && !pSrc->notIndexed
113077 && HasRowid(pTab)
113078 && !pSrc->isCorrelated
113079 && !pSrc->isRecursive
113081 /* Generate auto-index WhereLoops */
113082 WhereTerm *pTerm;
113083 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
113084 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
113085 if( pTerm->prereqRight & pNew->maskSelf ) continue;
113086 if( termCanDriveIndex(pTerm, pSrc, 0) ){
113087 pNew->u.btree.nEq = 1;
113088 pNew->u.btree.nSkip = 0;
113089 pNew->u.btree.pIndex = 0;
113090 pNew->nLTerm = 1;
113091 pNew->aLTerm[0] = pTerm;
113092 /* TUNING: One-time cost for computing the automatic index is
113093 ** approximately 7*N*log2(N) where N is the number of rows in
113094 ** the table being indexed. */
113095 pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
113096 /* TUNING: Each index lookup yields 20 rows in the table. This
113097 ** is more than the usual guess of 10 rows, since we have no way
113098 ** of knowning how selective the index will ultimately be. It would
113099 ** not be unreasonable to make this value much larger. */
113100 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
113101 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
113102 pNew->wsFlags = WHERE_AUTO_INDEX;
113103 pNew->prereq = mExtra | pTerm->prereqRight;
113104 rc = whereLoopInsert(pBuilder, pNew);
113108 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
113110 /* Loop over all indices
113112 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
113113 if( pProbe->pPartIdxWhere!=0
113114 && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
113115 continue; /* Partial index inappropriate for this query */
113117 pNew->u.btree.nEq = 0;
113118 pNew->u.btree.nSkip = 0;
113119 pNew->nLTerm = 0;
113120 pNew->iSortIdx = 0;
113121 pNew->rSetup = 0;
113122 pNew->prereq = mExtra;
113123 pNew->nOut = rSize;
113124 pNew->u.btree.pIndex = pProbe;
113125 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
113126 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
113127 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
113128 if( pProbe->tnum<=0 ){
113129 /* Integer primary key index */
113130 pNew->wsFlags = WHERE_IPK;
113132 /* Full table scan */
113133 pNew->iSortIdx = b ? iSortIdx : 0;
113134 /* TUNING: Cost of full table scan is 3*(N + log2(N)).
113135 ** + The extra 3 factor is to encourage the use of indexed lookups
113136 ** over full scans. FIXME */
113137 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
113138 whereLoopOutputAdjust(pWC, pNew);
113139 rc = whereLoopInsert(pBuilder, pNew);
113140 pNew->nOut = rSize;
113141 if( rc ) break;
113142 }else{
113143 Bitmask m;
113144 if( pProbe->isCovering ){
113145 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
113146 m = 0;
113147 }else{
113148 m = pSrc->colUsed & ~columnsInIndex(pProbe);
113149 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
113152 /* Full scan via index */
113153 if( b
113154 || !HasRowid(pTab)
113155 || ( m==0
113156 && pProbe->bUnordered==0
113157 && (pProbe->szIdxRow<pTab->szTabRow)
113158 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
113159 && sqlite3GlobalConfig.bUseCis
113160 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
113163 pNew->iSortIdx = b ? iSortIdx : 0;
113164 if( m==0 ){
113165 /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
113166 ** + The extra factor K of between 1.1 and 3.0 that depends
113167 ** on the relative sizes of the table and the index. K
113168 ** is smaller for smaller indices, thus favoring them.
113170 pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
113171 (15*pProbe->szIdxRow)/pTab->szTabRow;
113172 }else{
113173 /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
113174 ** which we will simplify to just N*log2(N) */
113175 pNew->rRun = rSize + rLogSize;
113177 whereLoopOutputAdjust(pWC, pNew);
113178 rc = whereLoopInsert(pBuilder, pNew);
113179 pNew->nOut = rSize;
113180 if( rc ) break;
113184 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
113185 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
113186 sqlite3Stat4ProbeFree(pBuilder->pRec);
113187 pBuilder->nRecValid = 0;
113188 pBuilder->pRec = 0;
113189 #endif
113191 /* If there was an INDEXED BY clause, then only that one index is
113192 ** considered. */
113193 if( pSrc->pIndex ) break;
113195 return rc;
113198 #ifndef SQLITE_OMIT_VIRTUALTABLE
113200 ** Add all WhereLoop objects for a table of the join identified by
113201 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
113203 static int whereLoopAddVirtual(
113204 WhereLoopBuilder *pBuilder, /* WHERE clause information */
113205 Bitmask mExtra
113207 WhereInfo *pWInfo; /* WHERE analysis context */
113208 Parse *pParse; /* The parsing context */
113209 WhereClause *pWC; /* The WHERE clause */
113210 struct SrcList_item *pSrc; /* The FROM clause term to search */
113211 Table *pTab;
113212 sqlite3 *db;
113213 sqlite3_index_info *pIdxInfo;
113214 struct sqlite3_index_constraint *pIdxCons;
113215 struct sqlite3_index_constraint_usage *pUsage;
113216 WhereTerm *pTerm;
113217 int i, j;
113218 int iTerm, mxTerm;
113219 int nConstraint;
113220 int seenIn = 0; /* True if an IN operator is seen */
113221 int seenVar = 0; /* True if a non-constant constraint is seen */
113222 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
113223 WhereLoop *pNew;
113224 int rc = SQLITE_OK;
113226 pWInfo = pBuilder->pWInfo;
113227 pParse = pWInfo->pParse;
113228 db = pParse->db;
113229 pWC = pBuilder->pWC;
113230 pNew = pBuilder->pNew;
113231 pSrc = &pWInfo->pTabList->a[pNew->iTab];
113232 pTab = pSrc->pTab;
113233 assert( IsVirtual(pTab) );
113234 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
113235 if( pIdxInfo==0 ) return SQLITE_NOMEM;
113236 pNew->prereq = 0;
113237 pNew->rSetup = 0;
113238 pNew->wsFlags = WHERE_VIRTUALTABLE;
113239 pNew->nLTerm = 0;
113240 pNew->u.vtab.needFree = 0;
113241 pUsage = pIdxInfo->aConstraintUsage;
113242 nConstraint = pIdxInfo->nConstraint;
113243 if( whereLoopResize(db, pNew, nConstraint) ){
113244 sqlite3DbFree(db, pIdxInfo);
113245 return SQLITE_NOMEM;
113248 for(iPhase=0; iPhase<=3; iPhase++){
113249 if( !seenIn && (iPhase&1)!=0 ){
113250 iPhase++;
113251 if( iPhase>3 ) break;
113253 if( !seenVar && iPhase>1 ) break;
113254 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
113255 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
113256 j = pIdxCons->iTermOffset;
113257 pTerm = &pWC->a[j];
113258 switch( iPhase ){
113259 case 0: /* Constants without IN operator */
113260 pIdxCons->usable = 0;
113261 if( (pTerm->eOperator & WO_IN)!=0 ){
113262 seenIn = 1;
113264 if( pTerm->prereqRight!=0 ){
113265 seenVar = 1;
113266 }else if( (pTerm->eOperator & WO_IN)==0 ){
113267 pIdxCons->usable = 1;
113269 break;
113270 case 1: /* Constants with IN operators */
113271 assert( seenIn );
113272 pIdxCons->usable = (pTerm->prereqRight==0);
113273 break;
113274 case 2: /* Variables without IN */
113275 assert( seenVar );
113276 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
113277 break;
113278 default: /* Variables with IN */
113279 assert( seenVar && seenIn );
113280 pIdxCons->usable = 1;
113281 break;
113284 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
113285 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
113286 pIdxInfo->idxStr = 0;
113287 pIdxInfo->idxNum = 0;
113288 pIdxInfo->needToFreeIdxStr = 0;
113289 pIdxInfo->orderByConsumed = 0;
113290 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
113291 pIdxInfo->estimatedRows = 25;
113292 rc = vtabBestIndex(pParse, pTab, pIdxInfo);
113293 if( rc ) goto whereLoopAddVtab_exit;
113294 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
113295 pNew->prereq = mExtra;
113296 mxTerm = -1;
113297 assert( pNew->nLSlot>=nConstraint );
113298 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
113299 pNew->u.vtab.omitMask = 0;
113300 for(i=0; i<nConstraint; i++, pIdxCons++){
113301 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
113302 j = pIdxCons->iTermOffset;
113303 if( iTerm>=nConstraint
113304 || j<0
113305 || j>=pWC->nTerm
113306 || pNew->aLTerm[iTerm]!=0
113308 rc = SQLITE_ERROR;
113309 sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
113310 goto whereLoopAddVtab_exit;
113312 testcase( iTerm==nConstraint-1 );
113313 testcase( j==0 );
113314 testcase( j==pWC->nTerm-1 );
113315 pTerm = &pWC->a[j];
113316 pNew->prereq |= pTerm->prereqRight;
113317 assert( iTerm<pNew->nLSlot );
113318 pNew->aLTerm[iTerm] = pTerm;
113319 if( iTerm>mxTerm ) mxTerm = iTerm;
113320 testcase( iTerm==15 );
113321 testcase( iTerm==16 );
113322 if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
113323 if( (pTerm->eOperator & WO_IN)!=0 ){
113324 if( pUsage[i].omit==0 ){
113325 /* Do not attempt to use an IN constraint if the virtual table
113326 ** says that the equivalent EQ constraint cannot be safely omitted.
113327 ** If we do attempt to use such a constraint, some rows might be
113328 ** repeated in the output. */
113329 break;
113331 /* A virtual table that is constrained by an IN clause may not
113332 ** consume the ORDER BY clause because (1) the order of IN terms
113333 ** is not necessarily related to the order of output terms and
113334 ** (2) Multiple outputs from a single IN value will not merge
113335 ** together. */
113336 pIdxInfo->orderByConsumed = 0;
113340 if( i>=nConstraint ){
113341 pNew->nLTerm = mxTerm+1;
113342 assert( pNew->nLTerm<=pNew->nLSlot );
113343 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
113344 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
113345 pIdxInfo->needToFreeIdxStr = 0;
113346 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
113347 pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
113348 && pIdxInfo->orderByConsumed);
113349 pNew->rSetup = 0;
113350 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
113351 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
113352 whereLoopInsert(pBuilder, pNew);
113353 if( pNew->u.vtab.needFree ){
113354 sqlite3_free(pNew->u.vtab.idxStr);
113355 pNew->u.vtab.needFree = 0;
113360 whereLoopAddVtab_exit:
113361 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
113362 sqlite3DbFree(db, pIdxInfo);
113363 return rc;
113365 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113368 ** Add WhereLoop entries to handle OR terms. This works for either
113369 ** btrees or virtual tables.
113371 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
113372 WhereInfo *pWInfo = pBuilder->pWInfo;
113373 WhereClause *pWC;
113374 WhereLoop *pNew;
113375 WhereTerm *pTerm, *pWCEnd;
113376 int rc = SQLITE_OK;
113377 int iCur;
113378 WhereClause tempWC;
113379 WhereLoopBuilder sSubBuild;
113380 WhereOrSet sSum, sCur, sPrev;
113381 struct SrcList_item *pItem;
113383 pWC = pBuilder->pWC;
113384 if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
113385 pWCEnd = pWC->a + pWC->nTerm;
113386 pNew = pBuilder->pNew;
113387 memset(&sSum, 0, sizeof(sSum));
113388 pItem = pWInfo->pTabList->a + pNew->iTab;
113389 if( !HasRowid(pItem->pTab) ) return SQLITE_OK;
113390 iCur = pItem->iCursor;
113392 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
113393 if( (pTerm->eOperator & WO_OR)!=0
113394 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
113396 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
113397 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
113398 WhereTerm *pOrTerm;
113399 int once = 1;
113400 int i, j;
113402 sSubBuild = *pBuilder;
113403 sSubBuild.pOrderBy = 0;
113404 sSubBuild.pOrSet = &sCur;
113406 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
113407 if( (pOrTerm->eOperator & WO_AND)!=0 ){
113408 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
113409 }else if( pOrTerm->leftCursor==iCur ){
113410 tempWC.pWInfo = pWC->pWInfo;
113411 tempWC.pOuter = pWC;
113412 tempWC.op = TK_AND;
113413 tempWC.nTerm = 1;
113414 tempWC.a = pOrTerm;
113415 sSubBuild.pWC = &tempWC;
113416 }else{
113417 continue;
113419 sCur.n = 0;
113420 #ifndef SQLITE_OMIT_VIRTUALTABLE
113421 if( IsVirtual(pItem->pTab) ){
113422 rc = whereLoopAddVirtual(&sSubBuild, mExtra);
113423 }else
113424 #endif
113426 rc = whereLoopAddBtree(&sSubBuild, mExtra);
113428 assert( rc==SQLITE_OK || sCur.n==0 );
113429 if( sCur.n==0 ){
113430 sSum.n = 0;
113431 break;
113432 }else if( once ){
113433 whereOrMove(&sSum, &sCur);
113434 once = 0;
113435 }else{
113436 whereOrMove(&sPrev, &sSum);
113437 sSum.n = 0;
113438 for(i=0; i<sPrev.n; i++){
113439 for(j=0; j<sCur.n; j++){
113440 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
113441 sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
113442 sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
113447 pNew->nLTerm = 1;
113448 pNew->aLTerm[0] = pTerm;
113449 pNew->wsFlags = WHERE_MULTI_OR;
113450 pNew->rSetup = 0;
113451 pNew->iSortIdx = 0;
113452 memset(&pNew->u, 0, sizeof(pNew->u));
113453 for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
113454 /* TUNING: Multiple by 3.5 for the secondary table lookup */
113455 pNew->rRun = sSum.a[i].rRun + 18;
113456 pNew->nOut = sSum.a[i].nOut;
113457 pNew->prereq = sSum.a[i].prereq;
113458 rc = whereLoopInsert(pBuilder, pNew);
113462 return rc;
113466 ** Add all WhereLoop objects for all tables
113468 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
113469 WhereInfo *pWInfo = pBuilder->pWInfo;
113470 Bitmask mExtra = 0;
113471 Bitmask mPrior = 0;
113472 int iTab;
113473 SrcList *pTabList = pWInfo->pTabList;
113474 struct SrcList_item *pItem;
113475 sqlite3 *db = pWInfo->pParse->db;
113476 int nTabList = pWInfo->nLevel;
113477 int rc = SQLITE_OK;
113478 u8 priorJoinType = 0;
113479 WhereLoop *pNew;
113481 /* Loop over the tables in the join, from left to right */
113482 pNew = pBuilder->pNew;
113483 whereLoopInit(pNew);
113484 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
113485 pNew->iTab = iTab;
113486 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
113487 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
113488 mExtra = mPrior;
113490 priorJoinType = pItem->jointype;
113491 if( IsVirtual(pItem->pTab) ){
113492 rc = whereLoopAddVirtual(pBuilder, mExtra);
113493 }else{
113494 rc = whereLoopAddBtree(pBuilder, mExtra);
113496 if( rc==SQLITE_OK ){
113497 rc = whereLoopAddOr(pBuilder, mExtra);
113499 mPrior |= pNew->maskSelf;
113500 if( rc || db->mallocFailed ) break;
113502 whereLoopClear(db, pNew);
113503 return rc;
113507 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
113508 ** parameters) to see if it outputs rows in the requested ORDER BY
113509 ** (or GROUP BY) without requiring a separate sort operation. Return:
113511 ** 0: ORDER BY is not satisfied. Sorting required
113512 ** 1: ORDER BY is satisfied. Omit sorting
113513 ** -1: Unknown at this time
113515 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
113516 ** strict. With GROUP BY and DISTINCT the only requirement is that
113517 ** equivalent rows appear immediately adjacent to one another. GROUP BY
113518 ** and DISTINT do not require rows to appear in any particular order as long
113519 ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
113520 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
113521 ** pOrderBy terms must be matched in strict left-to-right order.
113523 static int wherePathSatisfiesOrderBy(
113524 WhereInfo *pWInfo, /* The WHERE clause */
113525 ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
113526 WherePath *pPath, /* The WherePath to check */
113527 u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
113528 u16 nLoop, /* Number of entries in pPath->aLoop[] */
113529 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
113530 Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
113532 u8 revSet; /* True if rev is known */
113533 u8 rev; /* Composite sort order */
113534 u8 revIdx; /* Index sort order */
113535 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
113536 u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
113537 u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
113538 u16 nKeyCol; /* Number of key columns in pIndex */
113539 u16 nColumn; /* Total number of ordered columns in the index */
113540 u16 nOrderBy; /* Number terms in the ORDER BY clause */
113541 int iLoop; /* Index of WhereLoop in pPath being processed */
113542 int i, j; /* Loop counters */
113543 int iCur; /* Cursor number for current WhereLoop */
113544 int iColumn; /* A column number within table iCur */
113545 WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
113546 WhereTerm *pTerm; /* A single term of the WHERE clause */
113547 Expr *pOBExpr; /* An expression from the ORDER BY clause */
113548 CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
113549 Index *pIndex; /* The index associated with pLoop */
113550 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
113551 Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
113552 Bitmask obDone; /* Mask of all ORDER BY terms */
113553 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
113554 Bitmask ready; /* Mask of inner loops */
113557 ** We say the WhereLoop is "one-row" if it generates no more than one
113558 ** row of output. A WhereLoop is one-row if all of the following are true:
113559 ** (a) All index columns match with WHERE_COLUMN_EQ.
113560 ** (b) The index is unique
113561 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
113562 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
113564 ** We say the WhereLoop is "order-distinct" if the set of columns from
113565 ** that WhereLoop that are in the ORDER BY clause are different for every
113566 ** row of the WhereLoop. Every one-row WhereLoop is automatically
113567 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
113568 ** is not order-distinct. To be order-distinct is not quite the same as being
113569 ** UNIQUE since a UNIQUE column or index can have multiple rows that
113570 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
113571 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
113573 ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
113574 ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
113575 ** automatically order-distinct.
113578 assert( pOrderBy!=0 );
113580 /* Sortability of virtual tables is determined by the xBestIndex method
113581 ** of the virtual table itself */
113582 if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
113583 testcase( nLoop>0 ); /* True when outer loops are one-row and match
113584 ** no ORDER BY terms */
113585 return pLast->u.vtab.isOrdered;
113587 if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
113589 nOrderBy = pOrderBy->nExpr;
113590 testcase( nOrderBy==BMS-1 );
113591 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
113592 isOrderDistinct = 1;
113593 obDone = MASKBIT(nOrderBy)-1;
113594 orderDistinctMask = 0;
113595 ready = 0;
113596 for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
113597 if( iLoop>0 ) ready |= pLoop->maskSelf;
113598 pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
113599 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
113600 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
113602 /* Mark off any ORDER BY term X that is a column in the table of
113603 ** the current loop for which there is term in the WHERE
113604 ** clause of the form X IS NULL or X=? that reference only outer
113605 ** loops.
113607 for(i=0; i<nOrderBy; i++){
113608 if( MASKBIT(i) & obSat ) continue;
113609 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
113610 if( pOBExpr->op!=TK_COLUMN ) continue;
113611 if( pOBExpr->iTable!=iCur ) continue;
113612 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
113613 ~ready, WO_EQ|WO_ISNULL, 0);
113614 if( pTerm==0 ) continue;
113615 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
113616 const char *z1, *z2;
113617 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
113618 if( !pColl ) pColl = db->pDfltColl;
113619 z1 = pColl->zName;
113620 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
113621 if( !pColl ) pColl = db->pDfltColl;
113622 z2 = pColl->zName;
113623 if( sqlite3StrICmp(z1, z2)!=0 ) continue;
113625 obSat |= MASKBIT(i);
113628 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
113629 if( pLoop->wsFlags & WHERE_IPK ){
113630 pIndex = 0;
113631 nKeyCol = 0;
113632 nColumn = 1;
113633 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
113634 return 0;
113635 }else{
113636 nKeyCol = pIndex->nKeyCol;
113637 nColumn = pIndex->nColumn;
113638 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
113639 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
113640 isOrderDistinct = pIndex->onError!=OE_None;
113643 /* Loop through all columns of the index and deal with the ones
113644 ** that are not constrained by == or IN.
113646 rev = revSet = 0;
113647 distinctColumns = 0;
113648 for(j=0; j<nColumn; j++){
113649 u8 bOnce; /* True to run the ORDER BY search loop */
113651 /* Skip over == and IS NULL terms */
113652 if( j<pLoop->u.btree.nEq
113653 && pLoop->u.btree.nSkip==0
113654 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
113656 if( i & WO_ISNULL ){
113657 testcase( isOrderDistinct );
113658 isOrderDistinct = 0;
113660 continue;
113663 /* Get the column number in the table (iColumn) and sort order
113664 ** (revIdx) for the j-th column of the index.
113666 if( pIndex ){
113667 iColumn = pIndex->aiColumn[j];
113668 revIdx = pIndex->aSortOrder[j];
113669 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
113670 }else{
113671 iColumn = -1;
113672 revIdx = 0;
113675 /* An unconstrained column that might be NULL means that this
113676 ** WhereLoop is not well-ordered
113678 if( isOrderDistinct
113679 && iColumn>=0
113680 && j>=pLoop->u.btree.nEq
113681 && pIndex->pTable->aCol[iColumn].notNull==0
113683 isOrderDistinct = 0;
113686 /* Find the ORDER BY term that corresponds to the j-th column
113687 ** of the index and and mark that ORDER BY term off
113689 bOnce = 1;
113690 isMatch = 0;
113691 for(i=0; bOnce && i<nOrderBy; i++){
113692 if( MASKBIT(i) & obSat ) continue;
113693 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
113694 testcase( wctrlFlags & WHERE_GROUPBY );
113695 testcase( wctrlFlags & WHERE_DISTINCTBY );
113696 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
113697 if( pOBExpr->op!=TK_COLUMN ) continue;
113698 if( pOBExpr->iTable!=iCur ) continue;
113699 if( pOBExpr->iColumn!=iColumn ) continue;
113700 if( iColumn>=0 ){
113701 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
113702 if( !pColl ) pColl = db->pDfltColl;
113703 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
113705 isMatch = 1;
113706 break;
113708 if( isMatch ){
113709 if( iColumn<0 ){
113710 testcase( distinctColumns==0 );
113711 distinctColumns = 1;
113713 obSat |= MASKBIT(i);
113714 if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
113715 /* Make sure the sort order is compatible in an ORDER BY clause.
113716 ** Sort order is irrelevant for a GROUP BY clause. */
113717 if( revSet ){
113718 if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
113719 }else{
113720 rev = revIdx ^ pOrderBy->a[i].sortOrder;
113721 if( rev ) *pRevMask |= MASKBIT(iLoop);
113722 revSet = 1;
113725 }else{
113726 /* No match found */
113727 if( j==0 || j<nKeyCol ){
113728 testcase( isOrderDistinct!=0 );
113729 isOrderDistinct = 0;
113731 break;
113733 } /* end Loop over all index columns */
113734 if( distinctColumns ){
113735 testcase( isOrderDistinct==0 );
113736 isOrderDistinct = 1;
113738 } /* end-if not one-row */
113740 /* Mark off any other ORDER BY terms that reference pLoop */
113741 if( isOrderDistinct ){
113742 orderDistinctMask |= pLoop->maskSelf;
113743 for(i=0; i<nOrderBy; i++){
113744 Expr *p;
113745 if( MASKBIT(i) & obSat ) continue;
113746 p = pOrderBy->a[i].pExpr;
113747 if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
113748 obSat |= MASKBIT(i);
113752 } /* End the loop over all WhereLoops from outer-most down to inner-most */
113753 if( obSat==obDone ) return 1;
113754 if( !isOrderDistinct ) return 0;
113755 return -1;
113758 #ifdef WHERETRACE_ENABLED
113759 /* For debugging use only: */
113760 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
113761 static char zName[65];
113762 int i;
113763 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
113764 if( pLast ) zName[i++] = pLast->cId;
113765 zName[i] = 0;
113766 return zName;
113768 #endif
113772 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
113773 ** attempts to find the lowest cost path that visits each WhereLoop
113774 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
113776 ** Assume that the total number of output rows that will need to be sorted
113777 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
113778 ** costs if nRowEst==0.
113780 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
113781 ** error occurs.
113783 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
113784 int mxChoice; /* Maximum number of simultaneous paths tracked */
113785 int nLoop; /* Number of terms in the join */
113786 Parse *pParse; /* Parsing context */
113787 sqlite3 *db; /* The database connection */
113788 int iLoop; /* Loop counter over the terms of the join */
113789 int ii, jj; /* Loop counters */
113790 int mxI = 0; /* Index of next entry to replace */
113791 LogEst rCost; /* Cost of a path */
113792 LogEst nOut; /* Number of outputs */
113793 LogEst mxCost = 0; /* Maximum cost of a set of paths */
113794 LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
113795 LogEst rSortCost; /* Cost to do a sort */
113796 int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
113797 WherePath *aFrom; /* All nFrom paths at the previous level */
113798 WherePath *aTo; /* The nTo best paths at the current level */
113799 WherePath *pFrom; /* An element of aFrom[] that we are working on */
113800 WherePath *pTo; /* An element of aTo[] that we are working on */
113801 WhereLoop *pWLoop; /* One of the WhereLoop objects */
113802 WhereLoop **pX; /* Used to divy up the pSpace memory */
113803 char *pSpace; /* Temporary memory used by this routine */
113805 pParse = pWInfo->pParse;
113806 db = pParse->db;
113807 nLoop = pWInfo->nLevel;
113808 /* TUNING: For simple queries, only the best path is tracked.
113809 ** For 2-way joins, the 5 best paths are followed.
113810 ** For joins of 3 or more tables, track the 10 best paths */
113811 mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
113812 assert( nLoop<=pWInfo->pTabList->nSrc );
113813 WHERETRACE(0x002, ("---- begin solver\n"));
113815 /* Allocate and initialize space for aTo and aFrom */
113816 ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
113817 pSpace = sqlite3DbMallocRaw(db, ii);
113818 if( pSpace==0 ) return SQLITE_NOMEM;
113819 aTo = (WherePath*)pSpace;
113820 aFrom = aTo+mxChoice;
113821 memset(aFrom, 0, sizeof(aFrom[0]));
113822 pX = (WhereLoop**)(aFrom+mxChoice);
113823 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
113824 pFrom->aLoop = pX;
113827 /* Seed the search with a single WherePath containing zero WhereLoops.
113829 ** TUNING: Do not let the number of iterations go above 25. If the cost
113830 ** of computing an automatic index is not paid back within the first 25
113831 ** rows, then do not use the automatic index. */
113832 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
113833 nFrom = 1;
113835 /* Precompute the cost of sorting the final result set, if the caller
113836 ** to sqlite3WhereBegin() was concerned about sorting */
113837 rSortCost = 0;
113838 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
113839 aFrom[0].isOrderedValid = 1;
113840 }else{
113841 /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
113842 ** number of output rows. The 48 is the expected size of a row to sort.
113843 ** FIXME: compute a better estimate of the 48 multiplier based on the
113844 ** result set expressions. */
113845 rSortCost = nRowEst + estLog(nRowEst);
113846 WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
113849 /* Compute successively longer WherePaths using the previous generation
113850 ** of WherePaths as the basis for the next. Keep track of the mxChoice
113851 ** best paths at each generation */
113852 for(iLoop=0; iLoop<nLoop; iLoop++){
113853 nTo = 0;
113854 for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
113855 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
113856 Bitmask maskNew;
113857 Bitmask revMask = 0;
113858 u8 isOrderedValid = pFrom->isOrderedValid;
113859 u8 isOrdered = pFrom->isOrdered;
113860 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
113861 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
113862 /* At this point, pWLoop is a candidate to be the next loop.
113863 ** Compute its cost */
113864 rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
113865 rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
113866 nOut = pFrom->nRow + pWLoop->nOut;
113867 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
113868 if( !isOrderedValid ){
113869 switch( wherePathSatisfiesOrderBy(pWInfo,
113870 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
113871 iLoop, pWLoop, &revMask) ){
113872 case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
113873 isOrdered = 1;
113874 isOrderedValid = 1;
113875 break;
113876 case 0: /* No. pFrom+pWLoop will require a separate sort */
113877 isOrdered = 0;
113878 isOrderedValid = 1;
113879 rCost = sqlite3LogEstAdd(rCost, rSortCost);
113880 break;
113881 default: /* Cannot tell yet. Try again on the next iteration */
113882 break;
113884 }else{
113885 revMask = pFrom->revLoop;
113887 /* Check to see if pWLoop should be added to the mxChoice best so far */
113888 for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
113889 if( pTo->maskLoop==maskNew
113890 && pTo->isOrderedValid==isOrderedValid
113891 && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
113892 (pTo->rCost>=rCost && pTo->nRow>=nOut))
113894 testcase( jj==nTo-1 );
113895 break;
113898 if( jj>=nTo ){
113899 if( nTo>=mxChoice && rCost>=mxCost ){
113900 #ifdef WHERETRACE_ENABLED /* 0x4 */
113901 if( sqlite3WhereTrace&0x4 ){
113902 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
113903 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
113904 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
113906 #endif
113907 continue;
113909 /* Add a new Path to the aTo[] set */
113910 if( nTo<mxChoice ){
113911 /* Increase the size of the aTo set by one */
113912 jj = nTo++;
113913 }else{
113914 /* New path replaces the prior worst to keep count below mxChoice */
113915 jj = mxI;
113917 pTo = &aTo[jj];
113918 #ifdef WHERETRACE_ENABLED /* 0x4 */
113919 if( sqlite3WhereTrace&0x4 ){
113920 sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
113921 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
113922 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
113924 #endif
113925 }else{
113926 if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
113927 #ifdef WHERETRACE_ENABLED /* 0x4 */
113928 if( sqlite3WhereTrace&0x4 ){
113929 sqlite3DebugPrintf(
113930 "Skip %s cost=%-3d,%3d order=%c",
113931 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
113932 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
113933 sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
113934 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
113935 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
113937 #endif
113938 testcase( pTo->rCost==rCost );
113939 continue;
113941 testcase( pTo->rCost==rCost+1 );
113942 /* A new and better score for a previously created equivalent path */
113943 #ifdef WHERETRACE_ENABLED /* 0x4 */
113944 if( sqlite3WhereTrace&0x4 ){
113945 sqlite3DebugPrintf(
113946 "Update %s cost=%-3d,%3d order=%c",
113947 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
113948 isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
113949 sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
113950 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
113951 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
113953 #endif
113955 /* pWLoop is a winner. Add it to the set of best so far */
113956 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
113957 pTo->revLoop = revMask;
113958 pTo->nRow = nOut;
113959 pTo->rCost = rCost;
113960 pTo->isOrderedValid = isOrderedValid;
113961 pTo->isOrdered = isOrdered;
113962 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
113963 pTo->aLoop[iLoop] = pWLoop;
113964 if( nTo>=mxChoice ){
113965 mxI = 0;
113966 mxCost = aTo[0].rCost;
113967 mxOut = aTo[0].nRow;
113968 for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
113969 if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
113970 mxCost = pTo->rCost;
113971 mxOut = pTo->nRow;
113972 mxI = jj;
113979 #ifdef WHERETRACE_ENABLED /* >=2 */
113980 if( sqlite3WhereTrace>=2 ){
113981 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
113982 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
113983 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
113984 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
113985 pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
113986 if( pTo->isOrderedValid && pTo->isOrdered ){
113987 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
113988 }else{
113989 sqlite3DebugPrintf("\n");
113993 #endif
113995 /* Swap the roles of aFrom and aTo for the next generation */
113996 pFrom = aTo;
113997 aTo = aFrom;
113998 aFrom = pFrom;
113999 nFrom = nTo;
114002 if( nFrom==0 ){
114003 sqlite3ErrorMsg(pParse, "no query solution");
114004 sqlite3DbFree(db, pSpace);
114005 return SQLITE_ERROR;
114008 /* Find the lowest cost path. pFrom will be left pointing to that path */
114009 pFrom = aFrom;
114010 for(ii=1; ii<nFrom; ii++){
114011 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
114013 assert( pWInfo->nLevel==nLoop );
114014 /* Load the lowest cost path into pWInfo */
114015 for(iLoop=0; iLoop<nLoop; iLoop++){
114016 WhereLevel *pLevel = pWInfo->a + iLoop;
114017 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
114018 pLevel->iFrom = pWLoop->iTab;
114019 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
114021 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
114022 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
114023 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
114024 && nRowEst
114026 Bitmask notUsed;
114027 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
114028 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
114029 if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
114031 if( pFrom->isOrdered ){
114032 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
114033 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
114034 }else{
114035 pWInfo->bOBSat = 1;
114036 pWInfo->revMask = pFrom->revLoop;
114039 pWInfo->nRowOut = pFrom->nRow;
114041 /* Free temporary memory and return success */
114042 sqlite3DbFree(db, pSpace);
114043 return SQLITE_OK;
114047 ** Most queries use only a single table (they are not joins) and have
114048 ** simple == constraints against indexed fields. This routine attempts
114049 ** to plan those simple cases using much less ceremony than the
114050 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
114051 ** times for the common case.
114053 ** Return non-zero on success, if this query can be handled by this
114054 ** no-frills query planner. Return zero if this query needs the
114055 ** general-purpose query planner.
114057 static int whereShortCut(WhereLoopBuilder *pBuilder){
114058 WhereInfo *pWInfo;
114059 struct SrcList_item *pItem;
114060 WhereClause *pWC;
114061 WhereTerm *pTerm;
114062 WhereLoop *pLoop;
114063 int iCur;
114064 int j;
114065 Table *pTab;
114066 Index *pIdx;
114068 pWInfo = pBuilder->pWInfo;
114069 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
114070 assert( pWInfo->pTabList->nSrc>=1 );
114071 pItem = pWInfo->pTabList->a;
114072 pTab = pItem->pTab;
114073 if( IsVirtual(pTab) ) return 0;
114074 if( pItem->zIndex ) return 0;
114075 iCur = pItem->iCursor;
114076 pWC = &pWInfo->sWC;
114077 pLoop = pBuilder->pNew;
114078 pLoop->wsFlags = 0;
114079 pLoop->u.btree.nSkip = 0;
114080 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
114081 if( pTerm ){
114082 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
114083 pLoop->aLTerm[0] = pTerm;
114084 pLoop->nLTerm = 1;
114085 pLoop->u.btree.nEq = 1;
114086 /* TUNING: Cost of a rowid lookup is 10 */
114087 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
114088 }else{
114089 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
114090 assert( pLoop->aLTermSpace==pLoop->aLTerm );
114091 assert( ArraySize(pLoop->aLTermSpace)==4 );
114092 if( pIdx->onError==OE_None
114093 || pIdx->pPartIdxWhere!=0
114094 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
114095 ) continue;
114096 for(j=0; j<pIdx->nKeyCol; j++){
114097 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
114098 if( pTerm==0 ) break;
114099 pLoop->aLTerm[j] = pTerm;
114101 if( j!=pIdx->nKeyCol ) continue;
114102 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
114103 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
114104 pLoop->wsFlags |= WHERE_IDX_ONLY;
114106 pLoop->nLTerm = j;
114107 pLoop->u.btree.nEq = j;
114108 pLoop->u.btree.pIndex = pIdx;
114109 /* TUNING: Cost of a unique index lookup is 15 */
114110 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
114111 break;
114114 if( pLoop->wsFlags ){
114115 pLoop->nOut = (LogEst)1;
114116 pWInfo->a[0].pWLoop = pLoop;
114117 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
114118 pWInfo->a[0].iTabCur = iCur;
114119 pWInfo->nRowOut = 1;
114120 if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
114121 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
114122 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
114124 #ifdef SQLITE_DEBUG
114125 pLoop->cId = '0';
114126 #endif
114127 return 1;
114129 return 0;
114133 ** Generate the beginning of the loop used for WHERE clause processing.
114134 ** The return value is a pointer to an opaque structure that contains
114135 ** information needed to terminate the loop. Later, the calling routine
114136 ** should invoke sqlite3WhereEnd() with the return value of this function
114137 ** in order to complete the WHERE clause processing.
114139 ** If an error occurs, this routine returns NULL.
114141 ** The basic idea is to do a nested loop, one loop for each table in
114142 ** the FROM clause of a select. (INSERT and UPDATE statements are the
114143 ** same as a SELECT with only a single table in the FROM clause.) For
114144 ** example, if the SQL is this:
114146 ** SELECT * FROM t1, t2, t3 WHERE ...;
114148 ** Then the code generated is conceptually like the following:
114150 ** foreach row1 in t1 do \ Code generated
114151 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
114152 ** foreach row3 in t3 do /
114153 ** ...
114154 ** end \ Code generated
114155 ** end |-- by sqlite3WhereEnd()
114156 ** end /
114158 ** Note that the loops might not be nested in the order in which they
114159 ** appear in the FROM clause if a different order is better able to make
114160 ** use of indices. Note also that when the IN operator appears in
114161 ** the WHERE clause, it might result in additional nested loops for
114162 ** scanning through all values on the right-hand side of the IN.
114164 ** There are Btree cursors associated with each table. t1 uses cursor
114165 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
114166 ** And so forth. This routine generates code to open those VDBE cursors
114167 ** and sqlite3WhereEnd() generates the code to close them.
114169 ** The code that sqlite3WhereBegin() generates leaves the cursors named
114170 ** in pTabList pointing at their appropriate entries. The [...] code
114171 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
114172 ** data from the various tables of the loop.
114174 ** If the WHERE clause is empty, the foreach loops must each scan their
114175 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
114176 ** the tables have indices and there are terms in the WHERE clause that
114177 ** refer to those indices, a complete table scan can be avoided and the
114178 ** code will run much faster. Most of the work of this routine is checking
114179 ** to see if there are indices that can be used to speed up the loop.
114181 ** Terms of the WHERE clause are also used to limit which rows actually
114182 ** make it to the "..." in the middle of the loop. After each "foreach",
114183 ** terms of the WHERE clause that use only terms in that loop and outer
114184 ** loops are evaluated and if false a jump is made around all subsequent
114185 ** inner loops (or around the "..." if the test occurs within the inner-
114186 ** most loop)
114188 ** OUTER JOINS
114190 ** An outer join of tables t1 and t2 is conceptally coded as follows:
114192 ** foreach row1 in t1 do
114193 ** flag = 0
114194 ** foreach row2 in t2 do
114195 ** start:
114196 ** ...
114197 ** flag = 1
114198 ** end
114199 ** if flag==0 then
114200 ** move the row2 cursor to a null row
114201 ** goto start
114202 ** fi
114203 ** end
114205 ** ORDER BY CLAUSE PROCESSING
114207 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
114208 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
114209 ** if there is one. If there is no ORDER BY clause or if this routine
114210 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
114212 ** The iIdxCur parameter is the cursor number of an index. If
114213 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
114214 ** to use for OR clause processing. The WHERE clause should use this
114215 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
114216 ** the first cursor in an array of cursors for all indices. iIdxCur should
114217 ** be used to compute the appropriate cursor depending on which index is
114218 ** used.
114220 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
114221 Parse *pParse, /* The parser context */
114222 SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
114223 Expr *pWhere, /* The WHERE clause */
114224 ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
114225 ExprList *pResultSet, /* Result set of the query */
114226 u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
114227 int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
114229 int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
114230 int nTabList; /* Number of elements in pTabList */
114231 WhereInfo *pWInfo; /* Will become the return value of this function */
114232 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
114233 Bitmask notReady; /* Cursors that are not yet positioned */
114234 WhereLoopBuilder sWLB; /* The WhereLoop builder */
114235 WhereMaskSet *pMaskSet; /* The expression mask set */
114236 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
114237 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
114238 int ii; /* Loop counter */
114239 sqlite3 *db; /* Database connection */
114240 int rc; /* Return code */
114243 /* Variable initialization */
114244 db = pParse->db;
114245 memset(&sWLB, 0, sizeof(sWLB));
114246 sWLB.pOrderBy = pOrderBy;
114248 /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
114249 ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
114250 if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
114251 wctrlFlags &= ~WHERE_WANT_DISTINCT;
114254 /* The number of tables in the FROM clause is limited by the number of
114255 ** bits in a Bitmask
114257 testcase( pTabList->nSrc==BMS );
114258 if( pTabList->nSrc>BMS ){
114259 sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
114260 return 0;
114263 /* This function normally generates a nested loop for all tables in
114264 ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
114265 ** only generate code for the first table in pTabList and assume that
114266 ** any cursors associated with subsequent tables are uninitialized.
114268 nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
114270 /* Allocate and initialize the WhereInfo structure that will become the
114271 ** return value. A single allocation is used to store the WhereInfo
114272 ** struct, the contents of WhereInfo.a[], the WhereClause structure
114273 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
114274 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
114275 ** some architectures. Hence the ROUND8() below.
114277 nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
114278 pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
114279 if( db->mallocFailed ){
114280 sqlite3DbFree(db, pWInfo);
114281 pWInfo = 0;
114282 goto whereBeginError;
114284 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
114285 pWInfo->nLevel = nTabList;
114286 pWInfo->pParse = pParse;
114287 pWInfo->pTabList = pTabList;
114288 pWInfo->pOrderBy = pOrderBy;
114289 pWInfo->pResultSet = pResultSet;
114290 pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
114291 pWInfo->wctrlFlags = wctrlFlags;
114292 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
114293 pMaskSet = &pWInfo->sMaskSet;
114294 sWLB.pWInfo = pWInfo;
114295 sWLB.pWC = &pWInfo->sWC;
114296 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
114297 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
114298 whereLoopInit(sWLB.pNew);
114299 #ifdef SQLITE_DEBUG
114300 sWLB.pNew->cId = '*';
114301 #endif
114303 /* Split the WHERE clause into separate subexpressions where each
114304 ** subexpression is separated by an AND operator.
114306 initMaskSet(pMaskSet);
114307 whereClauseInit(&pWInfo->sWC, pWInfo);
114308 whereSplit(&pWInfo->sWC, pWhere, TK_AND);
114309 sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
114311 /* Special case: a WHERE clause that is constant. Evaluate the
114312 ** expression and either jump over all of the code or fall thru.
114314 for(ii=0; ii<sWLB.pWC->nTerm; ii++){
114315 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
114316 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
114317 SQLITE_JUMPIFNULL);
114318 sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
114322 /* Special case: No FROM clause
114324 if( nTabList==0 ){
114325 if( pOrderBy ) pWInfo->bOBSat = 1;
114326 if( wctrlFlags & WHERE_WANT_DISTINCT ){
114327 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
114331 /* Assign a bit from the bitmask to every term in the FROM clause.
114333 ** When assigning bitmask values to FROM clause cursors, it must be
114334 ** the case that if X is the bitmask for the N-th FROM clause term then
114335 ** the bitmask for all FROM clause terms to the left of the N-th term
114336 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
114337 ** its Expr.iRightJoinTable value to find the bitmask of the right table
114338 ** of the join. Subtracting one from the right table bitmask gives a
114339 ** bitmask for all tables to the left of the join. Knowing the bitmask
114340 ** for all tables to the left of a left join is important. Ticket #3015.
114342 ** Note that bitmasks are created for all pTabList->nSrc tables in
114343 ** pTabList, not just the first nTabList tables. nTabList is normally
114344 ** equal to pTabList->nSrc but might be shortened to 1 if the
114345 ** WHERE_ONETABLE_ONLY flag is set.
114347 for(ii=0; ii<pTabList->nSrc; ii++){
114348 createMask(pMaskSet, pTabList->a[ii].iCursor);
114350 #ifndef NDEBUG
114352 Bitmask toTheLeft = 0;
114353 for(ii=0; ii<pTabList->nSrc; ii++){
114354 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
114355 assert( (m-1)==toTheLeft );
114356 toTheLeft |= m;
114359 #endif
114361 /* Analyze all of the subexpressions. Note that exprAnalyze() might
114362 ** add new virtual terms onto the end of the WHERE clause. We do not
114363 ** want to analyze these virtual terms, so start analyzing at the end
114364 ** and work forward so that the added virtual terms are never processed.
114366 exprAnalyzeAll(pTabList, &pWInfo->sWC);
114367 if( db->mallocFailed ){
114368 goto whereBeginError;
114371 /* If the ORDER BY (or GROUP BY) clause contains references to general
114372 ** expressions, then we won't be able to satisfy it using indices, so
114373 ** go ahead and disable it now.
114375 if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
114376 for(ii=0; ii<pOrderBy->nExpr; ii++){
114377 Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
114378 if( pExpr->op!=TK_COLUMN ){
114379 pWInfo->pOrderBy = pOrderBy = 0;
114380 break;
114381 }else if( pExpr->iColumn<0 ){
114382 break;
114387 if( wctrlFlags & WHERE_WANT_DISTINCT ){
114388 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
114389 /* The DISTINCT marking is pointless. Ignore it. */
114390 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
114391 }else if( pOrderBy==0 ){
114392 /* Try to ORDER BY the result set to make distinct processing easier */
114393 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
114394 pWInfo->pOrderBy = pResultSet;
114398 /* Construct the WhereLoop objects */
114399 WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
114400 /* Display all terms of the WHERE clause */
114401 #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
114402 if( sqlite3WhereTrace & 0x100 ){
114403 int i;
114404 Vdbe *v = pParse->pVdbe;
114405 sqlite3ExplainBegin(v);
114406 for(i=0; i<sWLB.pWC->nTerm; i++){
114407 sqlite3ExplainPrintf(v, "#%-2d ", i);
114408 sqlite3ExplainPush(v);
114409 whereExplainTerm(v, &sWLB.pWC->a[i]);
114410 sqlite3ExplainPop(v);
114411 sqlite3ExplainNL(v);
114413 sqlite3ExplainFinish(v);
114414 sqlite3DebugPrintf("%s", sqlite3VdbeExplanation(v));
114416 #endif
114417 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
114418 rc = whereLoopAddAll(&sWLB);
114419 if( rc ) goto whereBeginError;
114421 /* Display all of the WhereLoop objects if wheretrace is enabled */
114422 #ifdef WHERETRACE_ENABLED /* !=0 */
114423 if( sqlite3WhereTrace ){
114424 WhereLoop *p;
114425 int i;
114426 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
114427 "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
114428 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
114429 p->cId = zLabel[i%sizeof(zLabel)];
114430 whereLoopPrint(p, sWLB.pWC);
114433 #endif
114435 wherePathSolver(pWInfo, 0);
114436 if( db->mallocFailed ) goto whereBeginError;
114437 if( pWInfo->pOrderBy ){
114438 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
114439 if( db->mallocFailed ) goto whereBeginError;
114442 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
114443 pWInfo->revMask = (Bitmask)(-1);
114445 if( pParse->nErr || NEVER(db->mallocFailed) ){
114446 goto whereBeginError;
114448 #ifdef WHERETRACE_ENABLED /* !=0 */
114449 if( sqlite3WhereTrace ){
114450 int ii;
114451 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
114452 if( pWInfo->bOBSat ){
114453 sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
114455 switch( pWInfo->eDistinct ){
114456 case WHERE_DISTINCT_UNIQUE: {
114457 sqlite3DebugPrintf(" DISTINCT=unique");
114458 break;
114460 case WHERE_DISTINCT_ORDERED: {
114461 sqlite3DebugPrintf(" DISTINCT=ordered");
114462 break;
114464 case WHERE_DISTINCT_UNORDERED: {
114465 sqlite3DebugPrintf(" DISTINCT=unordered");
114466 break;
114469 sqlite3DebugPrintf("\n");
114470 for(ii=0; ii<pWInfo->nLevel; ii++){
114471 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
114474 #endif
114475 /* Attempt to omit tables from the join that do not effect the result */
114476 if( pWInfo->nLevel>=2
114477 && pResultSet!=0
114478 && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
114480 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
114481 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
114482 while( pWInfo->nLevel>=2 ){
114483 WhereTerm *pTerm, *pEnd;
114484 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
114485 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
114486 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
114487 && (pLoop->wsFlags & WHERE_ONEROW)==0
114489 break;
114491 if( (tabUsed & pLoop->maskSelf)!=0 ) break;
114492 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
114493 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
114494 if( (pTerm->prereqAll & pLoop->maskSelf)!=0
114495 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
114497 break;
114500 if( pTerm<pEnd ) break;
114501 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
114502 pWInfo->nLevel--;
114503 nTabList--;
114506 WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
114507 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
114509 /* If the caller is an UPDATE or DELETE statement that is requesting
114510 ** to use a one-pass algorithm, determine if this is appropriate.
114511 ** The one-pass algorithm only works if the WHERE clause constrains
114512 ** the statement to update a single row.
114514 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
114515 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
114516 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
114517 pWInfo->okOnePass = 1;
114518 if( HasRowid(pTabList->a[0].pTab) ){
114519 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
114523 /* Open all tables in the pTabList and any indices selected for
114524 ** searching those tables.
114526 notReady = ~(Bitmask)0;
114527 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
114528 Table *pTab; /* Table to open */
114529 int iDb; /* Index of database containing table/index */
114530 struct SrcList_item *pTabItem;
114532 pTabItem = &pTabList->a[pLevel->iFrom];
114533 pTab = pTabItem->pTab;
114534 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114535 pLoop = pLevel->pWLoop;
114536 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
114537 /* Do nothing */
114538 }else
114539 #ifndef SQLITE_OMIT_VIRTUALTABLE
114540 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
114541 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
114542 int iCur = pTabItem->iCursor;
114543 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
114544 }else if( IsVirtual(pTab) ){
114545 /* noop */
114546 }else
114547 #endif
114548 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
114549 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
114550 int op = OP_OpenRead;
114551 if( pWInfo->okOnePass ){
114552 op = OP_OpenWrite;
114553 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
114555 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
114556 assert( pTabItem->iCursor==pLevel->iTabCur );
114557 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
114558 testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
114559 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
114560 Bitmask b = pTabItem->colUsed;
114561 int n = 0;
114562 for(; b; b=b>>1, n++){}
114563 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
114564 SQLITE_INT_TO_PTR(n), P4_INT32);
114565 assert( n<=pTab->nCol );
114567 }else{
114568 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
114570 if( pLoop->wsFlags & WHERE_INDEXED ){
114571 Index *pIx = pLoop->u.btree.pIndex;
114572 int iIndexCur;
114573 int op = OP_OpenRead;
114574 /* iIdxCur is always set if to a positive value if ONEPASS is possible */
114575 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
114576 if( pWInfo->okOnePass ){
114577 Index *pJ = pTabItem->pTab->pIndex;
114578 iIndexCur = iIdxCur;
114579 assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
114580 while( ALWAYS(pJ) && pJ!=pIx ){
114581 iIndexCur++;
114582 pJ = pJ->pNext;
114584 op = OP_OpenWrite;
114585 pWInfo->aiCurOnePass[1] = iIndexCur;
114586 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
114587 iIndexCur = iIdxCur;
114588 }else{
114589 iIndexCur = pParse->nTab++;
114591 pLevel->iIdxCur = iIndexCur;
114592 assert( pIx->pSchema==pTab->pSchema );
114593 assert( iIndexCur>=0 );
114594 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
114595 sqlite3VdbeSetP4KeyInfo(pParse, pIx);
114596 VdbeComment((v, "%s", pIx->zName));
114598 sqlite3CodeVerifySchema(pParse, iDb);
114599 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
114601 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
114602 if( db->mallocFailed ) goto whereBeginError;
114604 /* Generate the code to do the search. Each iteration of the for
114605 ** loop below generates code for a single nested loop of the VM
114606 ** program.
114608 notReady = ~(Bitmask)0;
114609 for(ii=0; ii<nTabList; ii++){
114610 pLevel = &pWInfo->a[ii];
114611 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
114612 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
114613 constructAutomaticIndex(pParse, &pWInfo->sWC,
114614 &pTabList->a[pLevel->iFrom], notReady, pLevel);
114615 if( db->mallocFailed ) goto whereBeginError;
114617 #endif
114618 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
114619 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
114620 notReady = codeOneLoopStart(pWInfo, ii, notReady);
114621 pWInfo->iContinue = pLevel->addrCont;
114624 /* Done. */
114625 VdbeModuleComment((v, "Begin WHERE-core"));
114626 return pWInfo;
114628 /* Jump here if malloc fails */
114629 whereBeginError:
114630 if( pWInfo ){
114631 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
114632 whereInfoFree(db, pWInfo);
114634 return 0;
114638 ** Generate the end of the WHERE loop. See comments on
114639 ** sqlite3WhereBegin() for additional information.
114641 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
114642 Parse *pParse = pWInfo->pParse;
114643 Vdbe *v = pParse->pVdbe;
114644 int i;
114645 WhereLevel *pLevel;
114646 WhereLoop *pLoop;
114647 SrcList *pTabList = pWInfo->pTabList;
114648 sqlite3 *db = pParse->db;
114650 /* Generate loop termination code.
114652 VdbeModuleComment((v, "End WHERE-core"));
114653 sqlite3ExprCacheClear(pParse);
114654 for(i=pWInfo->nLevel-1; i>=0; i--){
114655 int addr;
114656 pLevel = &pWInfo->a[i];
114657 pLoop = pLevel->pWLoop;
114658 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
114659 if( pLevel->op!=OP_Noop ){
114660 sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
114661 sqlite3VdbeChangeP5(v, pLevel->p5);
114663 if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
114664 struct InLoop *pIn;
114665 int j;
114666 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
114667 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
114668 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
114669 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
114670 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
114672 sqlite3DbFree(db, pLevel->u.in.aInLoop);
114674 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
114675 if( pLevel->addrSkip ){
114676 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
114677 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
114678 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
114679 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
114681 if( pLevel->iLeftJoin ){
114682 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
114683 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
114684 || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
114685 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
114686 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
114688 if( pLoop->wsFlags & WHERE_INDEXED ){
114689 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
114691 if( pLevel->op==OP_Return ){
114692 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
114693 }else{
114694 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
114696 sqlite3VdbeJumpHere(v, addr);
114698 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
114699 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
114702 /* The "break" point is here, just past the end of the outer loop.
114703 ** Set it.
114705 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
114707 assert( pWInfo->nLevel<=pTabList->nSrc );
114708 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
114709 Index *pIdx = 0;
114710 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
114711 Table *pTab = pTabItem->pTab;
114712 assert( pTab!=0 );
114713 pLoop = pLevel->pWLoop;
114715 /* Close all of the cursors that were opened by sqlite3WhereBegin.
114716 ** Except, do not close cursors that will be reused by the OR optimization
114717 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
114718 ** created for the ONEPASS optimization.
114720 if( (pTab->tabFlags & TF_Ephemeral)==0
114721 && pTab->pSelect==0
114722 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
114724 int ws = pLoop->wsFlags;
114725 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
114726 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
114728 if( (ws & WHERE_INDEXED)!=0
114729 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
114730 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
114732 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
114736 /* If this scan uses an index, make VDBE code substitutions to read data
114737 ** from the index instead of from the table where possible. In some cases
114738 ** this optimization prevents the table from ever being read, which can
114739 ** yield a significant performance boost.
114741 ** Calls to the code generator in between sqlite3WhereBegin and
114742 ** sqlite3WhereEnd will have created code that references the table
114743 ** directly. This loop scans all that code looking for opcodes
114744 ** that reference the table and converts them into opcodes that
114745 ** reference the index.
114747 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
114748 pIdx = pLoop->u.btree.pIndex;
114749 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
114750 pIdx = pLevel->u.pCovidx;
114752 if( pIdx && !db->mallocFailed ){
114753 int k, last;
114754 VdbeOp *pOp;
114756 last = sqlite3VdbeCurrentAddr(v);
114757 k = pLevel->addrBody;
114758 pOp = sqlite3VdbeGetOp(v, k);
114759 for(; k<last; k++, pOp++){
114760 if( pOp->p1!=pLevel->iTabCur ) continue;
114761 if( pOp->opcode==OP_Column ){
114762 int x = pOp->p2;
114763 assert( pIdx->pTable==pTab );
114764 if( !HasRowid(pTab) ){
114765 Index *pPk = sqlite3PrimaryKeyIndex(pTab);
114766 x = pPk->aiColumn[x];
114768 x = sqlite3ColumnOfIndex(pIdx, x);
114769 if( x>=0 ){
114770 pOp->p2 = x;
114771 pOp->p1 = pLevel->iIdxCur;
114773 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
114774 }else if( pOp->opcode==OP_Rowid ){
114775 pOp->p1 = pLevel->iIdxCur;
114776 pOp->opcode = OP_IdxRowid;
114782 /* Final cleanup
114784 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
114785 whereInfoFree(db, pWInfo);
114786 return;
114789 /************** End of where.c ***********************************************/
114790 /************** Begin file parse.c *******************************************/
114791 /* Driver template for the LEMON parser generator.
114792 ** The author disclaims copyright to this source code.
114794 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
114795 ** The only modifications are the addition of a couple of NEVER()
114796 ** macros to disable tests that are needed in the case of a general
114797 ** LALR(1) grammar but which are always false in the
114798 ** specific grammar used by SQLite.
114800 /* First off, code is included that follows the "include" declaration
114801 ** in the input grammar file. */
114802 /* #include <stdio.h> */
114806 ** Disable all error recovery processing in the parser push-down
114807 ** automaton.
114809 #define YYNOERRORRECOVERY 1
114812 ** Make yytestcase() the same as testcase()
114814 #define yytestcase(X) testcase(X)
114817 ** An instance of this structure holds information about the
114818 ** LIMIT clause of a SELECT statement.
114820 struct LimitVal {
114821 Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
114822 Expr *pOffset; /* The OFFSET expression. NULL if there is none */
114826 ** An instance of this structure is used to store the LIKE,
114827 ** GLOB, NOT LIKE, and NOT GLOB operators.
114829 struct LikeOp {
114830 Token eOperator; /* "like" or "glob" or "regexp" */
114831 int bNot; /* True if the NOT keyword is present */
114835 ** An instance of the following structure describes the event of a
114836 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
114837 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
114839 ** UPDATE ON (a,b,c)
114841 ** Then the "b" IdList records the list "a,b,c".
114843 struct TrigEvent { int a; IdList * b; };
114846 ** An instance of this structure holds the ATTACH key and the key type.
114848 struct AttachKey { int type; Token key; };
114851 /* This is a utility routine used to set the ExprSpan.zStart and
114852 ** ExprSpan.zEnd values of pOut so that the span covers the complete
114853 ** range of text beginning with pStart and going to the end of pEnd.
114855 static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
114856 pOut->zStart = pStart->z;
114857 pOut->zEnd = &pEnd->z[pEnd->n];
114860 /* Construct a new Expr object from a single identifier. Use the
114861 ** new Expr to populate pOut. Set the span of pOut to be the identifier
114862 ** that created the expression.
114864 static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
114865 pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
114866 pOut->zStart = pValue->z;
114867 pOut->zEnd = &pValue->z[pValue->n];
114870 /* This routine constructs a binary expression node out of two ExprSpan
114871 ** objects and uses the result to populate a new ExprSpan object.
114873 static void spanBinaryExpr(
114874 ExprSpan *pOut, /* Write the result here */
114875 Parse *pParse, /* The parsing context. Errors accumulate here */
114876 int op, /* The binary operation */
114877 ExprSpan *pLeft, /* The left operand */
114878 ExprSpan *pRight /* The right operand */
114880 pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
114881 pOut->zStart = pLeft->zStart;
114882 pOut->zEnd = pRight->zEnd;
114885 /* Construct an expression node for a unary postfix operator
114887 static void spanUnaryPostfix(
114888 ExprSpan *pOut, /* Write the new expression node here */
114889 Parse *pParse, /* Parsing context to record errors */
114890 int op, /* The operator */
114891 ExprSpan *pOperand, /* The operand */
114892 Token *pPostOp /* The operand token for setting the span */
114894 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
114895 pOut->zStart = pOperand->zStart;
114896 pOut->zEnd = &pPostOp->z[pPostOp->n];
114899 /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
114900 ** unary TK_ISNULL or TK_NOTNULL expression. */
114901 static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
114902 sqlite3 *db = pParse->db;
114903 if( db->mallocFailed==0 && pY->op==TK_NULL ){
114904 pA->op = (u8)op;
114905 sqlite3ExprDelete(db, pA->pRight);
114906 pA->pRight = 0;
114910 /* Construct an expression node for a unary prefix operator
114912 static void spanUnaryPrefix(
114913 ExprSpan *pOut, /* Write the new expression node here */
114914 Parse *pParse, /* Parsing context to record errors */
114915 int op, /* The operator */
114916 ExprSpan *pOperand, /* The operand */
114917 Token *pPreOp /* The operand token for setting the span */
114919 pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
114920 pOut->zStart = pPreOp->z;
114921 pOut->zEnd = pOperand->zEnd;
114923 /* Next is all token values, in a form suitable for use by makeheaders.
114924 ** This section will be null unless lemon is run with the -m switch.
114927 ** These constants (all generated automatically by the parser generator)
114928 ** specify the various kinds of tokens (terminals) that the parser
114929 ** understands.
114931 ** Each symbol here is a terminal symbol in the grammar.
114933 /* Make sure the INTERFACE macro is defined.
114935 #ifndef INTERFACE
114936 # define INTERFACE 1
114937 #endif
114938 /* The next thing included is series of defines which control
114939 ** various aspects of the generated parser.
114940 ** YYCODETYPE is the data type used for storing terminal
114941 ** and nonterminal numbers. "unsigned char" is
114942 ** used if there are fewer than 250 terminals
114943 ** and nonterminals. "int" is used otherwise.
114944 ** YYNOCODE is a number of type YYCODETYPE which corresponds
114945 ** to no legal terminal or nonterminal number. This
114946 ** number is used to fill in empty slots of the hash
114947 ** table.
114948 ** YYFALLBACK If defined, this indicates that one or more tokens
114949 ** have fall-back values which should be used if the
114950 ** original value of the token will not parse.
114951 ** YYACTIONTYPE is the data type used for storing terminal
114952 ** and nonterminal numbers. "unsigned char" is
114953 ** used if there are fewer than 250 rules and
114954 ** states combined. "int" is used otherwise.
114955 ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
114956 ** directly to the parser from the tokenizer.
114957 ** YYMINORTYPE is the data type used for all minor tokens.
114958 ** This is typically a union of many types, one of
114959 ** which is sqlite3ParserTOKENTYPE. The entry in the union
114960 ** for base tokens is called "yy0".
114961 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
114962 ** zero the stack is dynamically sized using realloc()
114963 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
114964 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
114965 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
114966 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
114967 ** YYNSTATE the combined number of states.
114968 ** YYNRULE the number of rules in the grammar
114969 ** YYERRORSYMBOL is the code number of the error symbol. If not
114970 ** defined, then do no error processing.
114972 #define YYCODETYPE unsigned char
114973 #define YYNOCODE 254
114974 #define YYACTIONTYPE unsigned short int
114975 #define YYWILDCARD 70
114976 #define sqlite3ParserTOKENTYPE Token
114977 typedef union {
114978 int yyinit;
114979 sqlite3ParserTOKENTYPE yy0;
114980 Select* yy3;
114981 ExprList* yy14;
114982 With* yy59;
114983 SrcList* yy65;
114984 struct LikeOp yy96;
114985 Expr* yy132;
114986 u8 yy186;
114987 int yy328;
114988 ExprSpan yy346;
114989 struct TrigEvent yy378;
114990 u16 yy381;
114991 IdList* yy408;
114992 struct {int value; int mask;} yy429;
114993 TriggerStep* yy473;
114994 struct LimitVal yy476;
114995 } YYMINORTYPE;
114996 #ifndef YYSTACKDEPTH
114997 #define YYSTACKDEPTH 100
114998 #endif
114999 #define sqlite3ParserARG_SDECL Parse *pParse;
115000 #define sqlite3ParserARG_PDECL ,Parse *pParse
115001 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
115002 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
115003 #define YYNSTATE 642
115004 #define YYNRULE 327
115005 #define YYFALLBACK 1
115006 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
115007 #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
115008 #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
115010 /* The yyzerominor constant is used to initialize instances of
115011 ** YYMINORTYPE objects to zero. */
115012 static const YYMINORTYPE yyzerominor = { 0 };
115014 /* Define the yytestcase() macro to be a no-op if is not already defined
115015 ** otherwise.
115017 ** Applications can choose to define yytestcase() in the %include section
115018 ** to a macro that can assist in verifying code coverage. For production
115019 ** code the yytestcase() macro should be turned off. But it is useful
115020 ** for testing.
115022 #ifndef yytestcase
115023 # define yytestcase(X)
115024 #endif
115027 /* Next are the tables used to determine what action to take based on the
115028 ** current state and lookahead token. These tables are used to implement
115029 ** functions that take a state number and lookahead value and return an
115030 ** action integer.
115032 ** Suppose the action integer is N. Then the action is determined as
115033 ** follows
115035 ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
115036 ** token onto the stack and goto state N.
115038 ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
115040 ** N == YYNSTATE+YYNRULE A syntax error has occurred.
115042 ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
115044 ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
115045 ** slots in the yy_action[] table.
115047 ** The action table is constructed as a single large table named yy_action[].
115048 ** Given state S and lookahead X, the action is computed as
115050 ** yy_action[ yy_shift_ofst[S] + X ]
115052 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
115053 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
115054 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
115055 ** and that yy_default[S] should be used instead.
115057 ** The formula above is for computing the action when the lookahead is
115058 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
115059 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
115060 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
115061 ** YY_SHIFT_USE_DFLT.
115063 ** The following are the tables generated in this section:
115065 ** yy_action[] A single table containing all actions.
115066 ** yy_lookahead[] A table containing the lookahead for each entry in
115067 ** yy_action. Used to detect hash collisions.
115068 ** yy_shift_ofst[] For each state, the offset into yy_action for
115069 ** shifting terminals.
115070 ** yy_reduce_ofst[] For each state, the offset into yy_action for
115071 ** shifting non-terminals after a reduce.
115072 ** yy_default[] Default action for each state.
115074 #define YY_ACTTAB_COUNT (1497)
115075 static const YYACTIONTYPE yy_action[] = {
115076 /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
115077 /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
115078 /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
115079 /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
115080 /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
115081 /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
115082 /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
115083 /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
115084 /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
115085 /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
115086 /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
115087 /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
115088 /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
115089 /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
115090 /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
115091 /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
115092 /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
115093 /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
115094 /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
115095 /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
115096 /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
115097 /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
115098 /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
115099 /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
115100 /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
115101 /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
115102 /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
115103 /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
115104 /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
115105 /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
115106 /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
115107 /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
115108 /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
115109 /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
115110 /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
115111 /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
115112 /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
115113 /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
115114 /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
115115 /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
115116 /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
115117 /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
115118 /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
115119 /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
115120 /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
115121 /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
115122 /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
115123 /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
115124 /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
115125 /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
115126 /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
115127 /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
115128 /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
115129 /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
115130 /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
115131 /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
115132 /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
115133 /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
115134 /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
115135 /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
115136 /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
115137 /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
115138 /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
115139 /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
115140 /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
115141 /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
115142 /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
115143 /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
115144 /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
115145 /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
115146 /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
115147 /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
115148 /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
115149 /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
115150 /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
115151 /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
115152 /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
115153 /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
115154 /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
115155 /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
115156 /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
115157 /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
115158 /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
115159 /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
115160 /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
115161 /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
115162 /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
115163 /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
115164 /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
115165 /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
115166 /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
115167 /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
115168 /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
115169 /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
115170 /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
115171 /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
115172 /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
115173 /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
115174 /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
115175 /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
115176 /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
115177 /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
115178 /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
115179 /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
115180 /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
115181 /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
115182 /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
115183 /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
115184 /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
115185 /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
115186 /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
115187 /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
115188 /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
115189 /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
115190 /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
115191 /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
115192 /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
115193 /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
115194 /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
115195 /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
115196 /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
115197 /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
115198 /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
115199 /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
115200 /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
115201 /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
115202 /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
115203 /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
115204 /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
115205 /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
115206 /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
115207 /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
115208 /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
115209 /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
115210 /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
115211 /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
115212 /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
115213 /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
115214 /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
115215 /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
115216 /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
115217 /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
115218 /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
115219 /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
115220 /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
115221 /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
115222 /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
115223 /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
115224 /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
115225 /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
115227 static const YYCODETYPE yy_lookahead[] = {
115228 /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
115229 /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
115230 /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
115231 /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
115232 /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
115233 /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
115234 /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
115235 /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
115236 /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
115237 /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
115238 /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
115239 /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
115240 /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
115241 /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
115242 /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
115243 /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
115244 /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
115245 /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
115246 /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
115247 /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
115248 /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
115249 /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
115250 /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
115251 /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
115252 /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
115253 /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
115254 /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
115255 /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
115256 /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
115257 /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
115258 /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
115259 /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
115260 /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
115261 /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
115262 /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
115263 /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
115264 /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
115265 /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
115266 /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
115267 /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
115268 /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
115269 /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
115270 /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
115271 /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
115272 /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
115273 /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
115274 /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
115275 /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
115276 /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
115277 /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
115278 /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
115279 /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
115280 /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
115281 /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
115282 /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
115283 /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
115284 /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
115285 /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
115286 /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
115287 /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
115288 /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
115289 /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
115290 /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
115291 /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
115292 /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
115293 /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
115294 /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
115295 /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
115296 /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
115297 /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
115298 /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
115299 /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
115300 /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
115301 /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
115302 /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
115303 /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
115304 /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
115305 /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
115306 /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
115307 /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
115308 /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
115309 /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
115310 /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
115311 /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
115312 /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
115313 /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
115314 /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
115315 /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
115316 /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
115317 /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
115318 /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
115319 /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
115320 /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
115321 /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
115322 /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
115323 /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
115324 /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
115325 /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
115326 /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
115327 /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
115328 /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
115329 /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
115330 /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
115331 /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
115332 /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
115333 /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
115334 /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
115335 /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
115336 /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
115337 /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
115338 /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
115339 /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
115340 /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
115341 /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
115342 /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
115343 /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
115344 /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
115345 /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
115346 /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
115347 /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
115348 /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
115349 /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
115350 /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
115351 /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
115352 /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
115353 /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
115354 /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
115355 /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
115356 /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
115357 /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
115358 /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
115359 /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
115360 /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
115361 /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
115362 /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
115363 /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
115364 /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
115365 /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
115366 /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
115367 /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
115368 /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
115369 /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
115370 /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
115371 /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
115372 /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
115373 /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
115374 /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
115375 /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
115376 /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
115377 /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
115379 #define YY_SHIFT_USE_DFLT (-86)
115380 #define YY_SHIFT_COUNT (429)
115381 #define YY_SHIFT_MIN (-85)
115382 #define YY_SHIFT_MAX (1383)
115383 static const short yy_shift_ofst[] = {
115384 /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
115385 /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
115386 /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
115387 /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
115388 /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
115389 /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
115390 /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
115391 /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
115392 /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
115393 /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
115394 /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
115395 /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
115396 /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
115397 /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
115398 /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
115399 /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
115400 /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
115401 /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
115402 /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
115403 /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
115404 /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
115405 /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
115406 /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
115407 /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
115408 /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
115409 /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
115410 /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
115411 /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
115412 /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
115413 /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
115414 /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
115415 /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
115416 /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
115417 /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
115418 /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
115419 /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
115420 /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
115421 /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
115422 /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
115423 /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
115424 /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
115425 /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
115426 /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
115428 #define YY_REDUCE_USE_DFLT (-110)
115429 #define YY_REDUCE_COUNT (305)
115430 #define YY_REDUCE_MIN (-109)
115431 #define YY_REDUCE_MAX (1323)
115432 static const short yy_reduce_ofst[] = {
115433 /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
115434 /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
115435 /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
115436 /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
115437 /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
115438 /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
115439 /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
115440 /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
115441 /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
115442 /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
115443 /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
115444 /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
115445 /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
115446 /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
115447 /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
115448 /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
115449 /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
115450 /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
115451 /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
115452 /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
115453 /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
115454 /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
115455 /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
115456 /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
115457 /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
115458 /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
115459 /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
115460 /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
115461 /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
115462 /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
115463 /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
115465 static const YYACTIONTYPE yy_default[] = {
115466 /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
115467 /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
115468 /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
115469 /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
115470 /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
115471 /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115472 /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115473 /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115474 /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115475 /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
115476 /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
115477 /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
115478 /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115479 /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115480 /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
115481 /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
115482 /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
115483 /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115484 /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115485 /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115486 /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
115487 /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
115488 /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
115489 /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
115490 /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
115491 /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
115492 /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
115493 /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
115494 /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
115495 /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
115496 /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
115497 /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
115498 /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115499 /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
115500 /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115501 /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
115502 /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
115503 /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
115504 /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
115505 /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
115506 /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
115507 /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
115508 /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
115509 /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
115510 /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
115511 /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
115512 /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
115513 /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
115514 /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
115515 /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
115516 /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
115517 /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
115518 /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
115519 /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
115520 /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
115521 /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
115522 /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
115523 /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
115524 /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
115525 /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
115526 /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
115527 /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
115528 /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
115529 /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
115530 /* 640 */ 645, 643,
115533 /* The next table maps tokens into fallback tokens. If a construct
115534 ** like the following:
115536 ** %fallback ID X Y Z.
115538 ** appears in the grammar, then ID becomes a fallback token for X, Y,
115539 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
115540 ** but it does not parse, the type of the token is changed to ID and
115541 ** the parse is retried before an error is thrown.
115543 #ifdef YYFALLBACK
115544 static const YYCODETYPE yyFallback[] = {
115545 0, /* $ => nothing */
115546 0, /* SEMI => nothing */
115547 27, /* EXPLAIN => ID */
115548 27, /* QUERY => ID */
115549 27, /* PLAN => ID */
115550 27, /* BEGIN => ID */
115551 0, /* TRANSACTION => nothing */
115552 27, /* DEFERRED => ID */
115553 27, /* IMMEDIATE => ID */
115554 27, /* EXCLUSIVE => ID */
115555 0, /* COMMIT => nothing */
115556 27, /* END => ID */
115557 27, /* ROLLBACK => ID */
115558 27, /* SAVEPOINT => ID */
115559 27, /* RELEASE => ID */
115560 0, /* TO => nothing */
115561 0, /* TABLE => nothing */
115562 0, /* CREATE => nothing */
115563 27, /* IF => ID */
115564 0, /* NOT => nothing */
115565 0, /* EXISTS => nothing */
115566 27, /* TEMP => ID */
115567 0, /* LP => nothing */
115568 0, /* RP => nothing */
115569 0, /* AS => nothing */
115570 27, /* WITHOUT => ID */
115571 0, /* COMMA => nothing */
115572 0, /* ID => nothing */
115573 0, /* INDEXED => nothing */
115574 27, /* ABORT => ID */
115575 27, /* ACTION => ID */
115576 27, /* AFTER => ID */
115577 27, /* ANALYZE => ID */
115578 27, /* ASC => ID */
115579 27, /* ATTACH => ID */
115580 27, /* BEFORE => ID */
115581 27, /* BY => ID */
115582 27, /* CASCADE => ID */
115583 27, /* CAST => ID */
115584 27, /* COLUMNKW => ID */
115585 27, /* CONFLICT => ID */
115586 27, /* DATABASE => ID */
115587 27, /* DESC => ID */
115588 27, /* DETACH => ID */
115589 27, /* EACH => ID */
115590 27, /* FAIL => ID */
115591 27, /* FOR => ID */
115592 27, /* IGNORE => ID */
115593 27, /* INITIALLY => ID */
115594 27, /* INSTEAD => ID */
115595 27, /* LIKE_KW => ID */
115596 27, /* MATCH => ID */
115597 27, /* NO => ID */
115598 27, /* KEY => ID */
115599 27, /* OF => ID */
115600 27, /* OFFSET => ID */
115601 27, /* PRAGMA => ID */
115602 27, /* RAISE => ID */
115603 27, /* RECURSIVE => ID */
115604 27, /* REPLACE => ID */
115605 27, /* RESTRICT => ID */
115606 27, /* ROW => ID */
115607 27, /* TRIGGER => ID */
115608 27, /* VACUUM => ID */
115609 27, /* VIEW => ID */
115610 27, /* VIRTUAL => ID */
115611 27, /* WITH => ID */
115612 27, /* REINDEX => ID */
115613 27, /* RENAME => ID */
115614 27, /* CTIME_KW => ID */
115616 #endif /* YYFALLBACK */
115618 /* The following structure represents a single element of the
115619 ** parser's stack. Information stored includes:
115621 ** + The state number for the parser at this level of the stack.
115623 ** + The value of the token stored at this level of the stack.
115624 ** (In other words, the "major" token.)
115626 ** + The semantic value stored at this level of the stack. This is
115627 ** the information used by the action routines in the grammar.
115628 ** It is sometimes called the "minor" token.
115630 struct yyStackEntry {
115631 YYACTIONTYPE stateno; /* The state-number */
115632 YYCODETYPE major; /* The major token value. This is the code
115633 ** number for the token at this stack level */
115634 YYMINORTYPE minor; /* The user-supplied minor token value. This
115635 ** is the value of the token */
115637 typedef struct yyStackEntry yyStackEntry;
115639 /* The state of the parser is completely contained in an instance of
115640 ** the following structure */
115641 struct yyParser {
115642 int yyidx; /* Index of top element in stack */
115643 #ifdef YYTRACKMAXSTACKDEPTH
115644 int yyidxMax; /* Maximum value of yyidx */
115645 #endif
115646 int yyerrcnt; /* Shifts left before out of the error */
115647 sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
115648 #if YYSTACKDEPTH<=0
115649 int yystksz; /* Current side of the stack */
115650 yyStackEntry *yystack; /* The parser's stack */
115651 #else
115652 yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
115653 #endif
115655 typedef struct yyParser yyParser;
115657 #ifndef NDEBUG
115658 /* #include <stdio.h> */
115659 static FILE *yyTraceFILE = 0;
115660 static char *yyTracePrompt = 0;
115661 #endif /* NDEBUG */
115663 #ifndef NDEBUG
115665 ** Turn parser tracing on by giving a stream to which to write the trace
115666 ** and a prompt to preface each trace message. Tracing is turned off
115667 ** by making either argument NULL
115669 ** Inputs:
115670 ** <ul>
115671 ** <li> A FILE* to which trace output should be written.
115672 ** If NULL, then tracing is turned off.
115673 ** <li> A prefix string written at the beginning of every
115674 ** line of trace output. If NULL, then tracing is
115675 ** turned off.
115676 ** </ul>
115678 ** Outputs:
115679 ** None.
115681 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
115682 yyTraceFILE = TraceFILE;
115683 yyTracePrompt = zTracePrompt;
115684 if( yyTraceFILE==0 ) yyTracePrompt = 0;
115685 else if( yyTracePrompt==0 ) yyTraceFILE = 0;
115687 #endif /* NDEBUG */
115689 #ifndef NDEBUG
115690 /* For tracing shifts, the names of all terminals and nonterminals
115691 ** are required. The following table supplies these names */
115692 static const char *const yyTokenName[] = {
115693 "$", "SEMI", "EXPLAIN", "QUERY",
115694 "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
115695 "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
115696 "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
115697 "TABLE", "CREATE", "IF", "NOT",
115698 "EXISTS", "TEMP", "LP", "RP",
115699 "AS", "WITHOUT", "COMMA", "ID",
115700 "INDEXED", "ABORT", "ACTION", "AFTER",
115701 "ANALYZE", "ASC", "ATTACH", "BEFORE",
115702 "BY", "CASCADE", "CAST", "COLUMNKW",
115703 "CONFLICT", "DATABASE", "DESC", "DETACH",
115704 "EACH", "FAIL", "FOR", "IGNORE",
115705 "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
115706 "NO", "KEY", "OF", "OFFSET",
115707 "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
115708 "RESTRICT", "ROW", "TRIGGER", "VACUUM",
115709 "VIEW", "VIRTUAL", "WITH", "REINDEX",
115710 "RENAME", "CTIME_KW", "ANY", "OR",
115711 "AND", "IS", "BETWEEN", "IN",
115712 "ISNULL", "NOTNULL", "NE", "EQ",
115713 "GT", "LE", "LT", "GE",
115714 "ESCAPE", "BITAND", "BITOR", "LSHIFT",
115715 "RSHIFT", "PLUS", "MINUS", "STAR",
115716 "SLASH", "REM", "CONCAT", "COLLATE",
115717 "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
115718 "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
115719 "CHECK", "REFERENCES", "AUTOINCR", "ON",
115720 "INSERT", "DELETE", "UPDATE", "SET",
115721 "DEFERRABLE", "FOREIGN", "DROP", "UNION",
115722 "ALL", "EXCEPT", "INTERSECT", "SELECT",
115723 "VALUES", "DISTINCT", "DOT", "FROM",
115724 "JOIN", "USING", "ORDER", "GROUP",
115725 "HAVING", "LIMIT", "WHERE", "INTO",
115726 "INTEGER", "FLOAT", "BLOB", "VARIABLE",
115727 "CASE", "WHEN", "THEN", "ELSE",
115728 "INDEX", "ALTER", "ADD", "error",
115729 "input", "cmdlist", "ecmd", "explain",
115730 "cmdx", "cmd", "transtype", "trans_opt",
115731 "nm", "savepoint_opt", "create_table", "create_table_args",
115732 "createkw", "temp", "ifnotexists", "dbnm",
115733 "columnlist", "conslist_opt", "table_options", "select",
115734 "column", "columnid", "type", "carglist",
115735 "typetoken", "typename", "signed", "plus_num",
115736 "minus_num", "ccons", "term", "expr",
115737 "onconf", "sortorder", "autoinc", "idxlist_opt",
115738 "refargs", "defer_subclause", "refarg", "refact",
115739 "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
115740 "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
115741 "raisetype", "ifexists", "fullname", "selectnowith",
115742 "oneselect", "with", "multiselect_op", "distinct",
115743 "selcollist", "from", "where_opt", "groupby_opt",
115744 "having_opt", "orderby_opt", "limit_opt", "values",
115745 "nexprlist", "exprlist", "sclp", "as",
115746 "seltablist", "stl_prefix", "joinop", "indexed_opt",
115747 "on_opt", "using_opt", "joinop2", "idlist",
115748 "sortlist", "setlist", "insert_cmd", "inscollist_opt",
115749 "likeop", "between_op", "in_op", "case_operand",
115750 "case_exprlist", "case_else", "uniqueflag", "collate",
115751 "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
115752 "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
115753 "trnm", "tridxby", "database_kw_opt", "key_opt",
115754 "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
115755 "vtabarg", "vtabargtoken", "lp", "anylist",
115756 "wqlist",
115758 #endif /* NDEBUG */
115760 #ifndef NDEBUG
115761 /* For tracing reduce actions, the names of all rules are required.
115763 static const char *const yyRuleName[] = {
115764 /* 0 */ "input ::= cmdlist",
115765 /* 1 */ "cmdlist ::= cmdlist ecmd",
115766 /* 2 */ "cmdlist ::= ecmd",
115767 /* 3 */ "ecmd ::= SEMI",
115768 /* 4 */ "ecmd ::= explain cmdx SEMI",
115769 /* 5 */ "explain ::=",
115770 /* 6 */ "explain ::= EXPLAIN",
115771 /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
115772 /* 8 */ "cmdx ::= cmd",
115773 /* 9 */ "cmd ::= BEGIN transtype trans_opt",
115774 /* 10 */ "trans_opt ::=",
115775 /* 11 */ "trans_opt ::= TRANSACTION",
115776 /* 12 */ "trans_opt ::= TRANSACTION nm",
115777 /* 13 */ "transtype ::=",
115778 /* 14 */ "transtype ::= DEFERRED",
115779 /* 15 */ "transtype ::= IMMEDIATE",
115780 /* 16 */ "transtype ::= EXCLUSIVE",
115781 /* 17 */ "cmd ::= COMMIT trans_opt",
115782 /* 18 */ "cmd ::= END trans_opt",
115783 /* 19 */ "cmd ::= ROLLBACK trans_opt",
115784 /* 20 */ "savepoint_opt ::= SAVEPOINT",
115785 /* 21 */ "savepoint_opt ::=",
115786 /* 22 */ "cmd ::= SAVEPOINT nm",
115787 /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
115788 /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
115789 /* 25 */ "cmd ::= create_table create_table_args",
115790 /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
115791 /* 27 */ "createkw ::= CREATE",
115792 /* 28 */ "ifnotexists ::=",
115793 /* 29 */ "ifnotexists ::= IF NOT EXISTS",
115794 /* 30 */ "temp ::= TEMP",
115795 /* 31 */ "temp ::=",
115796 /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
115797 /* 33 */ "create_table_args ::= AS select",
115798 /* 34 */ "table_options ::=",
115799 /* 35 */ "table_options ::= WITHOUT nm",
115800 /* 36 */ "columnlist ::= columnlist COMMA column",
115801 /* 37 */ "columnlist ::= column",
115802 /* 38 */ "column ::= columnid type carglist",
115803 /* 39 */ "columnid ::= nm",
115804 /* 40 */ "nm ::= ID|INDEXED",
115805 /* 41 */ "nm ::= STRING",
115806 /* 42 */ "nm ::= JOIN_KW",
115807 /* 43 */ "type ::=",
115808 /* 44 */ "type ::= typetoken",
115809 /* 45 */ "typetoken ::= typename",
115810 /* 46 */ "typetoken ::= typename LP signed RP",
115811 /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
115812 /* 48 */ "typename ::= ID|STRING",
115813 /* 49 */ "typename ::= typename ID|STRING",
115814 /* 50 */ "signed ::= plus_num",
115815 /* 51 */ "signed ::= minus_num",
115816 /* 52 */ "carglist ::= carglist ccons",
115817 /* 53 */ "carglist ::=",
115818 /* 54 */ "ccons ::= CONSTRAINT nm",
115819 /* 55 */ "ccons ::= DEFAULT term",
115820 /* 56 */ "ccons ::= DEFAULT LP expr RP",
115821 /* 57 */ "ccons ::= DEFAULT PLUS term",
115822 /* 58 */ "ccons ::= DEFAULT MINUS term",
115823 /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
115824 /* 60 */ "ccons ::= NULL onconf",
115825 /* 61 */ "ccons ::= NOT NULL onconf",
115826 /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
115827 /* 63 */ "ccons ::= UNIQUE onconf",
115828 /* 64 */ "ccons ::= CHECK LP expr RP",
115829 /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
115830 /* 66 */ "ccons ::= defer_subclause",
115831 /* 67 */ "ccons ::= COLLATE ID|STRING",
115832 /* 68 */ "autoinc ::=",
115833 /* 69 */ "autoinc ::= AUTOINCR",
115834 /* 70 */ "refargs ::=",
115835 /* 71 */ "refargs ::= refargs refarg",
115836 /* 72 */ "refarg ::= MATCH nm",
115837 /* 73 */ "refarg ::= ON INSERT refact",
115838 /* 74 */ "refarg ::= ON DELETE refact",
115839 /* 75 */ "refarg ::= ON UPDATE refact",
115840 /* 76 */ "refact ::= SET NULL",
115841 /* 77 */ "refact ::= SET DEFAULT",
115842 /* 78 */ "refact ::= CASCADE",
115843 /* 79 */ "refact ::= RESTRICT",
115844 /* 80 */ "refact ::= NO ACTION",
115845 /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
115846 /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
115847 /* 83 */ "init_deferred_pred_opt ::=",
115848 /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
115849 /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
115850 /* 86 */ "conslist_opt ::=",
115851 /* 87 */ "conslist_opt ::= COMMA conslist",
115852 /* 88 */ "conslist ::= conslist tconscomma tcons",
115853 /* 89 */ "conslist ::= tcons",
115854 /* 90 */ "tconscomma ::= COMMA",
115855 /* 91 */ "tconscomma ::=",
115856 /* 92 */ "tcons ::= CONSTRAINT nm",
115857 /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
115858 /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
115859 /* 95 */ "tcons ::= CHECK LP expr RP onconf",
115860 /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
115861 /* 97 */ "defer_subclause_opt ::=",
115862 /* 98 */ "defer_subclause_opt ::= defer_subclause",
115863 /* 99 */ "onconf ::=",
115864 /* 100 */ "onconf ::= ON CONFLICT resolvetype",
115865 /* 101 */ "orconf ::=",
115866 /* 102 */ "orconf ::= OR resolvetype",
115867 /* 103 */ "resolvetype ::= raisetype",
115868 /* 104 */ "resolvetype ::= IGNORE",
115869 /* 105 */ "resolvetype ::= REPLACE",
115870 /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
115871 /* 107 */ "ifexists ::= IF EXISTS",
115872 /* 108 */ "ifexists ::=",
115873 /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
115874 /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
115875 /* 111 */ "cmd ::= select",
115876 /* 112 */ "select ::= with selectnowith",
115877 /* 113 */ "selectnowith ::= oneselect",
115878 /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
115879 /* 115 */ "multiselect_op ::= UNION",
115880 /* 116 */ "multiselect_op ::= UNION ALL",
115881 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
115882 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
115883 /* 119 */ "oneselect ::= values",
115884 /* 120 */ "values ::= VALUES LP nexprlist RP",
115885 /* 121 */ "values ::= values COMMA LP exprlist RP",
115886 /* 122 */ "distinct ::= DISTINCT",
115887 /* 123 */ "distinct ::= ALL",
115888 /* 124 */ "distinct ::=",
115889 /* 125 */ "sclp ::= selcollist COMMA",
115890 /* 126 */ "sclp ::=",
115891 /* 127 */ "selcollist ::= sclp expr as",
115892 /* 128 */ "selcollist ::= sclp STAR",
115893 /* 129 */ "selcollist ::= sclp nm DOT STAR",
115894 /* 130 */ "as ::= AS nm",
115895 /* 131 */ "as ::= ID|STRING",
115896 /* 132 */ "as ::=",
115897 /* 133 */ "from ::=",
115898 /* 134 */ "from ::= FROM seltablist",
115899 /* 135 */ "stl_prefix ::= seltablist joinop",
115900 /* 136 */ "stl_prefix ::=",
115901 /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
115902 /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
115903 /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
115904 /* 140 */ "dbnm ::=",
115905 /* 141 */ "dbnm ::= DOT nm",
115906 /* 142 */ "fullname ::= nm dbnm",
115907 /* 143 */ "joinop ::= COMMA|JOIN",
115908 /* 144 */ "joinop ::= JOIN_KW JOIN",
115909 /* 145 */ "joinop ::= JOIN_KW nm JOIN",
115910 /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
115911 /* 147 */ "on_opt ::= ON expr",
115912 /* 148 */ "on_opt ::=",
115913 /* 149 */ "indexed_opt ::=",
115914 /* 150 */ "indexed_opt ::= INDEXED BY nm",
115915 /* 151 */ "indexed_opt ::= NOT INDEXED",
115916 /* 152 */ "using_opt ::= USING LP idlist RP",
115917 /* 153 */ "using_opt ::=",
115918 /* 154 */ "orderby_opt ::=",
115919 /* 155 */ "orderby_opt ::= ORDER BY sortlist",
115920 /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
115921 /* 157 */ "sortlist ::= expr sortorder",
115922 /* 158 */ "sortorder ::= ASC",
115923 /* 159 */ "sortorder ::= DESC",
115924 /* 160 */ "sortorder ::=",
115925 /* 161 */ "groupby_opt ::=",
115926 /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
115927 /* 163 */ "having_opt ::=",
115928 /* 164 */ "having_opt ::= HAVING expr",
115929 /* 165 */ "limit_opt ::=",
115930 /* 166 */ "limit_opt ::= LIMIT expr",
115931 /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
115932 /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
115933 /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
115934 /* 170 */ "where_opt ::=",
115935 /* 171 */ "where_opt ::= WHERE expr",
115936 /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
115937 /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
115938 /* 174 */ "setlist ::= nm EQ expr",
115939 /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
115940 /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
115941 /* 177 */ "insert_cmd ::= INSERT orconf",
115942 /* 178 */ "insert_cmd ::= REPLACE",
115943 /* 179 */ "inscollist_opt ::=",
115944 /* 180 */ "inscollist_opt ::= LP idlist RP",
115945 /* 181 */ "idlist ::= idlist COMMA nm",
115946 /* 182 */ "idlist ::= nm",
115947 /* 183 */ "expr ::= term",
115948 /* 184 */ "expr ::= LP expr RP",
115949 /* 185 */ "term ::= NULL",
115950 /* 186 */ "expr ::= ID|INDEXED",
115951 /* 187 */ "expr ::= JOIN_KW",
115952 /* 188 */ "expr ::= nm DOT nm",
115953 /* 189 */ "expr ::= nm DOT nm DOT nm",
115954 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
115955 /* 191 */ "term ::= STRING",
115956 /* 192 */ "expr ::= VARIABLE",
115957 /* 193 */ "expr ::= expr COLLATE ID|STRING",
115958 /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
115959 /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
115960 /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
115961 /* 197 */ "term ::= CTIME_KW",
115962 /* 198 */ "expr ::= expr AND expr",
115963 /* 199 */ "expr ::= expr OR expr",
115964 /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
115965 /* 201 */ "expr ::= expr EQ|NE expr",
115966 /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
115967 /* 203 */ "expr ::= expr PLUS|MINUS expr",
115968 /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
115969 /* 205 */ "expr ::= expr CONCAT expr",
115970 /* 206 */ "likeop ::= LIKE_KW|MATCH",
115971 /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
115972 /* 208 */ "expr ::= expr likeop expr",
115973 /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
115974 /* 210 */ "expr ::= expr ISNULL|NOTNULL",
115975 /* 211 */ "expr ::= expr NOT NULL",
115976 /* 212 */ "expr ::= expr IS expr",
115977 /* 213 */ "expr ::= expr IS NOT expr",
115978 /* 214 */ "expr ::= NOT expr",
115979 /* 215 */ "expr ::= BITNOT expr",
115980 /* 216 */ "expr ::= MINUS expr",
115981 /* 217 */ "expr ::= PLUS expr",
115982 /* 218 */ "between_op ::= BETWEEN",
115983 /* 219 */ "between_op ::= NOT BETWEEN",
115984 /* 220 */ "expr ::= expr between_op expr AND expr",
115985 /* 221 */ "in_op ::= IN",
115986 /* 222 */ "in_op ::= NOT IN",
115987 /* 223 */ "expr ::= expr in_op LP exprlist RP",
115988 /* 224 */ "expr ::= LP select RP",
115989 /* 225 */ "expr ::= expr in_op LP select RP",
115990 /* 226 */ "expr ::= expr in_op nm dbnm",
115991 /* 227 */ "expr ::= EXISTS LP select RP",
115992 /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
115993 /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
115994 /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
115995 /* 231 */ "case_else ::= ELSE expr",
115996 /* 232 */ "case_else ::=",
115997 /* 233 */ "case_operand ::= expr",
115998 /* 234 */ "case_operand ::=",
115999 /* 235 */ "exprlist ::= nexprlist",
116000 /* 236 */ "exprlist ::=",
116001 /* 237 */ "nexprlist ::= nexprlist COMMA expr",
116002 /* 238 */ "nexprlist ::= expr",
116003 /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
116004 /* 240 */ "uniqueflag ::= UNIQUE",
116005 /* 241 */ "uniqueflag ::=",
116006 /* 242 */ "idxlist_opt ::=",
116007 /* 243 */ "idxlist_opt ::= LP idxlist RP",
116008 /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
116009 /* 245 */ "idxlist ::= nm collate sortorder",
116010 /* 246 */ "collate ::=",
116011 /* 247 */ "collate ::= COLLATE ID|STRING",
116012 /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
116013 /* 249 */ "cmd ::= VACUUM",
116014 /* 250 */ "cmd ::= VACUUM nm",
116015 /* 251 */ "cmd ::= PRAGMA nm dbnm",
116016 /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
116017 /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
116018 /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
116019 /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
116020 /* 256 */ "nmnum ::= plus_num",
116021 /* 257 */ "nmnum ::= nm",
116022 /* 258 */ "nmnum ::= ON",
116023 /* 259 */ "nmnum ::= DELETE",
116024 /* 260 */ "nmnum ::= DEFAULT",
116025 /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
116026 /* 262 */ "plus_num ::= INTEGER|FLOAT",
116027 /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
116028 /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
116029 /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
116030 /* 266 */ "trigger_time ::= BEFORE",
116031 /* 267 */ "trigger_time ::= AFTER",
116032 /* 268 */ "trigger_time ::= INSTEAD OF",
116033 /* 269 */ "trigger_time ::=",
116034 /* 270 */ "trigger_event ::= DELETE|INSERT",
116035 /* 271 */ "trigger_event ::= UPDATE",
116036 /* 272 */ "trigger_event ::= UPDATE OF idlist",
116037 /* 273 */ "foreach_clause ::=",
116038 /* 274 */ "foreach_clause ::= FOR EACH ROW",
116039 /* 275 */ "when_clause ::=",
116040 /* 276 */ "when_clause ::= WHEN expr",
116041 /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
116042 /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
116043 /* 279 */ "trnm ::= nm",
116044 /* 280 */ "trnm ::= nm DOT nm",
116045 /* 281 */ "tridxby ::=",
116046 /* 282 */ "tridxby ::= INDEXED BY nm",
116047 /* 283 */ "tridxby ::= NOT INDEXED",
116048 /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
116049 /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
116050 /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
116051 /* 287 */ "trigger_cmd ::= select",
116052 /* 288 */ "expr ::= RAISE LP IGNORE RP",
116053 /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
116054 /* 290 */ "raisetype ::= ROLLBACK",
116055 /* 291 */ "raisetype ::= ABORT",
116056 /* 292 */ "raisetype ::= FAIL",
116057 /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
116058 /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
116059 /* 295 */ "cmd ::= DETACH database_kw_opt expr",
116060 /* 296 */ "key_opt ::=",
116061 /* 297 */ "key_opt ::= KEY expr",
116062 /* 298 */ "database_kw_opt ::= DATABASE",
116063 /* 299 */ "database_kw_opt ::=",
116064 /* 300 */ "cmd ::= REINDEX",
116065 /* 301 */ "cmd ::= REINDEX nm dbnm",
116066 /* 302 */ "cmd ::= ANALYZE",
116067 /* 303 */ "cmd ::= ANALYZE nm dbnm",
116068 /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
116069 /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
116070 /* 306 */ "add_column_fullname ::= fullname",
116071 /* 307 */ "kwcolumn_opt ::=",
116072 /* 308 */ "kwcolumn_opt ::= COLUMNKW",
116073 /* 309 */ "cmd ::= create_vtab",
116074 /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
116075 /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
116076 /* 312 */ "vtabarglist ::= vtabarg",
116077 /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
116078 /* 314 */ "vtabarg ::=",
116079 /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
116080 /* 316 */ "vtabargtoken ::= ANY",
116081 /* 317 */ "vtabargtoken ::= lp anylist RP",
116082 /* 318 */ "lp ::= LP",
116083 /* 319 */ "anylist ::=",
116084 /* 320 */ "anylist ::= anylist LP anylist RP",
116085 /* 321 */ "anylist ::= anylist ANY",
116086 /* 322 */ "with ::=",
116087 /* 323 */ "with ::= WITH wqlist",
116088 /* 324 */ "with ::= WITH RECURSIVE wqlist",
116089 /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
116090 /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
116092 #endif /* NDEBUG */
116095 #if YYSTACKDEPTH<=0
116097 ** Try to increase the size of the parser stack.
116099 static void yyGrowStack(yyParser *p){
116100 int newSize;
116101 yyStackEntry *pNew;
116103 newSize = p->yystksz*2 + 100;
116104 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
116105 if( pNew ){
116106 p->yystack = pNew;
116107 p->yystksz = newSize;
116108 #ifndef NDEBUG
116109 if( yyTraceFILE ){
116110 fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
116111 yyTracePrompt, p->yystksz);
116113 #endif
116116 #endif
116119 ** This function allocates a new parser.
116120 ** The only argument is a pointer to a function which works like
116121 ** malloc.
116123 ** Inputs:
116124 ** A pointer to the function used to allocate memory.
116126 ** Outputs:
116127 ** A pointer to a parser. This pointer is used in subsequent calls
116128 ** to sqlite3Parser and sqlite3ParserFree.
116130 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
116131 yyParser *pParser;
116132 pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
116133 if( pParser ){
116134 pParser->yyidx = -1;
116135 #ifdef YYTRACKMAXSTACKDEPTH
116136 pParser->yyidxMax = 0;
116137 #endif
116138 #if YYSTACKDEPTH<=0
116139 pParser->yystack = NULL;
116140 pParser->yystksz = 0;
116141 yyGrowStack(pParser);
116142 #endif
116144 return pParser;
116147 /* The following function deletes the value associated with a
116148 ** symbol. The symbol can be either a terminal or nonterminal.
116149 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
116150 ** the value.
116152 static void yy_destructor(
116153 yyParser *yypParser, /* The parser */
116154 YYCODETYPE yymajor, /* Type code for object to destroy */
116155 YYMINORTYPE *yypminor /* The object to be destroyed */
116157 sqlite3ParserARG_FETCH;
116158 switch( yymajor ){
116159 /* Here is inserted the actions which take place when a
116160 ** terminal or non-terminal is destroyed. This can happen
116161 ** when the symbol is popped from the stack during a
116162 ** reduce or during error processing or when a parser is
116163 ** being destroyed before it is finished parsing.
116165 ** Note: during a reduce, the only symbols destroyed are those
116166 ** which appear on the RHS of the rule, but which are not used
116167 ** inside the C code.
116169 case 163: /* select */
116170 case 195: /* selectnowith */
116171 case 196: /* oneselect */
116172 case 207: /* values */
116174 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
116176 break;
116177 case 174: /* term */
116178 case 175: /* expr */
116180 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
116182 break;
116183 case 179: /* idxlist_opt */
116184 case 188: /* idxlist */
116185 case 200: /* selcollist */
116186 case 203: /* groupby_opt */
116187 case 205: /* orderby_opt */
116188 case 208: /* nexprlist */
116189 case 209: /* exprlist */
116190 case 210: /* sclp */
116191 case 220: /* sortlist */
116192 case 221: /* setlist */
116193 case 228: /* case_exprlist */
116195 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
116197 break;
116198 case 194: /* fullname */
116199 case 201: /* from */
116200 case 212: /* seltablist */
116201 case 213: /* stl_prefix */
116203 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
116205 break;
116206 case 197: /* with */
116207 case 252: /* wqlist */
116209 sqlite3WithDelete(pParse->db, (yypminor->yy59));
116211 break;
116212 case 202: /* where_opt */
116213 case 204: /* having_opt */
116214 case 216: /* on_opt */
116215 case 227: /* case_operand */
116216 case 229: /* case_else */
116217 case 238: /* when_clause */
116218 case 243: /* key_opt */
116220 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
116222 break;
116223 case 217: /* using_opt */
116224 case 219: /* idlist */
116225 case 223: /* inscollist_opt */
116227 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
116229 break;
116230 case 234: /* trigger_cmd_list */
116231 case 239: /* trigger_cmd */
116233 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
116235 break;
116236 case 236: /* trigger_event */
116238 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
116240 break;
116241 default: break; /* If no destructor action specified: do nothing */
116246 ** Pop the parser's stack once.
116248 ** If there is a destructor routine associated with the token which
116249 ** is popped from the stack, then call it.
116251 ** Return the major token number for the symbol popped.
116253 static int yy_pop_parser_stack(yyParser *pParser){
116254 YYCODETYPE yymajor;
116255 yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
116257 /* There is no mechanism by which the parser stack can be popped below
116258 ** empty in SQLite. */
116259 if( NEVER(pParser->yyidx<0) ) return 0;
116260 #ifndef NDEBUG
116261 if( yyTraceFILE && pParser->yyidx>=0 ){
116262 fprintf(yyTraceFILE,"%sPopping %s\n",
116263 yyTracePrompt,
116264 yyTokenName[yytos->major]);
116266 #endif
116267 yymajor = yytos->major;
116268 yy_destructor(pParser, yymajor, &yytos->minor);
116269 pParser->yyidx--;
116270 return yymajor;
116274 ** Deallocate and destroy a parser. Destructors are all called for
116275 ** all stack elements before shutting the parser down.
116277 ** Inputs:
116278 ** <ul>
116279 ** <li> A pointer to the parser. This should be a pointer
116280 ** obtained from sqlite3ParserAlloc.
116281 ** <li> A pointer to a function used to reclaim memory obtained
116282 ** from malloc.
116283 ** </ul>
116285 SQLITE_PRIVATE void sqlite3ParserFree(
116286 void *p, /* The parser to be deleted */
116287 void (*freeProc)(void*) /* Function used to reclaim memory */
116289 yyParser *pParser = (yyParser*)p;
116290 /* In SQLite, we never try to destroy a parser that was not successfully
116291 ** created in the first place. */
116292 if( NEVER(pParser==0) ) return;
116293 while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
116294 #if YYSTACKDEPTH<=0
116295 free(pParser->yystack);
116296 #endif
116297 (*freeProc)((void*)pParser);
116301 ** Return the peak depth of the stack for a parser.
116303 #ifdef YYTRACKMAXSTACKDEPTH
116304 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
116305 yyParser *pParser = (yyParser*)p;
116306 return pParser->yyidxMax;
116308 #endif
116311 ** Find the appropriate action for a parser given the terminal
116312 ** look-ahead token iLookAhead.
116314 ** If the look-ahead token is YYNOCODE, then check to see if the action is
116315 ** independent of the look-ahead. If it is, return the action, otherwise
116316 ** return YY_NO_ACTION.
116318 static int yy_find_shift_action(
116319 yyParser *pParser, /* The parser */
116320 YYCODETYPE iLookAhead /* The look-ahead token */
116322 int i;
116323 int stateno = pParser->yystack[pParser->yyidx].stateno;
116325 if( stateno>YY_SHIFT_COUNT
116326 || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
116327 return yy_default[stateno];
116329 assert( iLookAhead!=YYNOCODE );
116330 i += iLookAhead;
116331 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
116332 if( iLookAhead>0 ){
116333 #ifdef YYFALLBACK
116334 YYCODETYPE iFallback; /* Fallback token */
116335 if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
116336 && (iFallback = yyFallback[iLookAhead])!=0 ){
116337 #ifndef NDEBUG
116338 if( yyTraceFILE ){
116339 fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
116340 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
116342 #endif
116343 return yy_find_shift_action(pParser, iFallback);
116345 #endif
116346 #ifdef YYWILDCARD
116348 int j = i - iLookAhead + YYWILDCARD;
116350 #if YY_SHIFT_MIN+YYWILDCARD<0
116351 j>=0 &&
116352 #endif
116353 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
116354 j<YY_ACTTAB_COUNT &&
116355 #endif
116356 yy_lookahead[j]==YYWILDCARD
116358 #ifndef NDEBUG
116359 if( yyTraceFILE ){
116360 fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
116361 yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
116363 #endif /* NDEBUG */
116364 return yy_action[j];
116367 #endif /* YYWILDCARD */
116369 return yy_default[stateno];
116370 }else{
116371 return yy_action[i];
116376 ** Find the appropriate action for a parser given the non-terminal
116377 ** look-ahead token iLookAhead.
116379 ** If the look-ahead token is YYNOCODE, then check to see if the action is
116380 ** independent of the look-ahead. If it is, return the action, otherwise
116381 ** return YY_NO_ACTION.
116383 static int yy_find_reduce_action(
116384 int stateno, /* Current state number */
116385 YYCODETYPE iLookAhead /* The look-ahead token */
116387 int i;
116388 #ifdef YYERRORSYMBOL
116389 if( stateno>YY_REDUCE_COUNT ){
116390 return yy_default[stateno];
116392 #else
116393 assert( stateno<=YY_REDUCE_COUNT );
116394 #endif
116395 i = yy_reduce_ofst[stateno];
116396 assert( i!=YY_REDUCE_USE_DFLT );
116397 assert( iLookAhead!=YYNOCODE );
116398 i += iLookAhead;
116399 #ifdef YYERRORSYMBOL
116400 if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
116401 return yy_default[stateno];
116403 #else
116404 assert( i>=0 && i<YY_ACTTAB_COUNT );
116405 assert( yy_lookahead[i]==iLookAhead );
116406 #endif
116407 return yy_action[i];
116411 ** The following routine is called if the stack overflows.
116413 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
116414 sqlite3ParserARG_FETCH;
116415 yypParser->yyidx--;
116416 #ifndef NDEBUG
116417 if( yyTraceFILE ){
116418 fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
116420 #endif
116421 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
116422 /* Here code is inserted which will execute if the parser
116423 ** stack every overflows */
116425 UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
116426 sqlite3ErrorMsg(pParse, "parser stack overflow");
116427 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
116431 ** Perform a shift action.
116433 static void yy_shift(
116434 yyParser *yypParser, /* The parser to be shifted */
116435 int yyNewState, /* The new state to shift in */
116436 int yyMajor, /* The major token to shift in */
116437 YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
116439 yyStackEntry *yytos;
116440 yypParser->yyidx++;
116441 #ifdef YYTRACKMAXSTACKDEPTH
116442 if( yypParser->yyidx>yypParser->yyidxMax ){
116443 yypParser->yyidxMax = yypParser->yyidx;
116445 #endif
116446 #if YYSTACKDEPTH>0
116447 if( yypParser->yyidx>=YYSTACKDEPTH ){
116448 yyStackOverflow(yypParser, yypMinor);
116449 return;
116451 #else
116452 if( yypParser->yyidx>=yypParser->yystksz ){
116453 yyGrowStack(yypParser);
116454 if( yypParser->yyidx>=yypParser->yystksz ){
116455 yyStackOverflow(yypParser, yypMinor);
116456 return;
116459 #endif
116460 yytos = &yypParser->yystack[yypParser->yyidx];
116461 yytos->stateno = (YYACTIONTYPE)yyNewState;
116462 yytos->major = (YYCODETYPE)yyMajor;
116463 yytos->minor = *yypMinor;
116464 #ifndef NDEBUG
116465 if( yyTraceFILE && yypParser->yyidx>0 ){
116466 int i;
116467 fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
116468 fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
116469 for(i=1; i<=yypParser->yyidx; i++)
116470 fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
116471 fprintf(yyTraceFILE,"\n");
116473 #endif
116476 /* The following table contains information about every rule that
116477 ** is used during the reduce.
116479 static const struct {
116480 YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
116481 unsigned char nrhs; /* Number of right-hand side symbols in the rule */
116482 } yyRuleInfo[] = {
116483 { 144, 1 },
116484 { 145, 2 },
116485 { 145, 1 },
116486 { 146, 1 },
116487 { 146, 3 },
116488 { 147, 0 },
116489 { 147, 1 },
116490 { 147, 3 },
116491 { 148, 1 },
116492 { 149, 3 },
116493 { 151, 0 },
116494 { 151, 1 },
116495 { 151, 2 },
116496 { 150, 0 },
116497 { 150, 1 },
116498 { 150, 1 },
116499 { 150, 1 },
116500 { 149, 2 },
116501 { 149, 2 },
116502 { 149, 2 },
116503 { 153, 1 },
116504 { 153, 0 },
116505 { 149, 2 },
116506 { 149, 3 },
116507 { 149, 5 },
116508 { 149, 2 },
116509 { 154, 6 },
116510 { 156, 1 },
116511 { 158, 0 },
116512 { 158, 3 },
116513 { 157, 1 },
116514 { 157, 0 },
116515 { 155, 5 },
116516 { 155, 2 },
116517 { 162, 0 },
116518 { 162, 2 },
116519 { 160, 3 },
116520 { 160, 1 },
116521 { 164, 3 },
116522 { 165, 1 },
116523 { 152, 1 },
116524 { 152, 1 },
116525 { 152, 1 },
116526 { 166, 0 },
116527 { 166, 1 },
116528 { 168, 1 },
116529 { 168, 4 },
116530 { 168, 6 },
116531 { 169, 1 },
116532 { 169, 2 },
116533 { 170, 1 },
116534 { 170, 1 },
116535 { 167, 2 },
116536 { 167, 0 },
116537 { 173, 2 },
116538 { 173, 2 },
116539 { 173, 4 },
116540 { 173, 3 },
116541 { 173, 3 },
116542 { 173, 2 },
116543 { 173, 2 },
116544 { 173, 3 },
116545 { 173, 5 },
116546 { 173, 2 },
116547 { 173, 4 },
116548 { 173, 4 },
116549 { 173, 1 },
116550 { 173, 2 },
116551 { 178, 0 },
116552 { 178, 1 },
116553 { 180, 0 },
116554 { 180, 2 },
116555 { 182, 2 },
116556 { 182, 3 },
116557 { 182, 3 },
116558 { 182, 3 },
116559 { 183, 2 },
116560 { 183, 2 },
116561 { 183, 1 },
116562 { 183, 1 },
116563 { 183, 2 },
116564 { 181, 3 },
116565 { 181, 2 },
116566 { 184, 0 },
116567 { 184, 2 },
116568 { 184, 2 },
116569 { 161, 0 },
116570 { 161, 2 },
116571 { 185, 3 },
116572 { 185, 1 },
116573 { 186, 1 },
116574 { 186, 0 },
116575 { 187, 2 },
116576 { 187, 7 },
116577 { 187, 5 },
116578 { 187, 5 },
116579 { 187, 10 },
116580 { 189, 0 },
116581 { 189, 1 },
116582 { 176, 0 },
116583 { 176, 3 },
116584 { 190, 0 },
116585 { 190, 2 },
116586 { 191, 1 },
116587 { 191, 1 },
116588 { 191, 1 },
116589 { 149, 4 },
116590 { 193, 2 },
116591 { 193, 0 },
116592 { 149, 8 },
116593 { 149, 4 },
116594 { 149, 1 },
116595 { 163, 2 },
116596 { 195, 1 },
116597 { 195, 3 },
116598 { 198, 1 },
116599 { 198, 2 },
116600 { 198, 1 },
116601 { 196, 9 },
116602 { 196, 1 },
116603 { 207, 4 },
116604 { 207, 5 },
116605 { 199, 1 },
116606 { 199, 1 },
116607 { 199, 0 },
116608 { 210, 2 },
116609 { 210, 0 },
116610 { 200, 3 },
116611 { 200, 2 },
116612 { 200, 4 },
116613 { 211, 2 },
116614 { 211, 1 },
116615 { 211, 0 },
116616 { 201, 0 },
116617 { 201, 2 },
116618 { 213, 2 },
116619 { 213, 0 },
116620 { 212, 7 },
116621 { 212, 7 },
116622 { 212, 7 },
116623 { 159, 0 },
116624 { 159, 2 },
116625 { 194, 2 },
116626 { 214, 1 },
116627 { 214, 2 },
116628 { 214, 3 },
116629 { 214, 4 },
116630 { 216, 2 },
116631 { 216, 0 },
116632 { 215, 0 },
116633 { 215, 3 },
116634 { 215, 2 },
116635 { 217, 4 },
116636 { 217, 0 },
116637 { 205, 0 },
116638 { 205, 3 },
116639 { 220, 4 },
116640 { 220, 2 },
116641 { 177, 1 },
116642 { 177, 1 },
116643 { 177, 0 },
116644 { 203, 0 },
116645 { 203, 3 },
116646 { 204, 0 },
116647 { 204, 2 },
116648 { 206, 0 },
116649 { 206, 2 },
116650 { 206, 4 },
116651 { 206, 4 },
116652 { 149, 6 },
116653 { 202, 0 },
116654 { 202, 2 },
116655 { 149, 8 },
116656 { 221, 5 },
116657 { 221, 3 },
116658 { 149, 6 },
116659 { 149, 7 },
116660 { 222, 2 },
116661 { 222, 1 },
116662 { 223, 0 },
116663 { 223, 3 },
116664 { 219, 3 },
116665 { 219, 1 },
116666 { 175, 1 },
116667 { 175, 3 },
116668 { 174, 1 },
116669 { 175, 1 },
116670 { 175, 1 },
116671 { 175, 3 },
116672 { 175, 5 },
116673 { 174, 1 },
116674 { 174, 1 },
116675 { 175, 1 },
116676 { 175, 3 },
116677 { 175, 6 },
116678 { 175, 5 },
116679 { 175, 4 },
116680 { 174, 1 },
116681 { 175, 3 },
116682 { 175, 3 },
116683 { 175, 3 },
116684 { 175, 3 },
116685 { 175, 3 },
116686 { 175, 3 },
116687 { 175, 3 },
116688 { 175, 3 },
116689 { 224, 1 },
116690 { 224, 2 },
116691 { 175, 3 },
116692 { 175, 5 },
116693 { 175, 2 },
116694 { 175, 3 },
116695 { 175, 3 },
116696 { 175, 4 },
116697 { 175, 2 },
116698 { 175, 2 },
116699 { 175, 2 },
116700 { 175, 2 },
116701 { 225, 1 },
116702 { 225, 2 },
116703 { 175, 5 },
116704 { 226, 1 },
116705 { 226, 2 },
116706 { 175, 5 },
116707 { 175, 3 },
116708 { 175, 5 },
116709 { 175, 4 },
116710 { 175, 4 },
116711 { 175, 5 },
116712 { 228, 5 },
116713 { 228, 4 },
116714 { 229, 2 },
116715 { 229, 0 },
116716 { 227, 1 },
116717 { 227, 0 },
116718 { 209, 1 },
116719 { 209, 0 },
116720 { 208, 3 },
116721 { 208, 1 },
116722 { 149, 12 },
116723 { 230, 1 },
116724 { 230, 0 },
116725 { 179, 0 },
116726 { 179, 3 },
116727 { 188, 5 },
116728 { 188, 3 },
116729 { 231, 0 },
116730 { 231, 2 },
116731 { 149, 4 },
116732 { 149, 1 },
116733 { 149, 2 },
116734 { 149, 3 },
116735 { 149, 5 },
116736 { 149, 6 },
116737 { 149, 5 },
116738 { 149, 6 },
116739 { 232, 1 },
116740 { 232, 1 },
116741 { 232, 1 },
116742 { 232, 1 },
116743 { 232, 1 },
116744 { 171, 2 },
116745 { 171, 1 },
116746 { 172, 2 },
116747 { 149, 5 },
116748 { 233, 11 },
116749 { 235, 1 },
116750 { 235, 1 },
116751 { 235, 2 },
116752 { 235, 0 },
116753 { 236, 1 },
116754 { 236, 1 },
116755 { 236, 3 },
116756 { 237, 0 },
116757 { 237, 3 },
116758 { 238, 0 },
116759 { 238, 2 },
116760 { 234, 3 },
116761 { 234, 2 },
116762 { 240, 1 },
116763 { 240, 3 },
116764 { 241, 0 },
116765 { 241, 3 },
116766 { 241, 2 },
116767 { 239, 7 },
116768 { 239, 5 },
116769 { 239, 5 },
116770 { 239, 1 },
116771 { 175, 4 },
116772 { 175, 6 },
116773 { 192, 1 },
116774 { 192, 1 },
116775 { 192, 1 },
116776 { 149, 4 },
116777 { 149, 6 },
116778 { 149, 3 },
116779 { 243, 0 },
116780 { 243, 2 },
116781 { 242, 1 },
116782 { 242, 0 },
116783 { 149, 1 },
116784 { 149, 3 },
116785 { 149, 1 },
116786 { 149, 3 },
116787 { 149, 6 },
116788 { 149, 6 },
116789 { 244, 1 },
116790 { 245, 0 },
116791 { 245, 1 },
116792 { 149, 1 },
116793 { 149, 4 },
116794 { 246, 8 },
116795 { 247, 1 },
116796 { 247, 3 },
116797 { 248, 0 },
116798 { 248, 2 },
116799 { 249, 1 },
116800 { 249, 3 },
116801 { 250, 1 },
116802 { 251, 0 },
116803 { 251, 4 },
116804 { 251, 2 },
116805 { 197, 0 },
116806 { 197, 2 },
116807 { 197, 3 },
116808 { 252, 6 },
116809 { 252, 8 },
116812 static void yy_accept(yyParser*); /* Forward Declaration */
116815 ** Perform a reduce action and the shift that must immediately
116816 ** follow the reduce.
116818 static void yy_reduce(
116819 yyParser *yypParser, /* The parser */
116820 int yyruleno /* Number of the rule by which to reduce */
116822 int yygoto; /* The next state */
116823 int yyact; /* The next action */
116824 YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
116825 yyStackEntry *yymsp; /* The top of the parser's stack */
116826 int yysize; /* Amount to pop the stack */
116827 sqlite3ParserARG_FETCH;
116828 yymsp = &yypParser->yystack[yypParser->yyidx];
116829 #ifndef NDEBUG
116830 if( yyTraceFILE && yyruleno>=0
116831 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
116832 fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
116833 yyRuleName[yyruleno]);
116835 #endif /* NDEBUG */
116837 /* Silence complaints from purify about yygotominor being uninitialized
116838 ** in some cases when it is copied into the stack after the following
116839 ** switch. yygotominor is uninitialized when a rule reduces that does
116840 ** not set the value of its left-hand side nonterminal. Leaving the
116841 ** value of the nonterminal uninitialized is utterly harmless as long
116842 ** as the value is never used. So really the only thing this code
116843 ** accomplishes is to quieten purify.
116845 ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
116846 ** without this code, their parser segfaults. I'm not sure what there
116847 ** parser is doing to make this happen. This is the second bug report
116848 ** from wireshark this week. Clearly they are stressing Lemon in ways
116849 ** that it has not been previously stressed... (SQLite ticket #2172)
116851 /*memset(&yygotominor, 0, sizeof(yygotominor));*/
116852 yygotominor = yyzerominor;
116855 switch( yyruleno ){
116856 /* Beginning here are the reduction cases. A typical example
116857 ** follows:
116858 ** case 0:
116859 ** #line <lineno> <grammarfile>
116860 ** { ... } // User supplied code
116861 ** #line <lineno> <thisfile>
116862 ** break;
116864 case 5: /* explain ::= */
116865 { sqlite3BeginParse(pParse, 0); }
116866 break;
116867 case 6: /* explain ::= EXPLAIN */
116868 { sqlite3BeginParse(pParse, 1); }
116869 break;
116870 case 7: /* explain ::= EXPLAIN QUERY PLAN */
116871 { sqlite3BeginParse(pParse, 2); }
116872 break;
116873 case 8: /* cmdx ::= cmd */
116874 { sqlite3FinishCoding(pParse); }
116875 break;
116876 case 9: /* cmd ::= BEGIN transtype trans_opt */
116877 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
116878 break;
116879 case 13: /* transtype ::= */
116880 {yygotominor.yy328 = TK_DEFERRED;}
116881 break;
116882 case 14: /* transtype ::= DEFERRED */
116883 case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
116884 case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
116885 case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
116886 case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
116887 {yygotominor.yy328 = yymsp[0].major;}
116888 break;
116889 case 17: /* cmd ::= COMMIT trans_opt */
116890 case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
116891 {sqlite3CommitTransaction(pParse);}
116892 break;
116893 case 19: /* cmd ::= ROLLBACK trans_opt */
116894 {sqlite3RollbackTransaction(pParse);}
116895 break;
116896 case 22: /* cmd ::= SAVEPOINT nm */
116898 sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
116900 break;
116901 case 23: /* cmd ::= RELEASE savepoint_opt nm */
116903 sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
116905 break;
116906 case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
116908 sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
116910 break;
116911 case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
116913 sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
116915 break;
116916 case 27: /* createkw ::= CREATE */
116918 pParse->db->lookaside.bEnabled = 0;
116919 yygotominor.yy0 = yymsp[0].minor.yy0;
116921 break;
116922 case 28: /* ifnotexists ::= */
116923 case 31: /* temp ::= */ yytestcase(yyruleno==31);
116924 case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
116925 case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
116926 case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
116927 case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
116928 case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
116929 case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
116930 case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
116931 case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
116932 {yygotominor.yy328 = 0;}
116933 break;
116934 case 29: /* ifnotexists ::= IF NOT EXISTS */
116935 case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
116936 case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
116937 case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
116938 case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
116939 case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
116940 case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
116941 {yygotominor.yy328 = 1;}
116942 break;
116943 case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
116945 sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
116947 break;
116948 case 33: /* create_table_args ::= AS select */
116950 sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
116951 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
116953 break;
116954 case 34: /* table_options ::= */
116955 {yygotominor.yy186 = 0;}
116956 break;
116957 case 35: /* table_options ::= WITHOUT nm */
116959 if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
116960 yygotominor.yy186 = TF_WithoutRowid;
116961 }else{
116962 yygotominor.yy186 = 0;
116963 sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
116966 break;
116967 case 38: /* column ::= columnid type carglist */
116969 yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
116970 yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
116972 break;
116973 case 39: /* columnid ::= nm */
116975 sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
116976 yygotominor.yy0 = yymsp[0].minor.yy0;
116977 pParse->constraintName.n = 0;
116979 break;
116980 case 40: /* nm ::= ID|INDEXED */
116981 case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
116982 case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
116983 case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
116984 case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
116985 case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
116986 case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
116987 case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
116988 case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
116989 case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
116990 case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
116991 case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
116992 case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
116993 case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
116994 case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
116995 case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
116996 case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
116997 case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
116998 case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
116999 {yygotominor.yy0 = yymsp[0].minor.yy0;}
117000 break;
117001 case 44: /* type ::= typetoken */
117002 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
117003 break;
117004 case 46: /* typetoken ::= typename LP signed RP */
117006 yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
117007 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
117009 break;
117010 case 47: /* typetoken ::= typename LP signed COMMA signed RP */
117012 yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
117013 yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
117015 break;
117016 case 49: /* typename ::= typename ID|STRING */
117017 {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);}
117018 break;
117019 case 54: /* ccons ::= CONSTRAINT nm */
117020 case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
117021 {pParse->constraintName = yymsp[0].minor.yy0;}
117022 break;
117023 case 55: /* ccons ::= DEFAULT term */
117024 case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
117025 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
117026 break;
117027 case 56: /* ccons ::= DEFAULT LP expr RP */
117028 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
117029 break;
117030 case 58: /* ccons ::= DEFAULT MINUS term */
117032 ExprSpan v;
117033 v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
117034 v.zStart = yymsp[-1].minor.yy0.z;
117035 v.zEnd = yymsp[0].minor.yy346.zEnd;
117036 sqlite3AddDefaultValue(pParse,&v);
117038 break;
117039 case 59: /* ccons ::= DEFAULT ID|INDEXED */
117041 ExprSpan v;
117042 spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
117043 sqlite3AddDefaultValue(pParse,&v);
117045 break;
117046 case 61: /* ccons ::= NOT NULL onconf */
117047 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
117048 break;
117049 case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
117050 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
117051 break;
117052 case 63: /* ccons ::= UNIQUE onconf */
117053 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
117054 break;
117055 case 64: /* ccons ::= CHECK LP expr RP */
117056 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
117057 break;
117058 case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
117059 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
117060 break;
117061 case 66: /* ccons ::= defer_subclause */
117062 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
117063 break;
117064 case 67: /* ccons ::= COLLATE ID|STRING */
117065 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
117066 break;
117067 case 70: /* refargs ::= */
117068 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
117069 break;
117070 case 71: /* refargs ::= refargs refarg */
117071 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
117072 break;
117073 case 72: /* refarg ::= MATCH nm */
117074 case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
117075 { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
117076 break;
117077 case 74: /* refarg ::= ON DELETE refact */
117078 { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
117079 break;
117080 case 75: /* refarg ::= ON UPDATE refact */
117081 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
117082 break;
117083 case 76: /* refact ::= SET NULL */
117084 { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
117085 break;
117086 case 77: /* refact ::= SET DEFAULT */
117087 { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
117088 break;
117089 case 78: /* refact ::= CASCADE */
117090 { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
117091 break;
117092 case 79: /* refact ::= RESTRICT */
117093 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
117094 break;
117095 case 80: /* refact ::= NO ACTION */
117096 { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
117097 break;
117098 case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
117099 case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
117100 case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
117101 case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
117102 {yygotominor.yy328 = yymsp[0].minor.yy328;}
117103 break;
117104 case 86: /* conslist_opt ::= */
117105 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
117106 break;
117107 case 87: /* conslist_opt ::= COMMA conslist */
117108 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
117109 break;
117110 case 90: /* tconscomma ::= COMMA */
117111 {pParse->constraintName.n = 0;}
117112 break;
117113 case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
117114 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
117115 break;
117116 case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
117117 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
117118 break;
117119 case 95: /* tcons ::= CHECK LP expr RP onconf */
117120 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
117121 break;
117122 case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
117124 sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
117125 sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
117127 break;
117128 case 99: /* onconf ::= */
117129 {yygotominor.yy328 = OE_Default;}
117130 break;
117131 case 101: /* orconf ::= */
117132 {yygotominor.yy186 = OE_Default;}
117133 break;
117134 case 102: /* orconf ::= OR resolvetype */
117135 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
117136 break;
117137 case 104: /* resolvetype ::= IGNORE */
117138 {yygotominor.yy328 = OE_Ignore;}
117139 break;
117140 case 105: /* resolvetype ::= REPLACE */
117141 {yygotominor.yy328 = OE_Replace;}
117142 break;
117143 case 106: /* cmd ::= DROP TABLE ifexists fullname */
117145 sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
117147 break;
117148 case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
117150 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);
117152 break;
117153 case 110: /* cmd ::= DROP VIEW ifexists fullname */
117155 sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
117157 break;
117158 case 111: /* cmd ::= select */
117160 SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
117161 sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
117162 sqlite3ExplainBegin(pParse->pVdbe);
117163 sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy3);
117164 sqlite3ExplainFinish(pParse->pVdbe);
117165 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
117167 break;
117168 case 112: /* select ::= with selectnowith */
117170 if( yymsp[0].minor.yy3 ){
117171 yymsp[0].minor.yy3->pWith = yymsp[-1].minor.yy59;
117172 }else{
117173 sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
117175 yygotominor.yy3 = yymsp[0].minor.yy3;
117177 break;
117178 case 113: /* selectnowith ::= oneselect */
117179 case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
117180 {yygotominor.yy3 = yymsp[0].minor.yy3;}
117181 break;
117182 case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
117184 if( yymsp[0].minor.yy3 ){
117185 yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
117186 yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
117187 if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
117188 }else{
117189 sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
117191 yygotominor.yy3 = yymsp[0].minor.yy3;
117193 break;
117194 case 116: /* multiselect_op ::= UNION ALL */
117195 {yygotominor.yy328 = TK_ALL;}
117196 break;
117197 case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
117199 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);
117201 break;
117202 case 120: /* values ::= VALUES LP nexprlist RP */
117204 yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
117206 break;
117207 case 121: /* values ::= values COMMA LP exprlist RP */
117209 Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
117210 if( pRight ){
117211 pRight->op = TK_ALL;
117212 pRight->pPrior = yymsp[-4].minor.yy3;
117213 yygotominor.yy3 = pRight;
117214 }else{
117215 yygotominor.yy3 = yymsp[-4].minor.yy3;
117218 break;
117219 case 122: /* distinct ::= DISTINCT */
117220 {yygotominor.yy381 = SF_Distinct;}
117221 break;
117222 case 123: /* distinct ::= ALL */
117223 case 124: /* distinct ::= */ yytestcase(yyruleno==124);
117224 {yygotominor.yy381 = 0;}
117225 break;
117226 case 125: /* sclp ::= selcollist COMMA */
117227 case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
117228 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
117229 break;
117230 case 126: /* sclp ::= */
117231 case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
117232 case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
117233 case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
117234 case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
117235 {yygotominor.yy14 = 0;}
117236 break;
117237 case 127: /* selcollist ::= sclp expr as */
117239 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
117240 if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
117241 sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
117243 break;
117244 case 128: /* selcollist ::= sclp STAR */
117246 Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
117247 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
117249 break;
117250 case 129: /* selcollist ::= sclp nm DOT STAR */
117252 Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
117253 Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
117254 Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
117255 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
117257 break;
117258 case 132: /* as ::= */
117259 {yygotominor.yy0.n = 0;}
117260 break;
117261 case 133: /* from ::= */
117262 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
117263 break;
117264 case 134: /* from ::= FROM seltablist */
117266 yygotominor.yy65 = yymsp[0].minor.yy65;
117267 sqlite3SrcListShiftJoinType(yygotominor.yy65);
117269 break;
117270 case 135: /* stl_prefix ::= seltablist joinop */
117272 yygotominor.yy65 = yymsp[-1].minor.yy65;
117273 if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
117275 break;
117276 case 136: /* stl_prefix ::= */
117277 {yygotominor.yy65 = 0;}
117278 break;
117279 case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
117281 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);
117282 sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
117284 break;
117285 case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
117287 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);
117289 break;
117290 case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
117292 if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
117293 yygotominor.yy65 = yymsp[-4].minor.yy65;
117294 }else if( yymsp[-4].minor.yy65->nSrc==1 ){
117295 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
117296 if( yygotominor.yy65 ){
117297 struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
117298 struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
117299 pNew->zName = pOld->zName;
117300 pNew->zDatabase = pOld->zDatabase;
117301 pNew->pSelect = pOld->pSelect;
117302 pOld->zName = pOld->zDatabase = 0;
117303 pOld->pSelect = 0;
117305 sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
117306 }else{
117307 Select *pSubquery;
117308 sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
117309 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
117310 yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
117313 break;
117314 case 140: /* dbnm ::= */
117315 case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
117316 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
117317 break;
117318 case 142: /* fullname ::= nm dbnm */
117319 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
117320 break;
117321 case 143: /* joinop ::= COMMA|JOIN */
117322 { yygotominor.yy328 = JT_INNER; }
117323 break;
117324 case 144: /* joinop ::= JOIN_KW JOIN */
117325 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
117326 break;
117327 case 145: /* joinop ::= JOIN_KW nm JOIN */
117328 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
117329 break;
117330 case 146: /* joinop ::= JOIN_KW nm nm JOIN */
117331 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
117332 break;
117333 case 147: /* on_opt ::= ON expr */
117334 case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
117335 case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
117336 case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
117337 case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
117338 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
117339 break;
117340 case 148: /* on_opt ::= */
117341 case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
117342 case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
117343 case 232: /* case_else ::= */ yytestcase(yyruleno==232);
117344 case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
117345 {yygotominor.yy132 = 0;}
117346 break;
117347 case 151: /* indexed_opt ::= NOT INDEXED */
117348 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
117349 break;
117350 case 152: /* using_opt ::= USING LP idlist RP */
117351 case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
117352 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
117353 break;
117354 case 153: /* using_opt ::= */
117355 case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
117356 {yygotominor.yy408 = 0;}
117357 break;
117358 case 155: /* orderby_opt ::= ORDER BY sortlist */
117359 case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
117360 case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
117361 {yygotominor.yy14 = yymsp[0].minor.yy14;}
117362 break;
117363 case 156: /* sortlist ::= sortlist COMMA expr sortorder */
117365 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
117366 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
117368 break;
117369 case 157: /* sortlist ::= expr sortorder */
117371 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
117372 if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
117374 break;
117375 case 158: /* sortorder ::= ASC */
117376 case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
117377 {yygotominor.yy328 = SQLITE_SO_ASC;}
117378 break;
117379 case 159: /* sortorder ::= DESC */
117380 {yygotominor.yy328 = SQLITE_SO_DESC;}
117381 break;
117382 case 165: /* limit_opt ::= */
117383 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
117384 break;
117385 case 166: /* limit_opt ::= LIMIT expr */
117386 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
117387 break;
117388 case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
117389 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
117390 break;
117391 case 168: /* limit_opt ::= LIMIT expr COMMA expr */
117392 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
117393 break;
117394 case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
117396 sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
117397 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
117398 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
117400 break;
117401 case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
117403 sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
117404 sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
117405 sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
117406 sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
117408 break;
117409 case 173: /* setlist ::= setlist COMMA nm EQ expr */
117411 yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
117412 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
117414 break;
117415 case 174: /* setlist ::= nm EQ expr */
117417 yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
117418 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
117420 break;
117421 case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
117423 sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
117424 sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
117426 break;
117427 case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
117429 sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
117430 sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
117432 break;
117433 case 177: /* insert_cmd ::= INSERT orconf */
117434 {yygotominor.yy186 = yymsp[0].minor.yy186;}
117435 break;
117436 case 178: /* insert_cmd ::= REPLACE */
117437 {yygotominor.yy186 = OE_Replace;}
117438 break;
117439 case 181: /* idlist ::= idlist COMMA nm */
117440 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
117441 break;
117442 case 182: /* idlist ::= nm */
117443 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
117444 break;
117445 case 183: /* expr ::= term */
117446 {yygotominor.yy346 = yymsp[0].minor.yy346;}
117447 break;
117448 case 184: /* expr ::= LP expr RP */
117449 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
117450 break;
117451 case 185: /* term ::= NULL */
117452 case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
117453 case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
117454 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
117455 break;
117456 case 186: /* expr ::= ID|INDEXED */
117457 case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
117458 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
117459 break;
117460 case 188: /* expr ::= nm DOT nm */
117462 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
117463 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
117464 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
117465 spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
117467 break;
117468 case 189: /* expr ::= nm DOT nm DOT nm */
117470 Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
117471 Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
117472 Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
117473 Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
117474 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
117475 spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
117477 break;
117478 case 192: /* expr ::= VARIABLE */
117480 if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
117481 /* When doing a nested parse, one can include terms in an expression
117482 ** that look like this: #1 #2 ... These terms refer to registers
117483 ** in the virtual machine. #N is the N-th register. */
117484 if( pParse->nested==0 ){
117485 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
117486 yygotominor.yy346.pExpr = 0;
117487 }else{
117488 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
117489 if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
117491 }else{
117492 spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
117493 sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
117495 spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
117497 break;
117498 case 193: /* expr ::= expr COLLATE ID|STRING */
117500 yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
117501 yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
117502 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117504 break;
117505 case 194: /* expr ::= CAST LP expr AS typetoken RP */
117507 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
117508 spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
117510 break;
117511 case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
117513 if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
117514 sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
117516 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
117517 spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
117518 if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
117519 yygotominor.yy346.pExpr->flags |= EP_Distinct;
117522 break;
117523 case 196: /* expr ::= ID|INDEXED LP STAR RP */
117525 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
117526 spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
117528 break;
117529 case 197: /* term ::= CTIME_KW */
117531 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
117532 spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
117534 break;
117535 case 198: /* expr ::= expr AND expr */
117536 case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
117537 case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
117538 case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
117539 case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
117540 case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
117541 case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
117542 case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
117543 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
117544 break;
117545 case 206: /* likeop ::= LIKE_KW|MATCH */
117546 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
117547 break;
117548 case 207: /* likeop ::= NOT LIKE_KW|MATCH */
117549 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
117550 break;
117551 case 208: /* expr ::= expr likeop expr */
117553 ExprList *pList;
117554 pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
117555 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
117556 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
117557 if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
117558 yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
117559 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
117560 if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
117562 break;
117563 case 209: /* expr ::= expr likeop expr ESCAPE expr */
117565 ExprList *pList;
117566 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
117567 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
117568 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
117569 yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
117570 if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
117571 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
117572 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
117573 if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
117575 break;
117576 case 210: /* expr ::= expr ISNULL|NOTNULL */
117577 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
117578 break;
117579 case 211: /* expr ::= expr NOT NULL */
117580 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
117581 break;
117582 case 212: /* expr ::= expr IS expr */
117584 spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
117585 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
117587 break;
117588 case 213: /* expr ::= expr IS NOT expr */
117590 spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
117591 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
117593 break;
117594 case 214: /* expr ::= NOT expr */
117595 case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
117596 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
117597 break;
117598 case 216: /* expr ::= MINUS expr */
117599 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
117600 break;
117601 case 217: /* expr ::= PLUS expr */
117602 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
117603 break;
117604 case 220: /* expr ::= expr between_op expr AND expr */
117606 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
117607 pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
117608 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
117609 if( yygotominor.yy346.pExpr ){
117610 yygotominor.yy346.pExpr->x.pList = pList;
117611 }else{
117612 sqlite3ExprListDelete(pParse->db, pList);
117614 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
117615 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
117616 yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
117618 break;
117619 case 223: /* expr ::= expr in_op LP exprlist RP */
117621 if( yymsp[-1].minor.yy14==0 ){
117622 /* Expressions of the form
117624 ** expr1 IN ()
117625 ** expr1 NOT IN ()
117627 ** simplify to constants 0 (false) and 1 (true), respectively,
117628 ** regardless of the value of expr1.
117630 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
117631 sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
117632 }else{
117633 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
117634 if( yygotominor.yy346.pExpr ){
117635 yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
117636 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
117637 }else{
117638 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
117640 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
117642 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
117643 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117645 break;
117646 case 224: /* expr ::= LP select RP */
117648 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
117649 if( yygotominor.yy346.pExpr ){
117650 yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
117651 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
117652 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
117653 }else{
117654 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
117656 yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
117657 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117659 break;
117660 case 225: /* expr ::= expr in_op LP select RP */
117662 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
117663 if( yygotominor.yy346.pExpr ){
117664 yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
117665 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
117666 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
117667 }else{
117668 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
117670 if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
117671 yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
117672 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117674 break;
117675 case 226: /* expr ::= expr in_op nm dbnm */
117677 SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
117678 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
117679 if( yygotominor.yy346.pExpr ){
117680 yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
117681 ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
117682 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
117683 }else{
117684 sqlite3SrcListDelete(pParse->db, pSrc);
117686 if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
117687 yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
117688 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];
117690 break;
117691 case 227: /* expr ::= EXISTS LP select RP */
117693 Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
117694 if( p ){
117695 p->x.pSelect = yymsp[-1].minor.yy3;
117696 ExprSetProperty(p, EP_xIsSelect);
117697 sqlite3ExprSetHeight(pParse, p);
117698 }else{
117699 sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
117701 yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
117702 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117704 break;
117705 case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
117707 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
117708 if( yygotominor.yy346.pExpr ){
117709 yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
117710 sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
117711 }else{
117712 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
117713 sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
117715 yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
117716 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117718 break;
117719 case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
117721 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
117722 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
117724 break;
117725 case 230: /* case_exprlist ::= WHEN expr THEN expr */
117727 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
117728 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
117730 break;
117731 case 237: /* nexprlist ::= nexprlist COMMA expr */
117732 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
117733 break;
117734 case 238: /* nexprlist ::= expr */
117735 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
117736 break;
117737 case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
117739 sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
117740 sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
117741 &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
117743 break;
117744 case 240: /* uniqueflag ::= UNIQUE */
117745 case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
117746 {yygotominor.yy328 = OE_Abort;}
117747 break;
117748 case 241: /* uniqueflag ::= */
117749 {yygotominor.yy328 = OE_None;}
117750 break;
117751 case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
117753 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
117754 yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
117755 sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
117756 sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
117757 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
117759 break;
117760 case 245: /* idxlist ::= nm collate sortorder */
117762 Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
117763 yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
117764 sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
117765 sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
117766 if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
117768 break;
117769 case 246: /* collate ::= */
117770 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
117771 break;
117772 case 248: /* cmd ::= DROP INDEX ifexists fullname */
117773 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
117774 break;
117775 case 249: /* cmd ::= VACUUM */
117776 case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
117777 {sqlite3Vacuum(pParse);}
117778 break;
117779 case 251: /* cmd ::= PRAGMA nm dbnm */
117780 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
117781 break;
117782 case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
117783 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
117784 break;
117785 case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
117786 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
117787 break;
117788 case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
117789 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
117790 break;
117791 case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
117792 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
117793 break;
117794 case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
117796 Token all;
117797 all.z = yymsp[-3].minor.yy0.z;
117798 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
117799 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
117801 break;
117802 case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
117804 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);
117805 yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
117807 break;
117808 case 266: /* trigger_time ::= BEFORE */
117809 case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
117810 { yygotominor.yy328 = TK_BEFORE; }
117811 break;
117812 case 267: /* trigger_time ::= AFTER */
117813 { yygotominor.yy328 = TK_AFTER; }
117814 break;
117815 case 268: /* trigger_time ::= INSTEAD OF */
117816 { yygotominor.yy328 = TK_INSTEAD;}
117817 break;
117818 case 270: /* trigger_event ::= DELETE|INSERT */
117819 case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
117820 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
117821 break;
117822 case 272: /* trigger_event ::= UPDATE OF idlist */
117823 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
117824 break;
117825 case 275: /* when_clause ::= */
117826 case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
117827 { yygotominor.yy132 = 0; }
117828 break;
117829 case 276: /* when_clause ::= WHEN expr */
117830 case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
117831 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
117832 break;
117833 case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
117835 assert( yymsp[-2].minor.yy473!=0 );
117836 yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
117837 yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
117838 yygotominor.yy473 = yymsp[-2].minor.yy473;
117840 break;
117841 case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
117843 assert( yymsp[-1].minor.yy473!=0 );
117844 yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
117845 yygotominor.yy473 = yymsp[-1].minor.yy473;
117847 break;
117848 case 280: /* trnm ::= nm DOT nm */
117850 yygotominor.yy0 = yymsp[0].minor.yy0;
117851 sqlite3ErrorMsg(pParse,
117852 "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
117853 "statements within triggers");
117855 break;
117856 case 282: /* tridxby ::= INDEXED BY nm */
117858 sqlite3ErrorMsg(pParse,
117859 "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
117860 "within triggers");
117862 break;
117863 case 283: /* tridxby ::= NOT INDEXED */
117865 sqlite3ErrorMsg(pParse,
117866 "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
117867 "within triggers");
117869 break;
117870 case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
117871 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
117872 break;
117873 case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
117874 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
117875 break;
117876 case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
117877 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
117878 break;
117879 case 287: /* trigger_cmd ::= select */
117880 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
117881 break;
117882 case 288: /* expr ::= RAISE LP IGNORE RP */
117884 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
117885 if( yygotominor.yy346.pExpr ){
117886 yygotominor.yy346.pExpr->affinity = OE_Ignore;
117888 yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
117889 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117891 break;
117892 case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
117894 yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
117895 if( yygotominor.yy346.pExpr ) {
117896 yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
117898 yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
117899 yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
117901 break;
117902 case 290: /* raisetype ::= ROLLBACK */
117903 {yygotominor.yy328 = OE_Rollback;}
117904 break;
117905 case 292: /* raisetype ::= FAIL */
117906 {yygotominor.yy328 = OE_Fail;}
117907 break;
117908 case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
117910 sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
117912 break;
117913 case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
117915 sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
117917 break;
117918 case 295: /* cmd ::= DETACH database_kw_opt expr */
117920 sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
117922 break;
117923 case 300: /* cmd ::= REINDEX */
117924 {sqlite3Reindex(pParse, 0, 0);}
117925 break;
117926 case 301: /* cmd ::= REINDEX nm dbnm */
117927 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
117928 break;
117929 case 302: /* cmd ::= ANALYZE */
117930 {sqlite3Analyze(pParse, 0, 0);}
117931 break;
117932 case 303: /* cmd ::= ANALYZE nm dbnm */
117933 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
117934 break;
117935 case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
117937 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
117939 break;
117940 case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
117942 sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
117944 break;
117945 case 306: /* add_column_fullname ::= fullname */
117947 pParse->db->lookaside.bEnabled = 0;
117948 sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
117950 break;
117951 case 309: /* cmd ::= create_vtab */
117952 {sqlite3VtabFinishParse(pParse,0);}
117953 break;
117954 case 310: /* cmd ::= create_vtab LP vtabarglist RP */
117955 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
117956 break;
117957 case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
117959 sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
117961 break;
117962 case 314: /* vtabarg ::= */
117963 {sqlite3VtabArgInit(pParse);}
117964 break;
117965 case 316: /* vtabargtoken ::= ANY */
117966 case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
117967 case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
117968 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
117969 break;
117970 case 322: /* with ::= */
117971 {yygotominor.yy59 = 0;}
117972 break;
117973 case 323: /* with ::= WITH wqlist */
117974 case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
117975 { yygotominor.yy59 = yymsp[0].minor.yy59; }
117976 break;
117977 case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
117979 yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
117981 break;
117982 case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
117984 yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
117986 break;
117987 default:
117988 /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
117989 /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
117990 /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
117991 /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
117992 /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
117993 /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
117994 /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
117995 /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
117996 /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
117997 /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
117998 /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
117999 /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
118000 /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
118001 /* (43) type ::= */ yytestcase(yyruleno==43);
118002 /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
118003 /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
118004 /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
118005 /* (53) carglist ::= */ yytestcase(yyruleno==53);
118006 /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
118007 /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
118008 /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
118009 /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
118010 /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
118011 /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
118012 /* (281) tridxby ::= */ yytestcase(yyruleno==281);
118013 /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
118014 /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
118015 /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
118016 /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
118017 /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
118018 /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
118019 /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
118020 /* (319) anylist ::= */ yytestcase(yyruleno==319);
118021 /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
118022 /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
118023 break;
118025 assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
118026 yygoto = yyRuleInfo[yyruleno].lhs;
118027 yysize = yyRuleInfo[yyruleno].nrhs;
118028 yypParser->yyidx -= yysize;
118029 yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
118030 if( yyact < YYNSTATE ){
118031 #ifdef NDEBUG
118032 /* If we are not debugging and the reduce action popped at least
118033 ** one element off the stack, then we can push the new element back
118034 ** onto the stack here, and skip the stack overflow test in yy_shift().
118035 ** That gives a significant speed improvement. */
118036 if( yysize ){
118037 yypParser->yyidx++;
118038 yymsp -= yysize-1;
118039 yymsp->stateno = (YYACTIONTYPE)yyact;
118040 yymsp->major = (YYCODETYPE)yygoto;
118041 yymsp->minor = yygotominor;
118042 }else
118043 #endif
118045 yy_shift(yypParser,yyact,yygoto,&yygotominor);
118047 }else{
118048 assert( yyact == YYNSTATE + YYNRULE + 1 );
118049 yy_accept(yypParser);
118054 ** The following code executes when the parse fails
118056 #ifndef YYNOERRORRECOVERY
118057 static void yy_parse_failed(
118058 yyParser *yypParser /* The parser */
118060 sqlite3ParserARG_FETCH;
118061 #ifndef NDEBUG
118062 if( yyTraceFILE ){
118063 fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
118065 #endif
118066 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
118067 /* Here code is inserted which will be executed whenever the
118068 ** parser fails */
118069 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
118071 #endif /* YYNOERRORRECOVERY */
118074 ** The following code executes when a syntax error first occurs.
118076 static void yy_syntax_error(
118077 yyParser *yypParser, /* The parser */
118078 int yymajor, /* The major type of the error token */
118079 YYMINORTYPE yyminor /* The minor type of the error token */
118081 sqlite3ParserARG_FETCH;
118082 #define TOKEN (yyminor.yy0)
118084 UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
118085 assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
118086 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
118087 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
118091 ** The following is executed when the parser accepts
118093 static void yy_accept(
118094 yyParser *yypParser /* The parser */
118096 sqlite3ParserARG_FETCH;
118097 #ifndef NDEBUG
118098 if( yyTraceFILE ){
118099 fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
118101 #endif
118102 while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
118103 /* Here code is inserted which will be executed whenever the
118104 ** parser accepts */
118105 sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
118108 /* The main parser program.
118109 ** The first argument is a pointer to a structure obtained from
118110 ** "sqlite3ParserAlloc" which describes the current state of the parser.
118111 ** The second argument is the major token number. The third is
118112 ** the minor token. The fourth optional argument is whatever the
118113 ** user wants (and specified in the grammar) and is available for
118114 ** use by the action routines.
118116 ** Inputs:
118117 ** <ul>
118118 ** <li> A pointer to the parser (an opaque structure.)
118119 ** <li> The major token number.
118120 ** <li> The minor token number.
118121 ** <li> An option argument of a grammar-specified type.
118122 ** </ul>
118124 ** Outputs:
118125 ** None.
118127 SQLITE_PRIVATE void sqlite3Parser(
118128 void *yyp, /* The parser */
118129 int yymajor, /* The major token code number */
118130 sqlite3ParserTOKENTYPE yyminor /* The value for the token */
118131 sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
118133 YYMINORTYPE yyminorunion;
118134 int yyact; /* The parser action. */
118135 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
118136 int yyendofinput; /* True if we are at the end of input */
118137 #endif
118138 #ifdef YYERRORSYMBOL
118139 int yyerrorhit = 0; /* True if yymajor has invoked an error */
118140 #endif
118141 yyParser *yypParser; /* The parser */
118143 /* (re)initialize the parser, if necessary */
118144 yypParser = (yyParser*)yyp;
118145 if( yypParser->yyidx<0 ){
118146 #if YYSTACKDEPTH<=0
118147 if( yypParser->yystksz <=0 ){
118148 /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
118149 yyminorunion = yyzerominor;
118150 yyStackOverflow(yypParser, &yyminorunion);
118151 return;
118153 #endif
118154 yypParser->yyidx = 0;
118155 yypParser->yyerrcnt = -1;
118156 yypParser->yystack[0].stateno = 0;
118157 yypParser->yystack[0].major = 0;
118159 yyminorunion.yy0 = yyminor;
118160 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
118161 yyendofinput = (yymajor==0);
118162 #endif
118163 sqlite3ParserARG_STORE;
118165 #ifndef NDEBUG
118166 if( yyTraceFILE ){
118167 fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
118169 #endif
118172 yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
118173 if( yyact<YYNSTATE ){
118174 yy_shift(yypParser,yyact,yymajor,&yyminorunion);
118175 yypParser->yyerrcnt--;
118176 yymajor = YYNOCODE;
118177 }else if( yyact < YYNSTATE + YYNRULE ){
118178 yy_reduce(yypParser,yyact-YYNSTATE);
118179 }else{
118180 assert( yyact == YY_ERROR_ACTION );
118181 #ifdef YYERRORSYMBOL
118182 int yymx;
118183 #endif
118184 #ifndef NDEBUG
118185 if( yyTraceFILE ){
118186 fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
118188 #endif
118189 #ifdef YYERRORSYMBOL
118190 /* A syntax error has occurred.
118191 ** The response to an error depends upon whether or not the
118192 ** grammar defines an error token "ERROR".
118194 ** This is what we do if the grammar does define ERROR:
118196 ** * Call the %syntax_error function.
118198 ** * Begin popping the stack until we enter a state where
118199 ** it is legal to shift the error symbol, then shift
118200 ** the error symbol.
118202 ** * Set the error count to three.
118204 ** * Begin accepting and shifting new tokens. No new error
118205 ** processing will occur until three tokens have been
118206 ** shifted successfully.
118209 if( yypParser->yyerrcnt<0 ){
118210 yy_syntax_error(yypParser,yymajor,yyminorunion);
118212 yymx = yypParser->yystack[yypParser->yyidx].major;
118213 if( yymx==YYERRORSYMBOL || yyerrorhit ){
118214 #ifndef NDEBUG
118215 if( yyTraceFILE ){
118216 fprintf(yyTraceFILE,"%sDiscard input token %s\n",
118217 yyTracePrompt,yyTokenName[yymajor]);
118219 #endif
118220 yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
118221 yymajor = YYNOCODE;
118222 }else{
118223 while(
118224 yypParser->yyidx >= 0 &&
118225 yymx != YYERRORSYMBOL &&
118226 (yyact = yy_find_reduce_action(
118227 yypParser->yystack[yypParser->yyidx].stateno,
118228 YYERRORSYMBOL)) >= YYNSTATE
118230 yy_pop_parser_stack(yypParser);
118232 if( yypParser->yyidx < 0 || yymajor==0 ){
118233 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
118234 yy_parse_failed(yypParser);
118235 yymajor = YYNOCODE;
118236 }else if( yymx!=YYERRORSYMBOL ){
118237 YYMINORTYPE u2;
118238 u2.YYERRSYMDT = 0;
118239 yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
118242 yypParser->yyerrcnt = 3;
118243 yyerrorhit = 1;
118244 #elif defined(YYNOERRORRECOVERY)
118245 /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
118246 ** do any kind of error recovery. Instead, simply invoke the syntax
118247 ** error routine and continue going as if nothing had happened.
118249 ** Applications can set this macro (for example inside %include) if
118250 ** they intend to abandon the parse upon the first syntax error seen.
118252 yy_syntax_error(yypParser,yymajor,yyminorunion);
118253 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
118254 yymajor = YYNOCODE;
118256 #else /* YYERRORSYMBOL is not defined */
118257 /* This is what we do if the grammar does not define ERROR:
118259 ** * Report an error message, and throw away the input token.
118261 ** * If the input token is $, then fail the parse.
118263 ** As before, subsequent error messages are suppressed until
118264 ** three input tokens have been successfully shifted.
118266 if( yypParser->yyerrcnt<=0 ){
118267 yy_syntax_error(yypParser,yymajor,yyminorunion);
118269 yypParser->yyerrcnt = 3;
118270 yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
118271 if( yyendofinput ){
118272 yy_parse_failed(yypParser);
118274 yymajor = YYNOCODE;
118275 #endif
118277 }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
118278 return;
118281 /************** End of parse.c ***********************************************/
118282 /************** Begin file tokenize.c ****************************************/
118284 ** 2001 September 15
118286 ** The author disclaims copyright to this source code. In place of
118287 ** a legal notice, here is a blessing:
118289 ** May you do good and not evil.
118290 ** May you find forgiveness for yourself and forgive others.
118291 ** May you share freely, never taking more than you give.
118293 *************************************************************************
118294 ** An tokenizer for SQL
118296 ** This file contains C code that splits an SQL input string up into
118297 ** individual tokens and sends those tokens one-by-one over to the
118298 ** parser for analysis.
118300 /* #include <stdlib.h> */
118303 ** The charMap() macro maps alphabetic characters into their
118304 ** lower-case ASCII equivalent. On ASCII machines, this is just
118305 ** an upper-to-lower case map. On EBCDIC machines we also need
118306 ** to adjust the encoding. Only alphabetic characters and underscores
118307 ** need to be translated.
118309 #ifdef SQLITE_ASCII
118310 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
118311 #endif
118312 #ifdef SQLITE_EBCDIC
118313 # define charMap(X) ebcdicToAscii[(unsigned char)X]
118314 const unsigned char ebcdicToAscii[] = {
118315 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
118316 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
118317 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
118318 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
118319 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
118320 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
118321 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
118322 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
118323 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
118324 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
118325 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
118326 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
118327 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
118328 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
118329 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
118330 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
118331 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
118333 #endif
118336 ** The sqlite3KeywordCode function looks up an identifier to determine if
118337 ** it is a keyword. If it is a keyword, the token code of that keyword is
118338 ** returned. If the input is not a keyword, TK_ID is returned.
118340 ** The implementation of this routine was generated by a program,
118341 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
118342 ** The output of the mkkeywordhash.c program is written into a file
118343 ** named keywordhash.h and then included into this source file by
118344 ** the #include below.
118346 /************** Include keywordhash.h in the middle of tokenize.c ************/
118347 /************** Begin file keywordhash.h *************************************/
118348 /***** This file contains automatically generated code ******
118350 ** The code in this file has been automatically generated by
118352 ** sqlite/tool/mkkeywordhash.c
118354 ** The code in this file implements a function that determines whether
118355 ** or not a given identifier is really an SQL keyword. The same thing
118356 ** might be implemented more directly using a hand-written hash table.
118357 ** But by using this automatically generated code, the size of the code
118358 ** is substantially reduced. This is important for embedded applications
118359 ** on platforms with limited memory.
118361 /* Hash score: 182 */
118362 static int keywordCode(const char *z, int n){
118363 /* zText[] encodes 834 bytes of keywords in 554 bytes */
118364 /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
118365 /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
118366 /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
118367 /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
118368 /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
118369 /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
118370 /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
118371 /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
118372 /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
118373 /* VACUUMVIEWINITIALLY */
118374 static const char zText[553] = {
118375 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
118376 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
118377 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
118378 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
118379 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
118380 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
118381 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
118382 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
118383 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
118384 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
118385 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
118386 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
118387 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
118388 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
118389 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
118390 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
118391 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
118392 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
118393 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
118394 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
118395 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
118396 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
118397 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
118398 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
118399 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
118400 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
118401 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
118402 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
118403 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
118404 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
118405 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
118407 static const unsigned char aHash[127] = {
118408 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
118409 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
118410 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
118411 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
118412 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
118413 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
118414 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
118415 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
118416 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
118417 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
118419 static const unsigned char aNext[124] = {
118420 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
118421 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
118422 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
118423 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
118424 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
118425 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
118426 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
118427 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
118428 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
118429 73, 83, 0, 35, 68, 0, 0,
118431 static const unsigned char aLen[124] = {
118432 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
118433 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
118434 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
118435 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
118436 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
118437 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
118438 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
118439 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
118440 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
118441 3, 5, 5, 6, 4, 9, 3,
118443 static const unsigned short int aOffset[124] = {
118444 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
118445 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
118446 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
118447 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
118448 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
118449 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
118450 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
118451 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
118452 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
118453 521, 524, 529, 534, 540, 544, 549,
118455 static const unsigned char aCode[124] = {
118456 TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
118457 TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
118458 TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
118459 TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
118460 TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
118461 TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
118462 TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
118463 TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
118464 TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
118465 TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
118466 TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
118467 TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
118468 TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
118469 TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
118470 TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
118471 TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
118472 TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
118473 TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
118474 TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
118475 TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
118476 TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
118477 TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
118478 TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
118479 TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
118480 TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
118482 int h, i;
118483 if( n<2 ) return TK_ID;
118484 h = ((charMap(z[0])*4) ^
118485 (charMap(z[n-1])*3) ^
118486 n) % 127;
118487 for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
118488 if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
118489 testcase( i==0 ); /* REINDEX */
118490 testcase( i==1 ); /* INDEXED */
118491 testcase( i==2 ); /* INDEX */
118492 testcase( i==3 ); /* DESC */
118493 testcase( i==4 ); /* ESCAPE */
118494 testcase( i==5 ); /* EACH */
118495 testcase( i==6 ); /* CHECK */
118496 testcase( i==7 ); /* KEY */
118497 testcase( i==8 ); /* BEFORE */
118498 testcase( i==9 ); /* FOREIGN */
118499 testcase( i==10 ); /* FOR */
118500 testcase( i==11 ); /* IGNORE */
118501 testcase( i==12 ); /* REGEXP */
118502 testcase( i==13 ); /* EXPLAIN */
118503 testcase( i==14 ); /* INSTEAD */
118504 testcase( i==15 ); /* ADD */
118505 testcase( i==16 ); /* DATABASE */
118506 testcase( i==17 ); /* AS */
118507 testcase( i==18 ); /* SELECT */
118508 testcase( i==19 ); /* TABLE */
118509 testcase( i==20 ); /* LEFT */
118510 testcase( i==21 ); /* THEN */
118511 testcase( i==22 ); /* END */
118512 testcase( i==23 ); /* DEFERRABLE */
118513 testcase( i==24 ); /* ELSE */
118514 testcase( i==25 ); /* EXCEPT */
118515 testcase( i==26 ); /* TRANSACTION */
118516 testcase( i==27 ); /* ACTION */
118517 testcase( i==28 ); /* ON */
118518 testcase( i==29 ); /* NATURAL */
118519 testcase( i==30 ); /* ALTER */
118520 testcase( i==31 ); /* RAISE */
118521 testcase( i==32 ); /* EXCLUSIVE */
118522 testcase( i==33 ); /* EXISTS */
118523 testcase( i==34 ); /* SAVEPOINT */
118524 testcase( i==35 ); /* INTERSECT */
118525 testcase( i==36 ); /* TRIGGER */
118526 testcase( i==37 ); /* REFERENCES */
118527 testcase( i==38 ); /* CONSTRAINT */
118528 testcase( i==39 ); /* INTO */
118529 testcase( i==40 ); /* OFFSET */
118530 testcase( i==41 ); /* OF */
118531 testcase( i==42 ); /* SET */
118532 testcase( i==43 ); /* TEMPORARY */
118533 testcase( i==44 ); /* TEMP */
118534 testcase( i==45 ); /* OR */
118535 testcase( i==46 ); /* UNIQUE */
118536 testcase( i==47 ); /* QUERY */
118537 testcase( i==48 ); /* WITHOUT */
118538 testcase( i==49 ); /* WITH */
118539 testcase( i==50 ); /* OUTER */
118540 testcase( i==51 ); /* RELEASE */
118541 testcase( i==52 ); /* ATTACH */
118542 testcase( i==53 ); /* HAVING */
118543 testcase( i==54 ); /* GROUP */
118544 testcase( i==55 ); /* UPDATE */
118545 testcase( i==56 ); /* BEGIN */
118546 testcase( i==57 ); /* INNER */
118547 testcase( i==58 ); /* RECURSIVE */
118548 testcase( i==59 ); /* BETWEEN */
118549 testcase( i==60 ); /* NOTNULL */
118550 testcase( i==61 ); /* NOT */
118551 testcase( i==62 ); /* NO */
118552 testcase( i==63 ); /* NULL */
118553 testcase( i==64 ); /* LIKE */
118554 testcase( i==65 ); /* CASCADE */
118555 testcase( i==66 ); /* ASC */
118556 testcase( i==67 ); /* DELETE */
118557 testcase( i==68 ); /* CASE */
118558 testcase( i==69 ); /* COLLATE */
118559 testcase( i==70 ); /* CREATE */
118560 testcase( i==71 ); /* CURRENT_DATE */
118561 testcase( i==72 ); /* DETACH */
118562 testcase( i==73 ); /* IMMEDIATE */
118563 testcase( i==74 ); /* JOIN */
118564 testcase( i==75 ); /* INSERT */
118565 testcase( i==76 ); /* MATCH */
118566 testcase( i==77 ); /* PLAN */
118567 testcase( i==78 ); /* ANALYZE */
118568 testcase( i==79 ); /* PRAGMA */
118569 testcase( i==80 ); /* ABORT */
118570 testcase( i==81 ); /* VALUES */
118571 testcase( i==82 ); /* VIRTUAL */
118572 testcase( i==83 ); /* LIMIT */
118573 testcase( i==84 ); /* WHEN */
118574 testcase( i==85 ); /* WHERE */
118575 testcase( i==86 ); /* RENAME */
118576 testcase( i==87 ); /* AFTER */
118577 testcase( i==88 ); /* REPLACE */
118578 testcase( i==89 ); /* AND */
118579 testcase( i==90 ); /* DEFAULT */
118580 testcase( i==91 ); /* AUTOINCREMENT */
118581 testcase( i==92 ); /* TO */
118582 testcase( i==93 ); /* IN */
118583 testcase( i==94 ); /* CAST */
118584 testcase( i==95 ); /* COLUMN */
118585 testcase( i==96 ); /* COMMIT */
118586 testcase( i==97 ); /* CONFLICT */
118587 testcase( i==98 ); /* CROSS */
118588 testcase( i==99 ); /* CURRENT_TIMESTAMP */
118589 testcase( i==100 ); /* CURRENT_TIME */
118590 testcase( i==101 ); /* PRIMARY */
118591 testcase( i==102 ); /* DEFERRED */
118592 testcase( i==103 ); /* DISTINCT */
118593 testcase( i==104 ); /* IS */
118594 testcase( i==105 ); /* DROP */
118595 testcase( i==106 ); /* FAIL */
118596 testcase( i==107 ); /* FROM */
118597 testcase( i==108 ); /* FULL */
118598 testcase( i==109 ); /* GLOB */
118599 testcase( i==110 ); /* BY */
118600 testcase( i==111 ); /* IF */
118601 testcase( i==112 ); /* ISNULL */
118602 testcase( i==113 ); /* ORDER */
118603 testcase( i==114 ); /* RESTRICT */
118604 testcase( i==115 ); /* RIGHT */
118605 testcase( i==116 ); /* ROLLBACK */
118606 testcase( i==117 ); /* ROW */
118607 testcase( i==118 ); /* UNION */
118608 testcase( i==119 ); /* USING */
118609 testcase( i==120 ); /* VACUUM */
118610 testcase( i==121 ); /* VIEW */
118611 testcase( i==122 ); /* INITIALLY */
118612 testcase( i==123 ); /* ALL */
118613 return aCode[i];
118616 return TK_ID;
118618 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
118619 return keywordCode((char*)z, n);
118621 #define SQLITE_N_KEYWORD 124
118623 /************** End of keywordhash.h *****************************************/
118624 /************** Continuing where we left off in tokenize.c *******************/
118628 ** If X is a character that can be used in an identifier then
118629 ** IdChar(X) will be true. Otherwise it is false.
118631 ** For ASCII, any character with the high-order bit set is
118632 ** allowed in an identifier. For 7-bit characters,
118633 ** sqlite3IsIdChar[X] must be 1.
118635 ** For EBCDIC, the rules are more complex but have the same
118636 ** end result.
118638 ** Ticket #1066. the SQL standard does not allow '$' in the
118639 ** middle of identfiers. But many SQL implementations do.
118640 ** SQLite will allow '$' in identifiers for compatibility.
118641 ** But the feature is undocumented.
118643 #ifdef SQLITE_ASCII
118644 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
118645 #endif
118646 #ifdef SQLITE_EBCDIC
118647 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
118648 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
118649 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
118650 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
118651 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
118652 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
118653 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
118654 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
118655 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
118656 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
118657 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
118658 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
118659 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
118660 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
118662 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
118663 #endif
118667 ** Return the length of the token that begins at z[0].
118668 ** Store the token type in *tokenType before returning.
118670 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
118671 int i, c;
118672 switch( *z ){
118673 case ' ': case '\t': case '\n': case '\f': case '\r': {
118674 testcase( z[0]==' ' );
118675 testcase( z[0]=='\t' );
118676 testcase( z[0]=='\n' );
118677 testcase( z[0]=='\f' );
118678 testcase( z[0]=='\r' );
118679 for(i=1; sqlite3Isspace(z[i]); i++){}
118680 *tokenType = TK_SPACE;
118681 return i;
118683 case '-': {
118684 if( z[1]=='-' ){
118685 for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
118686 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
118687 return i;
118689 *tokenType = TK_MINUS;
118690 return 1;
118692 case '(': {
118693 *tokenType = TK_LP;
118694 return 1;
118696 case ')': {
118697 *tokenType = TK_RP;
118698 return 1;
118700 case ';': {
118701 *tokenType = TK_SEMI;
118702 return 1;
118704 case '+': {
118705 *tokenType = TK_PLUS;
118706 return 1;
118708 case '*': {
118709 *tokenType = TK_STAR;
118710 return 1;
118712 case '/': {
118713 if( z[1]!='*' || z[2]==0 ){
118714 *tokenType = TK_SLASH;
118715 return 1;
118717 for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
118718 if( c ) i++;
118719 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
118720 return i;
118722 case '%': {
118723 *tokenType = TK_REM;
118724 return 1;
118726 case '=': {
118727 *tokenType = TK_EQ;
118728 return 1 + (z[1]=='=');
118730 case '<': {
118731 if( (c=z[1])=='=' ){
118732 *tokenType = TK_LE;
118733 return 2;
118734 }else if( c=='>' ){
118735 *tokenType = TK_NE;
118736 return 2;
118737 }else if( c=='<' ){
118738 *tokenType = TK_LSHIFT;
118739 return 2;
118740 }else{
118741 *tokenType = TK_LT;
118742 return 1;
118745 case '>': {
118746 if( (c=z[1])=='=' ){
118747 *tokenType = TK_GE;
118748 return 2;
118749 }else if( c=='>' ){
118750 *tokenType = TK_RSHIFT;
118751 return 2;
118752 }else{
118753 *tokenType = TK_GT;
118754 return 1;
118757 case '!': {
118758 if( z[1]!='=' ){
118759 *tokenType = TK_ILLEGAL;
118760 return 2;
118761 }else{
118762 *tokenType = TK_NE;
118763 return 2;
118766 case '|': {
118767 if( z[1]!='|' ){
118768 *tokenType = TK_BITOR;
118769 return 1;
118770 }else{
118771 *tokenType = TK_CONCAT;
118772 return 2;
118775 case ',': {
118776 *tokenType = TK_COMMA;
118777 return 1;
118779 case '&': {
118780 *tokenType = TK_BITAND;
118781 return 1;
118783 case '~': {
118784 *tokenType = TK_BITNOT;
118785 return 1;
118787 case '`':
118788 case '\'':
118789 case '"': {
118790 int delim = z[0];
118791 testcase( delim=='`' );
118792 testcase( delim=='\'' );
118793 testcase( delim=='"' );
118794 for(i=1; (c=z[i])!=0; i++){
118795 if( c==delim ){
118796 if( z[i+1]==delim ){
118798 }else{
118799 break;
118803 if( c=='\'' ){
118804 *tokenType = TK_STRING;
118805 return i+1;
118806 }else if( c!=0 ){
118807 *tokenType = TK_ID;
118808 return i+1;
118809 }else{
118810 *tokenType = TK_ILLEGAL;
118811 return i;
118814 case '.': {
118815 #ifndef SQLITE_OMIT_FLOATING_POINT
118816 if( !sqlite3Isdigit(z[1]) )
118817 #endif
118819 *tokenType = TK_DOT;
118820 return 1;
118822 /* If the next character is a digit, this is a floating point
118823 ** number that begins with ".". Fall thru into the next case */
118825 case '0': case '1': case '2': case '3': case '4':
118826 case '5': case '6': case '7': case '8': case '9': {
118827 testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
118828 testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
118829 testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
118830 testcase( z[0]=='9' );
118831 *tokenType = TK_INTEGER;
118832 for(i=0; sqlite3Isdigit(z[i]); i++){}
118833 #ifndef SQLITE_OMIT_FLOATING_POINT
118834 if( z[i]=='.' ){
118836 while( sqlite3Isdigit(z[i]) ){ i++; }
118837 *tokenType = TK_FLOAT;
118839 if( (z[i]=='e' || z[i]=='E') &&
118840 ( sqlite3Isdigit(z[i+1])
118841 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
118844 i += 2;
118845 while( sqlite3Isdigit(z[i]) ){ i++; }
118846 *tokenType = TK_FLOAT;
118848 #endif
118849 while( IdChar(z[i]) ){
118850 *tokenType = TK_ILLEGAL;
118853 return i;
118855 case '[': {
118856 for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
118857 *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
118858 return i;
118860 case '?': {
118861 *tokenType = TK_VARIABLE;
118862 for(i=1; sqlite3Isdigit(z[i]); i++){}
118863 return i;
118865 #ifndef SQLITE_OMIT_TCL_VARIABLE
118866 case '$':
118867 #endif
118868 case '@': /* For compatibility with MS SQL Server */
118869 case '#':
118870 case ':': {
118871 int n = 0;
118872 testcase( z[0]=='$' ); testcase( z[0]=='@' );
118873 testcase( z[0]==':' ); testcase( z[0]=='#' );
118874 *tokenType = TK_VARIABLE;
118875 for(i=1; (c=z[i])!=0; i++){
118876 if( IdChar(c) ){
118878 #ifndef SQLITE_OMIT_TCL_VARIABLE
118879 }else if( c=='(' && n>0 ){
118882 }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
118883 if( c==')' ){
118885 }else{
118886 *tokenType = TK_ILLEGAL;
118888 break;
118889 }else if( c==':' && z[i+1]==':' ){
118891 #endif
118892 }else{
118893 break;
118896 if( n==0 ) *tokenType = TK_ILLEGAL;
118897 return i;
118899 #ifndef SQLITE_OMIT_BLOB_LITERAL
118900 case 'x': case 'X': {
118901 testcase( z[0]=='x' ); testcase( z[0]=='X' );
118902 if( z[1]=='\'' ){
118903 *tokenType = TK_BLOB;
118904 for(i=2; sqlite3Isxdigit(z[i]); i++){}
118905 if( z[i]!='\'' || i%2 ){
118906 *tokenType = TK_ILLEGAL;
118907 while( z[i] && z[i]!='\'' ){ i++; }
118909 if( z[i] ) i++;
118910 return i;
118912 /* Otherwise fall through to the next case */
118914 #endif
118915 default: {
118916 if( !IdChar(*z) ){
118917 break;
118919 for(i=1; IdChar(z[i]); i++){}
118920 *tokenType = keywordCode((char*)z, i);
118921 return i;
118924 *tokenType = TK_ILLEGAL;
118925 return 1;
118929 ** Run the parser on the given SQL string. The parser structure is
118930 ** passed in. An SQLITE_ status code is returned. If an error occurs
118931 ** then an and attempt is made to write an error message into
118932 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
118933 ** error message.
118935 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
118936 int nErr = 0; /* Number of errors encountered */
118937 int i; /* Loop counter */
118938 void *pEngine; /* The LEMON-generated LALR(1) parser */
118939 int tokenType; /* type of the next token */
118940 int lastTokenParsed = -1; /* type of the previous token */
118941 u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
118942 sqlite3 *db = pParse->db; /* The database connection */
118943 int mxSqlLen; /* Max length of an SQL string */
118946 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
118947 if( db->nVdbeActive==0 ){
118948 db->u1.isInterrupted = 0;
118950 pParse->rc = SQLITE_OK;
118951 pParse->zTail = zSql;
118952 i = 0;
118953 assert( pzErrMsg!=0 );
118954 pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
118955 if( pEngine==0 ){
118956 db->mallocFailed = 1;
118957 return SQLITE_NOMEM;
118959 assert( pParse->pNewTable==0 );
118960 assert( pParse->pNewTrigger==0 );
118961 assert( pParse->nVar==0 );
118962 assert( pParse->nzVar==0 );
118963 assert( pParse->azVar==0 );
118964 enableLookaside = db->lookaside.bEnabled;
118965 if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
118966 while( !db->mallocFailed && zSql[i]!=0 ){
118967 assert( i>=0 );
118968 pParse->sLastToken.z = &zSql[i];
118969 pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
118970 i += pParse->sLastToken.n;
118971 if( i>mxSqlLen ){
118972 pParse->rc = SQLITE_TOOBIG;
118973 break;
118975 switch( tokenType ){
118976 case TK_SPACE: {
118977 if( db->u1.isInterrupted ){
118978 sqlite3ErrorMsg(pParse, "interrupt");
118979 pParse->rc = SQLITE_INTERRUPT;
118980 goto abort_parse;
118982 break;
118984 case TK_ILLEGAL: {
118985 sqlite3DbFree(db, *pzErrMsg);
118986 *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
118987 &pParse->sLastToken);
118988 nErr++;
118989 goto abort_parse;
118991 case TK_SEMI: {
118992 pParse->zTail = &zSql[i];
118993 /* Fall thru into the default case */
118995 default: {
118996 sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
118997 lastTokenParsed = tokenType;
118998 if( pParse->rc!=SQLITE_OK ){
118999 goto abort_parse;
119001 break;
119005 abort_parse:
119006 if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
119007 if( lastTokenParsed!=TK_SEMI ){
119008 sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
119009 pParse->zTail = &zSql[i];
119011 sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
119013 #ifdef YYTRACKMAXSTACKDEPTH
119014 sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
119015 sqlite3ParserStackPeak(pEngine)
119017 #endif /* YYDEBUG */
119018 sqlite3ParserFree(pEngine, sqlite3_free);
119019 db->lookaside.bEnabled = enableLookaside;
119020 if( db->mallocFailed ){
119021 pParse->rc = SQLITE_NOMEM;
119023 if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
119024 sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
119026 assert( pzErrMsg!=0 );
119027 if( pParse->zErrMsg ){
119028 *pzErrMsg = pParse->zErrMsg;
119029 sqlite3_log(pParse->rc, "%s", *pzErrMsg);
119030 pParse->zErrMsg = 0;
119031 nErr++;
119033 if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
119034 sqlite3VdbeDelete(pParse->pVdbe);
119035 pParse->pVdbe = 0;
119037 #ifndef SQLITE_OMIT_SHARED_CACHE
119038 if( pParse->nested==0 ){
119039 sqlite3DbFree(db, pParse->aTableLock);
119040 pParse->aTableLock = 0;
119041 pParse->nTableLock = 0;
119043 #endif
119044 #ifndef SQLITE_OMIT_VIRTUALTABLE
119045 sqlite3_free(pParse->apVtabLock);
119046 #endif
119048 if( !IN_DECLARE_VTAB ){
119049 /* If the pParse->declareVtab flag is set, do not delete any table
119050 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
119051 ** will take responsibility for freeing the Table structure.
119053 sqlite3DeleteTable(db, pParse->pNewTable);
119056 if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
119057 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
119058 for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
119059 sqlite3DbFree(db, pParse->azVar);
119060 while( pParse->pAinc ){
119061 AutoincInfo *p = pParse->pAinc;
119062 pParse->pAinc = p->pNext;
119063 sqlite3DbFree(db, p);
119065 while( pParse->pZombieTab ){
119066 Table *p = pParse->pZombieTab;
119067 pParse->pZombieTab = p->pNextZombie;
119068 sqlite3DeleteTable(db, p);
119070 if( nErr>0 && pParse->rc==SQLITE_OK ){
119071 pParse->rc = SQLITE_ERROR;
119073 return nErr;
119076 /************** End of tokenize.c ********************************************/
119077 /************** Begin file complete.c ****************************************/
119079 ** 2001 September 15
119081 ** The author disclaims copyright to this source code. In place of
119082 ** a legal notice, here is a blessing:
119084 ** May you do good and not evil.
119085 ** May you find forgiveness for yourself and forgive others.
119086 ** May you share freely, never taking more than you give.
119088 *************************************************************************
119089 ** An tokenizer for SQL
119091 ** This file contains C code that implements the sqlite3_complete() API.
119092 ** This code used to be part of the tokenizer.c source file. But by
119093 ** separating it out, the code will be automatically omitted from
119094 ** static links that do not use it.
119096 #ifndef SQLITE_OMIT_COMPLETE
119099 ** This is defined in tokenize.c. We just have to import the definition.
119101 #ifndef SQLITE_AMALGAMATION
119102 #ifdef SQLITE_ASCII
119103 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
119104 #endif
119105 #ifdef SQLITE_EBCDIC
119106 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
119107 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
119108 #endif
119109 #endif /* SQLITE_AMALGAMATION */
119113 ** Token types used by the sqlite3_complete() routine. See the header
119114 ** comments on that procedure for additional information.
119116 #define tkSEMI 0
119117 #define tkWS 1
119118 #define tkOTHER 2
119119 #ifndef SQLITE_OMIT_TRIGGER
119120 #define tkEXPLAIN 3
119121 #define tkCREATE 4
119122 #define tkTEMP 5
119123 #define tkTRIGGER 6
119124 #define tkEND 7
119125 #endif
119128 ** Return TRUE if the given SQL string ends in a semicolon.
119130 ** Special handling is require for CREATE TRIGGER statements.
119131 ** Whenever the CREATE TRIGGER keywords are seen, the statement
119132 ** must end with ";END;".
119134 ** This implementation uses a state machine with 8 states:
119136 ** (0) INVALID We have not yet seen a non-whitespace character.
119138 ** (1) START At the beginning or end of an SQL statement. This routine
119139 ** returns 1 if it ends in the START state and 0 if it ends
119140 ** in any other state.
119142 ** (2) NORMAL We are in the middle of statement which ends with a single
119143 ** semicolon.
119145 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
119146 ** a statement.
119148 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
119149 ** statement, possibly preceeded by EXPLAIN and/or followed by
119150 ** TEMP or TEMPORARY
119152 ** (5) TRIGGER We are in the middle of a trigger definition that must be
119153 ** ended by a semicolon, the keyword END, and another semicolon.
119155 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
119156 ** the end of a trigger definition.
119158 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
119159 ** of a trigger difinition.
119161 ** Transitions between states above are determined by tokens extracted
119162 ** from the input. The following tokens are significant:
119164 ** (0) tkSEMI A semicolon.
119165 ** (1) tkWS Whitespace.
119166 ** (2) tkOTHER Any other SQL token.
119167 ** (3) tkEXPLAIN The "explain" keyword.
119168 ** (4) tkCREATE The "create" keyword.
119169 ** (5) tkTEMP The "temp" or "temporary" keyword.
119170 ** (6) tkTRIGGER The "trigger" keyword.
119171 ** (7) tkEND The "end" keyword.
119173 ** Whitespace never causes a state transition and is always ignored.
119174 ** This means that a SQL string of all whitespace is invalid.
119176 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
119177 ** to recognize the end of a trigger can be omitted. All we have to do
119178 ** is look for a semicolon that is not part of an string or comment.
119180 SQLITE_API int sqlite3_complete(const char *zSql){
119181 u8 state = 0; /* Current state, using numbers defined in header comment */
119182 u8 token; /* Value of the next token */
119184 #ifndef SQLITE_OMIT_TRIGGER
119185 /* A complex statement machine used to detect the end of a CREATE TRIGGER
119186 ** statement. This is the normal case.
119188 static const u8 trans[8][8] = {
119189 /* Token: */
119190 /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
119191 /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
119192 /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
119193 /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
119194 /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
119195 /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
119196 /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
119197 /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
119198 /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
119200 #else
119201 /* If triggers are not supported by this compile then the statement machine
119202 ** used to detect the end of a statement is much simplier
119204 static const u8 trans[3][3] = {
119205 /* Token: */
119206 /* State: ** SEMI WS OTHER */
119207 /* 0 INVALID: */ { 1, 0, 2, },
119208 /* 1 START: */ { 1, 1, 2, },
119209 /* 2 NORMAL: */ { 1, 2, 2, },
119211 #endif /* SQLITE_OMIT_TRIGGER */
119213 while( *zSql ){
119214 switch( *zSql ){
119215 case ';': { /* A semicolon */
119216 token = tkSEMI;
119217 break;
119219 case ' ':
119220 case '\r':
119221 case '\t':
119222 case '\n':
119223 case '\f': { /* White space is ignored */
119224 token = tkWS;
119225 break;
119227 case '/': { /* C-style comments */
119228 if( zSql[1]!='*' ){
119229 token = tkOTHER;
119230 break;
119232 zSql += 2;
119233 while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
119234 if( zSql[0]==0 ) return 0;
119235 zSql++;
119236 token = tkWS;
119237 break;
119239 case '-': { /* SQL-style comments from "--" to end of line */
119240 if( zSql[1]!='-' ){
119241 token = tkOTHER;
119242 break;
119244 while( *zSql && *zSql!='\n' ){ zSql++; }
119245 if( *zSql==0 ) return state==1;
119246 token = tkWS;
119247 break;
119249 case '[': { /* Microsoft-style identifiers in [...] */
119250 zSql++;
119251 while( *zSql && *zSql!=']' ){ zSql++; }
119252 if( *zSql==0 ) return 0;
119253 token = tkOTHER;
119254 break;
119256 case '`': /* Grave-accent quoted symbols used by MySQL */
119257 case '"': /* single- and double-quoted strings */
119258 case '\'': {
119259 int c = *zSql;
119260 zSql++;
119261 while( *zSql && *zSql!=c ){ zSql++; }
119262 if( *zSql==0 ) return 0;
119263 token = tkOTHER;
119264 break;
119266 default: {
119267 #ifdef SQLITE_EBCDIC
119268 unsigned char c;
119269 #endif
119270 if( IdChar((u8)*zSql) ){
119271 /* Keywords and unquoted identifiers */
119272 int nId;
119273 for(nId=1; IdChar(zSql[nId]); nId++){}
119274 #ifdef SQLITE_OMIT_TRIGGER
119275 token = tkOTHER;
119276 #else
119277 switch( *zSql ){
119278 case 'c': case 'C': {
119279 if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
119280 token = tkCREATE;
119281 }else{
119282 token = tkOTHER;
119284 break;
119286 case 't': case 'T': {
119287 if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
119288 token = tkTRIGGER;
119289 }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
119290 token = tkTEMP;
119291 }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
119292 token = tkTEMP;
119293 }else{
119294 token = tkOTHER;
119296 break;
119298 case 'e': case 'E': {
119299 if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
119300 token = tkEND;
119301 }else
119302 #ifndef SQLITE_OMIT_EXPLAIN
119303 if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
119304 token = tkEXPLAIN;
119305 }else
119306 #endif
119308 token = tkOTHER;
119310 break;
119312 default: {
119313 token = tkOTHER;
119314 break;
119317 #endif /* SQLITE_OMIT_TRIGGER */
119318 zSql += nId-1;
119319 }else{
119320 /* Operators and special symbols */
119321 token = tkOTHER;
119323 break;
119326 state = trans[state][token];
119327 zSql++;
119329 return state==1;
119332 #ifndef SQLITE_OMIT_UTF16
119334 ** This routine is the same as the sqlite3_complete() routine described
119335 ** above, except that the parameter is required to be UTF-16 encoded, not
119336 ** UTF-8.
119338 SQLITE_API int sqlite3_complete16(const void *zSql){
119339 sqlite3_value *pVal;
119340 char const *zSql8;
119341 int rc = SQLITE_NOMEM;
119343 #ifndef SQLITE_OMIT_AUTOINIT
119344 rc = sqlite3_initialize();
119345 if( rc ) return rc;
119346 #endif
119347 pVal = sqlite3ValueNew(0);
119348 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
119349 zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
119350 if( zSql8 ){
119351 rc = sqlite3_complete(zSql8);
119352 }else{
119353 rc = SQLITE_NOMEM;
119355 sqlite3ValueFree(pVal);
119356 return sqlite3ApiExit(0, rc);
119358 #endif /* SQLITE_OMIT_UTF16 */
119359 #endif /* SQLITE_OMIT_COMPLETE */
119361 /************** End of complete.c ********************************************/
119362 /************** Begin file main.c ********************************************/
119364 ** 2001 September 15
119366 ** The author disclaims copyright to this source code. In place of
119367 ** a legal notice, here is a blessing:
119369 ** May you do good and not evil.
119370 ** May you find forgiveness for yourself and forgive others.
119371 ** May you share freely, never taking more than you give.
119373 *************************************************************************
119374 ** Main file for the SQLite library. The routines in this file
119375 ** implement the programmer interface to the library. Routines in
119376 ** other files are for internal use by SQLite and should not be
119377 ** accessed by users of the library.
119380 #ifdef SQLITE_ENABLE_FTS3
119381 /************** Include fts3.h in the middle of main.c ***********************/
119382 /************** Begin file fts3.h ********************************************/
119384 ** 2006 Oct 10
119386 ** The author disclaims copyright to this source code. In place of
119387 ** a legal notice, here is a blessing:
119389 ** May you do good and not evil.
119390 ** May you find forgiveness for yourself and forgive others.
119391 ** May you share freely, never taking more than you give.
119393 ******************************************************************************
119395 ** This header file is used by programs that want to link against the
119396 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
119399 #if 0
119400 extern "C" {
119401 #endif /* __cplusplus */
119403 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
119405 #if 0
119406 } /* extern "C" */
119407 #endif /* __cplusplus */
119409 /************** End of fts3.h ************************************************/
119410 /************** Continuing where we left off in main.c ***********************/
119411 #endif
119412 #ifdef SQLITE_ENABLE_RTREE
119413 /************** Include rtree.h in the middle of main.c **********************/
119414 /************** Begin file rtree.h *******************************************/
119416 ** 2008 May 26
119418 ** The author disclaims copyright to this source code. In place of
119419 ** a legal notice, here is a blessing:
119421 ** May you do good and not evil.
119422 ** May you find forgiveness for yourself and forgive others.
119423 ** May you share freely, never taking more than you give.
119425 ******************************************************************************
119427 ** This header file is used by programs that want to link against the
119428 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
119431 #if 0
119432 extern "C" {
119433 #endif /* __cplusplus */
119435 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
119437 #if 0
119438 } /* extern "C" */
119439 #endif /* __cplusplus */
119441 /************** End of rtree.h ***********************************************/
119442 /************** Continuing where we left off in main.c ***********************/
119443 #endif
119444 #ifdef SQLITE_ENABLE_ICU
119445 /************** Include sqliteicu.h in the middle of main.c ******************/
119446 /************** Begin file sqliteicu.h ***************************************/
119448 ** 2008 May 26
119450 ** The author disclaims copyright to this source code. In place of
119451 ** a legal notice, here is a blessing:
119453 ** May you do good and not evil.
119454 ** May you find forgiveness for yourself and forgive others.
119455 ** May you share freely, never taking more than you give.
119457 ******************************************************************************
119459 ** This header file is used by programs that want to link against the
119460 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
119463 #if 0
119464 extern "C" {
119465 #endif /* __cplusplus */
119467 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
119469 #if 0
119470 } /* extern "C" */
119471 #endif /* __cplusplus */
119474 /************** End of sqliteicu.h *******************************************/
119475 /************** Continuing where we left off in main.c ***********************/
119476 #endif
119478 #ifndef SQLITE_AMALGAMATION
119479 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
119480 ** contains the text of SQLITE_VERSION macro.
119482 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
119483 #endif
119485 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
119486 ** a pointer to the to the sqlite3_version[] string constant.
119488 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
119490 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
119491 ** pointer to a string constant whose value is the same as the
119492 ** SQLITE_SOURCE_ID C preprocessor macro.
119494 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
119496 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
119497 ** returns an integer equal to SQLITE_VERSION_NUMBER.
119499 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
119501 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
119502 ** zero if and only if SQLite was compiled with mutexing code omitted due to
119503 ** the SQLITE_THREADSAFE compile-time option being set to 0.
119505 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
119507 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
119509 ** If the following function pointer is not NULL and if
119510 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
119511 ** I/O active are written using this function. These messages
119512 ** are intended for debugging activity only.
119514 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
119515 #endif
119518 ** If the following global variable points to a string which is the
119519 ** name of a directory, then that directory will be used to store
119520 ** temporary files.
119522 ** See also the "PRAGMA temp_store_directory" SQL command.
119524 SQLITE_API char *sqlite3_temp_directory = 0;
119527 ** If the following global variable points to a string which is the
119528 ** name of a directory, then that directory will be used to store
119529 ** all database files specified with a relative pathname.
119531 ** See also the "PRAGMA data_store_directory" SQL command.
119533 SQLITE_API char *sqlite3_data_directory = 0;
119536 ** Initialize SQLite.
119538 ** This routine must be called to initialize the memory allocation,
119539 ** VFS, and mutex subsystems prior to doing any serious work with
119540 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
119541 ** this routine will be called automatically by key routines such as
119542 ** sqlite3_open().
119544 ** This routine is a no-op except on its very first call for the process,
119545 ** or for the first call after a call to sqlite3_shutdown.
119547 ** The first thread to call this routine runs the initialization to
119548 ** completion. If subsequent threads call this routine before the first
119549 ** thread has finished the initialization process, then the subsequent
119550 ** threads must block until the first thread finishes with the initialization.
119552 ** The first thread might call this routine recursively. Recursive
119553 ** calls to this routine should not block, of course. Otherwise the
119554 ** initialization process would never complete.
119556 ** Let X be the first thread to enter this routine. Let Y be some other
119557 ** thread. Then while the initial invocation of this routine by X is
119558 ** incomplete, it is required that:
119560 ** * Calls to this routine from Y must block until the outer-most
119561 ** call by X completes.
119563 ** * Recursive calls to this routine from thread X return immediately
119564 ** without blocking.
119566 SQLITE_API int sqlite3_initialize(void){
119567 MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
119568 int rc; /* Result code */
119569 #ifdef SQLITE_EXTRA_INIT
119570 int bRunExtraInit = 0; /* Extra initialization needed */
119571 #endif
119573 #ifdef SQLITE_OMIT_WSD
119574 rc = sqlite3_wsd_init(4096, 24);
119575 if( rc!=SQLITE_OK ){
119576 return rc;
119578 #endif
119580 /* If SQLite is already completely initialized, then this call
119581 ** to sqlite3_initialize() should be a no-op. But the initialization
119582 ** must be complete. So isInit must not be set until the very end
119583 ** of this routine.
119585 if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
119587 /* Make sure the mutex subsystem is initialized. If unable to
119588 ** initialize the mutex subsystem, return early with the error.
119589 ** If the system is so sick that we are unable to allocate a mutex,
119590 ** there is not much SQLite is going to be able to do.
119592 ** The mutex subsystem must take care of serializing its own
119593 ** initialization.
119595 rc = sqlite3MutexInit();
119596 if( rc ) return rc;
119598 /* Initialize the malloc() system and the recursive pInitMutex mutex.
119599 ** This operation is protected by the STATIC_MASTER mutex. Note that
119600 ** MutexAlloc() is called for a static mutex prior to initializing the
119601 ** malloc subsystem - this implies that the allocation of a static
119602 ** mutex must not require support from the malloc subsystem.
119604 MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
119605 sqlite3_mutex_enter(pMaster);
119606 sqlite3GlobalConfig.isMutexInit = 1;
119607 if( !sqlite3GlobalConfig.isMallocInit ){
119608 rc = sqlite3MallocInit();
119610 if( rc==SQLITE_OK ){
119611 sqlite3GlobalConfig.isMallocInit = 1;
119612 if( !sqlite3GlobalConfig.pInitMutex ){
119613 sqlite3GlobalConfig.pInitMutex =
119614 sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
119615 if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
119616 rc = SQLITE_NOMEM;
119620 if( rc==SQLITE_OK ){
119621 sqlite3GlobalConfig.nRefInitMutex++;
119623 sqlite3_mutex_leave(pMaster);
119625 /* If rc is not SQLITE_OK at this point, then either the malloc
119626 ** subsystem could not be initialized or the system failed to allocate
119627 ** the pInitMutex mutex. Return an error in either case. */
119628 if( rc!=SQLITE_OK ){
119629 return rc;
119632 /* Do the rest of the initialization under the recursive mutex so
119633 ** that we will be able to handle recursive calls into
119634 ** sqlite3_initialize(). The recursive calls normally come through
119635 ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
119636 ** recursive calls might also be possible.
119638 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
119639 ** to the xInit method, so the xInit method need not be threadsafe.
119641 ** The following mutex is what serializes access to the appdef pcache xInit
119642 ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
119643 ** call to sqlite3PcacheInitialize().
119645 sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
119646 if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
119647 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
119648 sqlite3GlobalConfig.inProgress = 1;
119649 memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
119650 sqlite3RegisterGlobalFunctions();
119651 if( sqlite3GlobalConfig.isPCacheInit==0 ){
119652 rc = sqlite3PcacheInitialize();
119654 if( rc==SQLITE_OK ){
119655 sqlite3GlobalConfig.isPCacheInit = 1;
119656 rc = sqlite3OsInit();
119658 if( rc==SQLITE_OK ){
119659 sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
119660 sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
119661 sqlite3GlobalConfig.isInit = 1;
119662 #ifdef SQLITE_EXTRA_INIT
119663 bRunExtraInit = 1;
119664 #endif
119666 sqlite3GlobalConfig.inProgress = 0;
119668 sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
119670 /* Go back under the static mutex and clean up the recursive
119671 ** mutex to prevent a resource leak.
119673 sqlite3_mutex_enter(pMaster);
119674 sqlite3GlobalConfig.nRefInitMutex--;
119675 if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
119676 assert( sqlite3GlobalConfig.nRefInitMutex==0 );
119677 sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
119678 sqlite3GlobalConfig.pInitMutex = 0;
119680 sqlite3_mutex_leave(pMaster);
119682 /* The following is just a sanity check to make sure SQLite has
119683 ** been compiled correctly. It is important to run this code, but
119684 ** we don't want to run it too often and soak up CPU cycles for no
119685 ** reason. So we run it once during initialization.
119687 #ifndef NDEBUG
119688 #ifndef SQLITE_OMIT_FLOATING_POINT
119689 /* This section of code's only "output" is via assert() statements. */
119690 if ( rc==SQLITE_OK ){
119691 u64 x = (((u64)1)<<63)-1;
119692 double y;
119693 assert(sizeof(x)==8);
119694 assert(sizeof(x)==sizeof(y));
119695 memcpy(&y, &x, 8);
119696 assert( sqlite3IsNaN(y) );
119698 #endif
119699 #endif
119701 /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
119702 ** compile-time option.
119704 #ifdef SQLITE_EXTRA_INIT
119705 if( bRunExtraInit ){
119706 int SQLITE_EXTRA_INIT(const char*);
119707 rc = SQLITE_EXTRA_INIT(0);
119709 #endif
119711 return rc;
119715 ** Undo the effects of sqlite3_initialize(). Must not be called while
119716 ** there are outstanding database connections or memory allocations or
119717 ** while any part of SQLite is otherwise in use in any thread. This
119718 ** routine is not threadsafe. But it is safe to invoke this routine
119719 ** on when SQLite is already shut down. If SQLite is already shut down
119720 ** when this routine is invoked, then this routine is a harmless no-op.
119722 SQLITE_API int sqlite3_shutdown(void){
119723 if( sqlite3GlobalConfig.isInit ){
119724 #ifdef SQLITE_EXTRA_SHUTDOWN
119725 void SQLITE_EXTRA_SHUTDOWN(void);
119726 SQLITE_EXTRA_SHUTDOWN();
119727 #endif
119728 sqlite3_os_end();
119729 sqlite3_reset_auto_extension();
119730 sqlite3GlobalConfig.isInit = 0;
119732 if( sqlite3GlobalConfig.isPCacheInit ){
119733 sqlite3PcacheShutdown();
119734 sqlite3GlobalConfig.isPCacheInit = 0;
119736 if( sqlite3GlobalConfig.isMallocInit ){
119737 sqlite3MallocEnd();
119738 sqlite3GlobalConfig.isMallocInit = 0;
119740 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
119741 /* The heap subsystem has now been shutdown and these values are supposed
119742 ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
119743 ** which would rely on that heap subsystem; therefore, make sure these
119744 ** values cannot refer to heap memory that was just invalidated when the
119745 ** heap subsystem was shutdown. This is only done if the current call to
119746 ** this function resulted in the heap subsystem actually being shutdown.
119748 sqlite3_data_directory = 0;
119749 sqlite3_temp_directory = 0;
119750 #endif
119752 if( sqlite3GlobalConfig.isMutexInit ){
119753 sqlite3MutexEnd();
119754 sqlite3GlobalConfig.isMutexInit = 0;
119757 return SQLITE_OK;
119761 ** This API allows applications to modify the global configuration of
119762 ** the SQLite library at run-time.
119764 ** This routine should only be called when there are no outstanding
119765 ** database connections or memory allocations. This routine is not
119766 ** threadsafe. Failure to heed these warnings can lead to unpredictable
119767 ** behavior.
119769 SQLITE_API int sqlite3_config(int op, ...){
119770 va_list ap;
119771 int rc = SQLITE_OK;
119773 /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
119774 ** the SQLite library is in use. */
119775 if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
119777 va_start(ap, op);
119778 switch( op ){
119780 /* Mutex configuration options are only available in a threadsafe
119781 ** compile.
119783 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
119784 case SQLITE_CONFIG_SINGLETHREAD: {
119785 /* Disable all mutexing */
119786 sqlite3GlobalConfig.bCoreMutex = 0;
119787 sqlite3GlobalConfig.bFullMutex = 0;
119788 break;
119790 case SQLITE_CONFIG_MULTITHREAD: {
119791 /* Disable mutexing of database connections */
119792 /* Enable mutexing of core data structures */
119793 sqlite3GlobalConfig.bCoreMutex = 1;
119794 sqlite3GlobalConfig.bFullMutex = 0;
119795 break;
119797 case SQLITE_CONFIG_SERIALIZED: {
119798 /* Enable all mutexing */
119799 sqlite3GlobalConfig.bCoreMutex = 1;
119800 sqlite3GlobalConfig.bFullMutex = 1;
119801 break;
119803 case SQLITE_CONFIG_MUTEX: {
119804 /* Specify an alternative mutex implementation */
119805 sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
119806 break;
119808 case SQLITE_CONFIG_GETMUTEX: {
119809 /* Retrieve the current mutex implementation */
119810 *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
119811 break;
119813 #endif
119816 case SQLITE_CONFIG_MALLOC: {
119817 /* Specify an alternative malloc implementation */
119818 sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
119819 break;
119821 case SQLITE_CONFIG_GETMALLOC: {
119822 /* Retrieve the current malloc() implementation */
119823 if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
119824 *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
119825 break;
119827 case SQLITE_CONFIG_MEMSTATUS: {
119828 /* Enable or disable the malloc status collection */
119829 sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
119830 break;
119832 case SQLITE_CONFIG_SCRATCH: {
119833 /* Designate a buffer for scratch memory space */
119834 sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
119835 sqlite3GlobalConfig.szScratch = va_arg(ap, int);
119836 sqlite3GlobalConfig.nScratch = va_arg(ap, int);
119837 break;
119839 case SQLITE_CONFIG_PAGECACHE: {
119840 /* Designate a buffer for page cache memory space */
119841 sqlite3GlobalConfig.pPage = va_arg(ap, void*);
119842 sqlite3GlobalConfig.szPage = va_arg(ap, int);
119843 sqlite3GlobalConfig.nPage = va_arg(ap, int);
119844 break;
119847 case SQLITE_CONFIG_PCACHE: {
119848 /* no-op */
119849 break;
119851 case SQLITE_CONFIG_GETPCACHE: {
119852 /* now an error */
119853 rc = SQLITE_ERROR;
119854 break;
119857 case SQLITE_CONFIG_PCACHE2: {
119858 /* Specify an alternative page cache implementation */
119859 sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
119860 break;
119862 case SQLITE_CONFIG_GETPCACHE2: {
119863 if( sqlite3GlobalConfig.pcache2.xInit==0 ){
119864 sqlite3PCacheSetDefault();
119866 *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
119867 break;
119870 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
119871 case SQLITE_CONFIG_HEAP: {
119872 /* Designate a buffer for heap memory space */
119873 sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
119874 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
119875 sqlite3GlobalConfig.mnReq = va_arg(ap, int);
119877 if( sqlite3GlobalConfig.mnReq<1 ){
119878 sqlite3GlobalConfig.mnReq = 1;
119879 }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
119880 /* cap min request size at 2^12 */
119881 sqlite3GlobalConfig.mnReq = (1<<12);
119884 if( sqlite3GlobalConfig.pHeap==0 ){
119885 /* If the heap pointer is NULL, then restore the malloc implementation
119886 ** back to NULL pointers too. This will cause the malloc to go
119887 ** back to its default implementation when sqlite3_initialize() is
119888 ** run.
119890 memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
119891 }else{
119892 /* The heap pointer is not NULL, then install one of the
119893 ** mem5.c/mem3.c methods. The enclosing #if guarantees at
119894 ** least one of these methods is currently enabled.
119896 #ifdef SQLITE_ENABLE_MEMSYS3
119897 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
119898 #endif
119899 #ifdef SQLITE_ENABLE_MEMSYS5
119900 sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
119901 #endif
119903 break;
119905 #endif
119907 case SQLITE_CONFIG_LOOKASIDE: {
119908 sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
119909 sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
119910 break;
119913 /* Record a pointer to the logger function and its first argument.
119914 ** The default is NULL. Logging is disabled if the function pointer is
119915 ** NULL.
119917 case SQLITE_CONFIG_LOG: {
119918 /* MSVC is picky about pulling func ptrs from va lists.
119919 ** http://support.microsoft.com/kb/47961
119920 ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
119922 typedef void(*LOGFUNC_t)(void*,int,const char*);
119923 sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
119924 sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
119925 break;
119928 case SQLITE_CONFIG_URI: {
119929 sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
119930 break;
119933 case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
119934 sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
119935 break;
119938 #ifdef SQLITE_ENABLE_SQLLOG
119939 case SQLITE_CONFIG_SQLLOG: {
119940 typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
119941 sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
119942 sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
119943 break;
119945 #endif
119947 case SQLITE_CONFIG_MMAP_SIZE: {
119948 sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
119949 sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
119950 if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
119951 mxMmap = SQLITE_MAX_MMAP_SIZE;
119953 sqlite3GlobalConfig.mxMmap = mxMmap;
119954 if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
119955 if( szMmap>mxMmap) szMmap = mxMmap;
119956 sqlite3GlobalConfig.szMmap = szMmap;
119957 break;
119960 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
119961 case SQLITE_CONFIG_WIN32_HEAPSIZE: {
119962 sqlite3GlobalConfig.nHeap = va_arg(ap, int);
119963 break;
119965 #endif
119967 default: {
119968 rc = SQLITE_ERROR;
119969 break;
119972 va_end(ap);
119973 return rc;
119977 ** Set up the lookaside buffers for a database connection.
119978 ** Return SQLITE_OK on success.
119979 ** If lookaside is already active, return SQLITE_BUSY.
119981 ** The sz parameter is the number of bytes in each lookaside slot.
119982 ** The cnt parameter is the number of slots. If pStart is NULL the
119983 ** space for the lookaside memory is obtained from sqlite3_malloc().
119984 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
119985 ** the lookaside memory.
119987 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
119988 void *pStart;
119989 if( db->lookaside.nOut ){
119990 return SQLITE_BUSY;
119992 /* Free any existing lookaside buffer for this handle before
119993 ** allocating a new one so we don't have to have space for
119994 ** both at the same time.
119996 if( db->lookaside.bMalloced ){
119997 sqlite3_free(db->lookaside.pStart);
119999 /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
120000 ** than a pointer to be useful.
120002 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
120003 if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
120004 if( cnt<0 ) cnt = 0;
120005 if( sz==0 || cnt==0 ){
120006 sz = 0;
120007 pStart = 0;
120008 }else if( pBuf==0 ){
120009 sqlite3BeginBenignMalloc();
120010 pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
120011 sqlite3EndBenignMalloc();
120012 if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
120013 }else{
120014 pStart = pBuf;
120016 db->lookaside.pStart = pStart;
120017 db->lookaside.pFree = 0;
120018 db->lookaside.sz = (u16)sz;
120019 if( pStart ){
120020 int i;
120021 LookasideSlot *p;
120022 assert( sz > (int)sizeof(LookasideSlot*) );
120023 p = (LookasideSlot*)pStart;
120024 for(i=cnt-1; i>=0; i--){
120025 p->pNext = db->lookaside.pFree;
120026 db->lookaside.pFree = p;
120027 p = (LookasideSlot*)&((u8*)p)[sz];
120029 db->lookaside.pEnd = p;
120030 db->lookaside.bEnabled = 1;
120031 db->lookaside.bMalloced = pBuf==0 ?1:0;
120032 }else{
120033 db->lookaside.pStart = db;
120034 db->lookaside.pEnd = db;
120035 db->lookaside.bEnabled = 0;
120036 db->lookaside.bMalloced = 0;
120038 return SQLITE_OK;
120042 ** Return the mutex associated with a database connection.
120044 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
120045 return db->mutex;
120049 ** Free up as much memory as we can from the given database
120050 ** connection.
120052 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
120053 int i;
120054 sqlite3_mutex_enter(db->mutex);
120055 sqlite3BtreeEnterAll(db);
120056 for(i=0; i<db->nDb; i++){
120057 Btree *pBt = db->aDb[i].pBt;
120058 if( pBt ){
120059 Pager *pPager = sqlite3BtreePager(pBt);
120060 sqlite3PagerShrink(pPager);
120063 sqlite3BtreeLeaveAll(db);
120064 sqlite3_mutex_leave(db->mutex);
120065 return SQLITE_OK;
120069 ** Configuration settings for an individual database connection
120071 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
120072 va_list ap;
120073 int rc;
120074 va_start(ap, op);
120075 switch( op ){
120076 case SQLITE_DBCONFIG_LOOKASIDE: {
120077 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
120078 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
120079 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
120080 rc = setupLookaside(db, pBuf, sz, cnt);
120081 break;
120083 default: {
120084 static const struct {
120085 int op; /* The opcode */
120086 u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
120087 } aFlagOp[] = {
120088 { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
120089 { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
120091 unsigned int i;
120092 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
120093 for(i=0; i<ArraySize(aFlagOp); i++){
120094 if( aFlagOp[i].op==op ){
120095 int onoff = va_arg(ap, int);
120096 int *pRes = va_arg(ap, int*);
120097 int oldFlags = db->flags;
120098 if( onoff>0 ){
120099 db->flags |= aFlagOp[i].mask;
120100 }else if( onoff==0 ){
120101 db->flags &= ~aFlagOp[i].mask;
120103 if( oldFlags!=db->flags ){
120104 sqlite3ExpirePreparedStatements(db);
120106 if( pRes ){
120107 *pRes = (db->flags & aFlagOp[i].mask)!=0;
120109 rc = SQLITE_OK;
120110 break;
120113 break;
120116 va_end(ap);
120117 return rc;
120122 ** Return true if the buffer z[0..n-1] contains all spaces.
120124 static int allSpaces(const char *z, int n){
120125 while( n>0 && z[n-1]==' ' ){ n--; }
120126 return n==0;
120130 ** This is the default collating function named "BINARY" which is always
120131 ** available.
120133 ** If the padFlag argument is not NULL then space padding at the end
120134 ** of strings is ignored. This implements the RTRIM collation.
120136 static int binCollFunc(
120137 void *padFlag,
120138 int nKey1, const void *pKey1,
120139 int nKey2, const void *pKey2
120141 int rc, n;
120142 n = nKey1<nKey2 ? nKey1 : nKey2;
120143 rc = memcmp(pKey1, pKey2, n);
120144 if( rc==0 ){
120145 if( padFlag
120146 && allSpaces(((char*)pKey1)+n, nKey1-n)
120147 && allSpaces(((char*)pKey2)+n, nKey2-n)
120149 /* Leave rc unchanged at 0 */
120150 }else{
120151 rc = nKey1 - nKey2;
120154 return rc;
120158 ** Another built-in collating sequence: NOCASE.
120160 ** This collating sequence is intended to be used for "case independent
120161 ** comparison". SQLite's knowledge of upper and lower case equivalents
120162 ** extends only to the 26 characters used in the English language.
120164 ** At the moment there is only a UTF-8 implementation.
120166 static int nocaseCollatingFunc(
120167 void *NotUsed,
120168 int nKey1, const void *pKey1,
120169 int nKey2, const void *pKey2
120171 int r = sqlite3StrNICmp(
120172 (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
120173 UNUSED_PARAMETER(NotUsed);
120174 if( 0==r ){
120175 r = nKey1-nKey2;
120177 return r;
120181 ** Return the ROWID of the most recent insert
120183 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
120184 return db->lastRowid;
120188 ** Return the number of changes in the most recent call to sqlite3_exec().
120190 SQLITE_API int sqlite3_changes(sqlite3 *db){
120191 return db->nChange;
120195 ** Return the number of changes since the database handle was opened.
120197 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
120198 return db->nTotalChange;
120202 ** Close all open savepoints. This function only manipulates fields of the
120203 ** database handle object, it does not close any savepoints that may be open
120204 ** at the b-tree/pager level.
120206 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
120207 while( db->pSavepoint ){
120208 Savepoint *pTmp = db->pSavepoint;
120209 db->pSavepoint = pTmp->pNext;
120210 sqlite3DbFree(db, pTmp);
120212 db->nSavepoint = 0;
120213 db->nStatement = 0;
120214 db->isTransactionSavepoint = 0;
120218 ** Invoke the destructor function associated with FuncDef p, if any. Except,
120219 ** if this is not the last copy of the function, do not invoke it. Multiple
120220 ** copies of a single function are created when create_function() is called
120221 ** with SQLITE_ANY as the encoding.
120223 static void functionDestroy(sqlite3 *db, FuncDef *p){
120224 FuncDestructor *pDestructor = p->pDestructor;
120225 if( pDestructor ){
120226 pDestructor->nRef--;
120227 if( pDestructor->nRef==0 ){
120228 pDestructor->xDestroy(pDestructor->pUserData);
120229 sqlite3DbFree(db, pDestructor);
120235 ** Disconnect all sqlite3_vtab objects that belong to database connection
120236 ** db. This is called when db is being closed.
120238 static void disconnectAllVtab(sqlite3 *db){
120239 #ifndef SQLITE_OMIT_VIRTUALTABLE
120240 int i;
120241 sqlite3BtreeEnterAll(db);
120242 for(i=0; i<db->nDb; i++){
120243 Schema *pSchema = db->aDb[i].pSchema;
120244 if( db->aDb[i].pSchema ){
120245 HashElem *p;
120246 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
120247 Table *pTab = (Table *)sqliteHashData(p);
120248 if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
120252 sqlite3BtreeLeaveAll(db);
120253 #else
120254 UNUSED_PARAMETER(db);
120255 #endif
120259 ** Return TRUE if database connection db has unfinalized prepared
120260 ** statements or unfinished sqlite3_backup objects.
120262 static int connectionIsBusy(sqlite3 *db){
120263 int j;
120264 assert( sqlite3_mutex_held(db->mutex) );
120265 if( db->pVdbe ) return 1;
120266 for(j=0; j<db->nDb; j++){
120267 Btree *pBt = db->aDb[j].pBt;
120268 if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
120270 return 0;
120274 ** Close an existing SQLite database
120276 static int sqlite3Close(sqlite3 *db, int forceZombie){
120277 if( !db ){
120278 return SQLITE_OK;
120280 if( !sqlite3SafetyCheckSickOrOk(db) ){
120281 return SQLITE_MISUSE_BKPT;
120283 sqlite3_mutex_enter(db->mutex);
120285 /* Force xDisconnect calls on all virtual tables */
120286 disconnectAllVtab(db);
120288 /* If a transaction is open, the disconnectAllVtab() call above
120289 ** will not have called the xDisconnect() method on any virtual
120290 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
120291 ** call will do so. We need to do this before the check for active
120292 ** SQL statements below, as the v-table implementation may be storing
120293 ** some prepared statements internally.
120295 sqlite3VtabRollback(db);
120297 /* Legacy behavior (sqlite3_close() behavior) is to return
120298 ** SQLITE_BUSY if the connection can not be closed immediately.
120300 if( !forceZombie && connectionIsBusy(db) ){
120301 sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
120302 "statements or unfinished backups");
120303 sqlite3_mutex_leave(db->mutex);
120304 return SQLITE_BUSY;
120307 #ifdef SQLITE_ENABLE_SQLLOG
120308 if( sqlite3GlobalConfig.xSqllog ){
120309 /* Closing the handle. Fourth parameter is passed the value 2. */
120310 sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
120312 #endif
120314 /* Convert the connection into a zombie and then close it.
120316 db->magic = SQLITE_MAGIC_ZOMBIE;
120317 sqlite3LeaveMutexAndCloseZombie(db);
120318 return SQLITE_OK;
120322 ** Two variations on the public interface for closing a database
120323 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
120324 ** leaves the connection option if there are unfinalized prepared
120325 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
120326 ** version forces the connection to become a zombie if there are
120327 ** unclosed resources, and arranges for deallocation when the last
120328 ** prepare statement or sqlite3_backup closes.
120330 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
120331 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
120335 ** Close the mutex on database connection db.
120337 ** Furthermore, if database connection db is a zombie (meaning that there
120338 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
120339 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
120340 ** finished, then free all resources.
120342 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
120343 HashElem *i; /* Hash table iterator */
120344 int j;
120346 /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
120347 ** or if the connection has not yet been closed by sqlite3_close_v2(),
120348 ** then just leave the mutex and return.
120350 if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
120351 sqlite3_mutex_leave(db->mutex);
120352 return;
120355 /* If we reach this point, it means that the database connection has
120356 ** closed all sqlite3_stmt and sqlite3_backup objects and has been
120357 ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
120358 ** go ahead and free all resources.
120361 /* If a transaction is open, roll it back. This also ensures that if
120362 ** any database schemas have been modified by an uncommitted transaction
120363 ** they are reset. And that the required b-tree mutex is held to make
120364 ** the pager rollback and schema reset an atomic operation. */
120365 sqlite3RollbackAll(db, SQLITE_OK);
120367 /* Free any outstanding Savepoint structures. */
120368 sqlite3CloseSavepoints(db);
120370 /* Close all database connections */
120371 for(j=0; j<db->nDb; j++){
120372 struct Db *pDb = &db->aDb[j];
120373 if( pDb->pBt ){
120374 sqlite3BtreeClose(pDb->pBt);
120375 pDb->pBt = 0;
120376 if( j!=1 ){
120377 pDb->pSchema = 0;
120381 /* Clear the TEMP schema separately and last */
120382 if( db->aDb[1].pSchema ){
120383 sqlite3SchemaClear(db->aDb[1].pSchema);
120385 sqlite3VtabUnlockList(db);
120387 /* Free up the array of auxiliary databases */
120388 sqlite3CollapseDatabaseArray(db);
120389 assert( db->nDb<=2 );
120390 assert( db->aDb==db->aDbStatic );
120392 /* Tell the code in notify.c that the connection no longer holds any
120393 ** locks and does not require any further unlock-notify callbacks.
120395 sqlite3ConnectionClosed(db);
120397 for(j=0; j<ArraySize(db->aFunc.a); j++){
120398 FuncDef *pNext, *pHash, *p;
120399 for(p=db->aFunc.a[j]; p; p=pHash){
120400 pHash = p->pHash;
120401 while( p ){
120402 functionDestroy(db, p);
120403 pNext = p->pNext;
120404 sqlite3DbFree(db, p);
120405 p = pNext;
120409 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
120410 CollSeq *pColl = (CollSeq *)sqliteHashData(i);
120411 /* Invoke any destructors registered for collation sequence user data. */
120412 for(j=0; j<3; j++){
120413 if( pColl[j].xDel ){
120414 pColl[j].xDel(pColl[j].pUser);
120417 sqlite3DbFree(db, pColl);
120419 sqlite3HashClear(&db->aCollSeq);
120420 #ifndef SQLITE_OMIT_VIRTUALTABLE
120421 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
120422 Module *pMod = (Module *)sqliteHashData(i);
120423 if( pMod->xDestroy ){
120424 pMod->xDestroy(pMod->pAux);
120426 sqlite3DbFree(db, pMod);
120428 sqlite3HashClear(&db->aModule);
120429 #endif
120431 sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
120432 sqlite3ValueFree(db->pErr);
120433 sqlite3CloseExtensions(db);
120435 db->magic = SQLITE_MAGIC_ERROR;
120437 /* The temp-database schema is allocated differently from the other schema
120438 ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
120439 ** So it needs to be freed here. Todo: Why not roll the temp schema into
120440 ** the same sqliteMalloc() as the one that allocates the database
120441 ** structure?
120443 sqlite3DbFree(db, db->aDb[1].pSchema);
120444 sqlite3_mutex_leave(db->mutex);
120445 db->magic = SQLITE_MAGIC_CLOSED;
120446 sqlite3_mutex_free(db->mutex);
120447 assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
120448 if( db->lookaside.bMalloced ){
120449 sqlite3_free(db->lookaside.pStart);
120451 sqlite3_free(db);
120455 ** Rollback all database files. If tripCode is not SQLITE_OK, then
120456 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
120457 ** breaker") and made to return tripCode if there are any further
120458 ** attempts to use that cursor.
120460 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
120461 int i;
120462 int inTrans = 0;
120463 assert( sqlite3_mutex_held(db->mutex) );
120464 sqlite3BeginBenignMalloc();
120466 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
120467 ** This is important in case the transaction being rolled back has
120468 ** modified the database schema. If the b-tree mutexes are not taken
120469 ** here, then another shared-cache connection might sneak in between
120470 ** the database rollback and schema reset, which can cause false
120471 ** corruption reports in some cases. */
120472 sqlite3BtreeEnterAll(db);
120474 for(i=0; i<db->nDb; i++){
120475 Btree *p = db->aDb[i].pBt;
120476 if( p ){
120477 if( sqlite3BtreeIsInTrans(p) ){
120478 inTrans = 1;
120480 sqlite3BtreeRollback(p, tripCode);
120483 sqlite3VtabRollback(db);
120484 sqlite3EndBenignMalloc();
120486 if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
120487 sqlite3ExpirePreparedStatements(db);
120488 sqlite3ResetAllSchemasOfConnection(db);
120490 sqlite3BtreeLeaveAll(db);
120492 /* Any deferred constraint violations have now been resolved. */
120493 db->nDeferredCons = 0;
120494 db->nDeferredImmCons = 0;
120495 db->flags &= ~SQLITE_DeferFKs;
120497 /* If one has been configured, invoke the rollback-hook callback */
120498 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
120499 db->xRollbackCallback(db->pRollbackArg);
120504 ** Return a static string containing the name corresponding to the error code
120505 ** specified in the argument.
120507 #if defined(SQLITE_TEST)
120508 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
120509 const char *zName = 0;
120510 int i, origRc = rc;
120511 for(i=0; i<2 && zName==0; i++, rc &= 0xff){
120512 switch( rc ){
120513 case SQLITE_OK: zName = "SQLITE_OK"; break;
120514 case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
120515 case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
120516 case SQLITE_PERM: zName = "SQLITE_PERM"; break;
120517 case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
120518 case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
120519 case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
120520 case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
120521 case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
120522 case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
120523 case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
120524 case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
120525 case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
120526 case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
120527 case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
120528 case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
120529 case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
120530 case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
120531 case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
120532 case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
120533 case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
120534 case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
120535 case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
120536 case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
120537 case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
120538 case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
120539 case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
120540 case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
120541 case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
120542 case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
120543 case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
120544 case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
120545 case SQLITE_IOERR_CHECKRESERVEDLOCK:
120546 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
120547 case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
120548 case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
120549 case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
120550 case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
120551 case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
120552 case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
120553 case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
120554 case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
120555 case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
120556 case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
120557 case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
120558 case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
120559 case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
120560 case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
120561 case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
120562 case SQLITE_FULL: zName = "SQLITE_FULL"; break;
120563 case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
120564 case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
120565 case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
120566 case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
120567 case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
120568 case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
120569 case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
120570 case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
120571 case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
120572 case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
120573 case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
120574 case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
120575 case SQLITE_CONSTRAINT_FOREIGNKEY:
120576 zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
120577 case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
120578 case SQLITE_CONSTRAINT_PRIMARYKEY:
120579 zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
120580 case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
120581 case SQLITE_CONSTRAINT_COMMITHOOK:
120582 zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
120583 case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
120584 case SQLITE_CONSTRAINT_FUNCTION:
120585 zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
120586 case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
120587 case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
120588 case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
120589 case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
120590 case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
120591 case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
120592 case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
120593 case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
120594 case SQLITE_ROW: zName = "SQLITE_ROW"; break;
120595 case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
120596 case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
120597 case SQLITE_NOTICE_RECOVER_ROLLBACK:
120598 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
120599 case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
120600 case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
120601 case SQLITE_DONE: zName = "SQLITE_DONE"; break;
120604 if( zName==0 ){
120605 static char zBuf[50];
120606 sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
120607 zName = zBuf;
120609 return zName;
120611 #endif
120614 ** Return a static string that describes the kind of error specified in the
120615 ** argument.
120617 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
120618 static const char* const aMsg[] = {
120619 /* SQLITE_OK */ "not an error",
120620 /* SQLITE_ERROR */ "SQL logic error or missing database",
120621 /* SQLITE_INTERNAL */ 0,
120622 /* SQLITE_PERM */ "access permission denied",
120623 /* SQLITE_ABORT */ "callback requested query abort",
120624 /* SQLITE_BUSY */ "database is locked",
120625 /* SQLITE_LOCKED */ "database table is locked",
120626 /* SQLITE_NOMEM */ "out of memory",
120627 /* SQLITE_READONLY */ "attempt to write a readonly database",
120628 /* SQLITE_INTERRUPT */ "interrupted",
120629 /* SQLITE_IOERR */ "disk I/O error",
120630 /* SQLITE_CORRUPT */ "database disk image is malformed",
120631 /* SQLITE_NOTFOUND */ "unknown operation",
120632 /* SQLITE_FULL */ "database or disk is full",
120633 /* SQLITE_CANTOPEN */ "unable to open database file",
120634 /* SQLITE_PROTOCOL */ "locking protocol",
120635 /* SQLITE_EMPTY */ "table contains no data",
120636 /* SQLITE_SCHEMA */ "database schema has changed",
120637 /* SQLITE_TOOBIG */ "string or blob too big",
120638 /* SQLITE_CONSTRAINT */ "constraint failed",
120639 /* SQLITE_MISMATCH */ "datatype mismatch",
120640 /* SQLITE_MISUSE */ "library routine called out of sequence",
120641 /* SQLITE_NOLFS */ "large file support is disabled",
120642 /* SQLITE_AUTH */ "authorization denied",
120643 /* SQLITE_FORMAT */ "auxiliary database format error",
120644 /* SQLITE_RANGE */ "bind or column index out of range",
120645 /* SQLITE_NOTADB */ "file is encrypted or is not a database",
120647 const char *zErr = "unknown error";
120648 switch( rc ){
120649 case SQLITE_ABORT_ROLLBACK: {
120650 zErr = "abort due to ROLLBACK";
120651 break;
120653 default: {
120654 rc &= 0xff;
120655 if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
120656 zErr = aMsg[rc];
120658 break;
120661 return zErr;
120665 ** This routine implements a busy callback that sleeps and tries
120666 ** again until a timeout value is reached. The timeout value is
120667 ** an integer number of milliseconds passed in as the first
120668 ** argument.
120670 static int sqliteDefaultBusyCallback(
120671 void *ptr, /* Database connection */
120672 int count /* Number of times table has been busy */
120674 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
120675 static const u8 delays[] =
120676 { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
120677 static const u8 totals[] =
120678 { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
120679 # define NDELAY ArraySize(delays)
120680 sqlite3 *db = (sqlite3 *)ptr;
120681 int timeout = db->busyTimeout;
120682 int delay, prior;
120684 assert( count>=0 );
120685 if( count < NDELAY ){
120686 delay = delays[count];
120687 prior = totals[count];
120688 }else{
120689 delay = delays[NDELAY-1];
120690 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
120692 if( prior + delay > timeout ){
120693 delay = timeout - prior;
120694 if( delay<=0 ) return 0;
120696 sqlite3OsSleep(db->pVfs, delay*1000);
120697 return 1;
120698 #else
120699 sqlite3 *db = (sqlite3 *)ptr;
120700 int timeout = ((sqlite3 *)ptr)->busyTimeout;
120701 if( (count+1)*1000 > timeout ){
120702 return 0;
120704 sqlite3OsSleep(db->pVfs, 1000000);
120705 return 1;
120706 #endif
120710 ** Invoke the given busy handler.
120712 ** This routine is called when an operation failed with a lock.
120713 ** If this routine returns non-zero, the lock is retried. If it
120714 ** returns 0, the operation aborts with an SQLITE_BUSY error.
120716 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
120717 int rc;
120718 if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
120719 rc = p->xFunc(p->pArg, p->nBusy);
120720 if( rc==0 ){
120721 p->nBusy = -1;
120722 }else{
120723 p->nBusy++;
120725 return rc;
120729 ** This routine sets the busy callback for an Sqlite database to the
120730 ** given callback function with the given argument.
120732 SQLITE_API int sqlite3_busy_handler(
120733 sqlite3 *db,
120734 int (*xBusy)(void*,int),
120735 void *pArg
120737 sqlite3_mutex_enter(db->mutex);
120738 db->busyHandler.xFunc = xBusy;
120739 db->busyHandler.pArg = pArg;
120740 db->busyHandler.nBusy = 0;
120741 db->busyTimeout = 0;
120742 sqlite3_mutex_leave(db->mutex);
120743 return SQLITE_OK;
120746 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
120748 ** This routine sets the progress callback for an Sqlite database to the
120749 ** given callback function with the given argument. The progress callback will
120750 ** be invoked every nOps opcodes.
120752 SQLITE_API void sqlite3_progress_handler(
120753 sqlite3 *db,
120754 int nOps,
120755 int (*xProgress)(void*),
120756 void *pArg
120758 sqlite3_mutex_enter(db->mutex);
120759 if( nOps>0 ){
120760 db->xProgress = xProgress;
120761 db->nProgressOps = (unsigned)nOps;
120762 db->pProgressArg = pArg;
120763 }else{
120764 db->xProgress = 0;
120765 db->nProgressOps = 0;
120766 db->pProgressArg = 0;
120768 sqlite3_mutex_leave(db->mutex);
120770 #endif
120774 ** This routine installs a default busy handler that waits for the
120775 ** specified number of milliseconds before returning 0.
120777 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
120778 if( ms>0 ){
120779 sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
120780 db->busyTimeout = ms;
120781 }else{
120782 sqlite3_busy_handler(db, 0, 0);
120784 return SQLITE_OK;
120788 ** Cause any pending operation to stop at its earliest opportunity.
120790 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
120791 db->u1.isInterrupted = 1;
120796 ** This function is exactly the same as sqlite3_create_function(), except
120797 ** that it is designed to be called by internal code. The difference is
120798 ** that if a malloc() fails in sqlite3_create_function(), an error code
120799 ** is returned and the mallocFailed flag cleared.
120801 SQLITE_PRIVATE int sqlite3CreateFunc(
120802 sqlite3 *db,
120803 const char *zFunctionName,
120804 int nArg,
120805 int enc,
120806 void *pUserData,
120807 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
120808 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
120809 void (*xFinal)(sqlite3_context*),
120810 FuncDestructor *pDestructor
120812 FuncDef *p;
120813 int nName;
120814 int extraFlags;
120816 assert( sqlite3_mutex_held(db->mutex) );
120817 if( zFunctionName==0 ||
120818 (xFunc && (xFinal || xStep)) ||
120819 (!xFunc && (xFinal && !xStep)) ||
120820 (!xFunc && (!xFinal && xStep)) ||
120821 (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
120822 (255<(nName = sqlite3Strlen30( zFunctionName))) ){
120823 return SQLITE_MISUSE_BKPT;
120826 assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
120827 extraFlags = enc & SQLITE_DETERMINISTIC;
120828 enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
120830 #ifndef SQLITE_OMIT_UTF16
120831 /* If SQLITE_UTF16 is specified as the encoding type, transform this
120832 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
120833 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
120835 ** If SQLITE_ANY is specified, add three versions of the function
120836 ** to the hash table.
120838 if( enc==SQLITE_UTF16 ){
120839 enc = SQLITE_UTF16NATIVE;
120840 }else if( enc==SQLITE_ANY ){
120841 int rc;
120842 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
120843 pUserData, xFunc, xStep, xFinal, pDestructor);
120844 if( rc==SQLITE_OK ){
120845 rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
120846 pUserData, xFunc, xStep, xFinal, pDestructor);
120848 if( rc!=SQLITE_OK ){
120849 return rc;
120851 enc = SQLITE_UTF16BE;
120853 #else
120854 enc = SQLITE_UTF8;
120855 #endif
120857 /* Check if an existing function is being overridden or deleted. If so,
120858 ** and there are active VMs, then return SQLITE_BUSY. If a function
120859 ** is being overridden/deleted but there are no active VMs, allow the
120860 ** operation to continue but invalidate all precompiled statements.
120862 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
120863 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
120864 if( db->nVdbeActive ){
120865 sqlite3Error(db, SQLITE_BUSY,
120866 "unable to delete/modify user-function due to active statements");
120867 assert( !db->mallocFailed );
120868 return SQLITE_BUSY;
120869 }else{
120870 sqlite3ExpirePreparedStatements(db);
120874 p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
120875 assert(p || db->mallocFailed);
120876 if( !p ){
120877 return SQLITE_NOMEM;
120880 /* If an older version of the function with a configured destructor is
120881 ** being replaced invoke the destructor function here. */
120882 functionDestroy(db, p);
120884 if( pDestructor ){
120885 pDestructor->nRef++;
120887 p->pDestructor = pDestructor;
120888 p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
120889 testcase( p->funcFlags & SQLITE_DETERMINISTIC );
120890 p->xFunc = xFunc;
120891 p->xStep = xStep;
120892 p->xFinalize = xFinal;
120893 p->pUserData = pUserData;
120894 p->nArg = (u16)nArg;
120895 return SQLITE_OK;
120899 ** Create new user functions.
120901 SQLITE_API int sqlite3_create_function(
120902 sqlite3 *db,
120903 const char *zFunc,
120904 int nArg,
120905 int enc,
120906 void *p,
120907 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
120908 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
120909 void (*xFinal)(sqlite3_context*)
120911 return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
120912 xFinal, 0);
120915 SQLITE_API int sqlite3_create_function_v2(
120916 sqlite3 *db,
120917 const char *zFunc,
120918 int nArg,
120919 int enc,
120920 void *p,
120921 void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
120922 void (*xStep)(sqlite3_context*,int,sqlite3_value **),
120923 void (*xFinal)(sqlite3_context*),
120924 void (*xDestroy)(void *)
120926 int rc = SQLITE_ERROR;
120927 FuncDestructor *pArg = 0;
120928 sqlite3_mutex_enter(db->mutex);
120929 if( xDestroy ){
120930 pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
120931 if( !pArg ){
120932 xDestroy(p);
120933 goto out;
120935 pArg->xDestroy = xDestroy;
120936 pArg->pUserData = p;
120938 rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
120939 if( pArg && pArg->nRef==0 ){
120940 assert( rc!=SQLITE_OK );
120941 xDestroy(p);
120942 sqlite3DbFree(db, pArg);
120946 rc = sqlite3ApiExit(db, rc);
120947 sqlite3_mutex_leave(db->mutex);
120948 return rc;
120951 #ifndef SQLITE_OMIT_UTF16
120952 SQLITE_API int sqlite3_create_function16(
120953 sqlite3 *db,
120954 const void *zFunctionName,
120955 int nArg,
120956 int eTextRep,
120957 void *p,
120958 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
120959 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
120960 void (*xFinal)(sqlite3_context*)
120962 int rc;
120963 char *zFunc8;
120964 sqlite3_mutex_enter(db->mutex);
120965 assert( !db->mallocFailed );
120966 zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
120967 rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
120968 sqlite3DbFree(db, zFunc8);
120969 rc = sqlite3ApiExit(db, rc);
120970 sqlite3_mutex_leave(db->mutex);
120971 return rc;
120973 #endif
120977 ** Declare that a function has been overloaded by a virtual table.
120979 ** If the function already exists as a regular global function, then
120980 ** this routine is a no-op. If the function does not exist, then create
120981 ** a new one that always throws a run-time error.
120983 ** When virtual tables intend to provide an overloaded function, they
120984 ** should call this routine to make sure the global function exists.
120985 ** A global function must exist in order for name resolution to work
120986 ** properly.
120988 SQLITE_API int sqlite3_overload_function(
120989 sqlite3 *db,
120990 const char *zName,
120991 int nArg
120993 int nName = sqlite3Strlen30(zName);
120994 int rc = SQLITE_OK;
120995 sqlite3_mutex_enter(db->mutex);
120996 if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
120997 rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
120998 0, sqlite3InvalidFunction, 0, 0, 0);
121000 rc = sqlite3ApiExit(db, rc);
121001 sqlite3_mutex_leave(db->mutex);
121002 return rc;
121005 #ifndef SQLITE_OMIT_TRACE
121007 ** Register a trace function. The pArg from the previously registered trace
121008 ** is returned.
121010 ** A NULL trace function means that no tracing is executes. A non-NULL
121011 ** trace is a pointer to a function that is invoked at the start of each
121012 ** SQL statement.
121014 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
121015 void *pOld;
121016 sqlite3_mutex_enter(db->mutex);
121017 pOld = db->pTraceArg;
121018 db->xTrace = xTrace;
121019 db->pTraceArg = pArg;
121020 sqlite3_mutex_leave(db->mutex);
121021 return pOld;
121024 ** Register a profile function. The pArg from the previously registered
121025 ** profile function is returned.
121027 ** A NULL profile function means that no profiling is executes. A non-NULL
121028 ** profile is a pointer to a function that is invoked at the conclusion of
121029 ** each SQL statement that is run.
121031 SQLITE_API void *sqlite3_profile(
121032 sqlite3 *db,
121033 void (*xProfile)(void*,const char*,sqlite_uint64),
121034 void *pArg
121036 void *pOld;
121037 sqlite3_mutex_enter(db->mutex);
121038 pOld = db->pProfileArg;
121039 db->xProfile = xProfile;
121040 db->pProfileArg = pArg;
121041 sqlite3_mutex_leave(db->mutex);
121042 return pOld;
121044 #endif /* SQLITE_OMIT_TRACE */
121047 ** Register a function to be invoked when a transaction commits.
121048 ** If the invoked function returns non-zero, then the commit becomes a
121049 ** rollback.
121051 SQLITE_API void *sqlite3_commit_hook(
121052 sqlite3 *db, /* Attach the hook to this database */
121053 int (*xCallback)(void*), /* Function to invoke on each commit */
121054 void *pArg /* Argument to the function */
121056 void *pOld;
121057 sqlite3_mutex_enter(db->mutex);
121058 pOld = db->pCommitArg;
121059 db->xCommitCallback = xCallback;
121060 db->pCommitArg = pArg;
121061 sqlite3_mutex_leave(db->mutex);
121062 return pOld;
121066 ** Register a callback to be invoked each time a row is updated,
121067 ** inserted or deleted using this database connection.
121069 SQLITE_API void *sqlite3_update_hook(
121070 sqlite3 *db, /* Attach the hook to this database */
121071 void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
121072 void *pArg /* Argument to the function */
121074 void *pRet;
121075 sqlite3_mutex_enter(db->mutex);
121076 pRet = db->pUpdateArg;
121077 db->xUpdateCallback = xCallback;
121078 db->pUpdateArg = pArg;
121079 sqlite3_mutex_leave(db->mutex);
121080 return pRet;
121084 ** Register a callback to be invoked each time a transaction is rolled
121085 ** back by this database connection.
121087 SQLITE_API void *sqlite3_rollback_hook(
121088 sqlite3 *db, /* Attach the hook to this database */
121089 void (*xCallback)(void*), /* Callback function */
121090 void *pArg /* Argument to the function */
121092 void *pRet;
121093 sqlite3_mutex_enter(db->mutex);
121094 pRet = db->pRollbackArg;
121095 db->xRollbackCallback = xCallback;
121096 db->pRollbackArg = pArg;
121097 sqlite3_mutex_leave(db->mutex);
121098 return pRet;
121101 #ifndef SQLITE_OMIT_WAL
121103 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
121104 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
121105 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
121106 ** wal_autocheckpoint()).
121108 SQLITE_PRIVATE int sqlite3WalDefaultHook(
121109 void *pClientData, /* Argument */
121110 sqlite3 *db, /* Connection */
121111 const char *zDb, /* Database */
121112 int nFrame /* Size of WAL */
121114 if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
121115 sqlite3BeginBenignMalloc();
121116 sqlite3_wal_checkpoint(db, zDb);
121117 sqlite3EndBenignMalloc();
121119 return SQLITE_OK;
121121 #endif /* SQLITE_OMIT_WAL */
121124 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
121125 ** a database after committing a transaction if there are nFrame or
121126 ** more frames in the log file. Passing zero or a negative value as the
121127 ** nFrame parameter disables automatic checkpoints entirely.
121129 ** The callback registered by this function replaces any existing callback
121130 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
121131 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
121132 ** configured by this function.
121134 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
121135 #ifdef SQLITE_OMIT_WAL
121136 UNUSED_PARAMETER(db);
121137 UNUSED_PARAMETER(nFrame);
121138 #else
121139 if( nFrame>0 ){
121140 sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
121141 }else{
121142 sqlite3_wal_hook(db, 0, 0);
121144 #endif
121145 return SQLITE_OK;
121149 ** Register a callback to be invoked each time a transaction is written
121150 ** into the write-ahead-log by this database connection.
121152 SQLITE_API void *sqlite3_wal_hook(
121153 sqlite3 *db, /* Attach the hook to this db handle */
121154 int(*xCallback)(void *, sqlite3*, const char*, int),
121155 void *pArg /* First argument passed to xCallback() */
121157 #ifndef SQLITE_OMIT_WAL
121158 void *pRet;
121159 sqlite3_mutex_enter(db->mutex);
121160 pRet = db->pWalArg;
121161 db->xWalCallback = xCallback;
121162 db->pWalArg = pArg;
121163 sqlite3_mutex_leave(db->mutex);
121164 return pRet;
121165 #else
121166 return 0;
121167 #endif
121171 ** Checkpoint database zDb.
121173 SQLITE_API int sqlite3_wal_checkpoint_v2(
121174 sqlite3 *db, /* Database handle */
121175 const char *zDb, /* Name of attached database (or NULL) */
121176 int eMode, /* SQLITE_CHECKPOINT_* value */
121177 int *pnLog, /* OUT: Size of WAL log in frames */
121178 int *pnCkpt /* OUT: Total number of frames checkpointed */
121180 #ifdef SQLITE_OMIT_WAL
121181 return SQLITE_OK;
121182 #else
121183 int rc; /* Return code */
121184 int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
121186 /* Initialize the output variables to -1 in case an error occurs. */
121187 if( pnLog ) *pnLog = -1;
121188 if( pnCkpt ) *pnCkpt = -1;
121190 assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
121191 assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
121192 assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
121193 if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
121194 return SQLITE_MISUSE;
121197 sqlite3_mutex_enter(db->mutex);
121198 if( zDb && zDb[0] ){
121199 iDb = sqlite3FindDbName(db, zDb);
121201 if( iDb<0 ){
121202 rc = SQLITE_ERROR;
121203 sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
121204 }else{
121205 rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
121206 sqlite3Error(db, rc, 0);
121208 rc = sqlite3ApiExit(db, rc);
121209 sqlite3_mutex_leave(db->mutex);
121210 return rc;
121211 #endif
121216 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
121217 ** to contains a zero-length string, all attached databases are
121218 ** checkpointed.
121220 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
121221 return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
121224 #ifndef SQLITE_OMIT_WAL
121226 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
121227 ** not currently open in WAL mode.
121229 ** If a transaction is open on the database being checkpointed, this
121230 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
121231 ** an error occurs while running the checkpoint, an SQLite error code is
121232 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
121234 ** The mutex on database handle db should be held by the caller. The mutex
121235 ** associated with the specific b-tree being checkpointed is taken by
121236 ** this function while the checkpoint is running.
121238 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
121239 ** checkpointed. If an error is encountered it is returned immediately -
121240 ** no attempt is made to checkpoint any remaining databases.
121242 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
121244 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
121245 int rc = SQLITE_OK; /* Return code */
121246 int i; /* Used to iterate through attached dbs */
121247 int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
121249 assert( sqlite3_mutex_held(db->mutex) );
121250 assert( !pnLog || *pnLog==-1 );
121251 assert( !pnCkpt || *pnCkpt==-1 );
121253 for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
121254 if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
121255 rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
121256 pnLog = 0;
121257 pnCkpt = 0;
121258 if( rc==SQLITE_BUSY ){
121259 bBusy = 1;
121260 rc = SQLITE_OK;
121265 return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
121267 #endif /* SQLITE_OMIT_WAL */
121270 ** This function returns true if main-memory should be used instead of
121271 ** a temporary file for transient pager files and statement journals.
121272 ** The value returned depends on the value of db->temp_store (runtime
121273 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
121274 ** following table describes the relationship between these two values
121275 ** and this functions return value.
121277 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
121278 ** ----------------- -------------- ------------------------------
121279 ** 0 any file (return 0)
121280 ** 1 1 file (return 0)
121281 ** 1 2 memory (return 1)
121282 ** 1 0 file (return 0)
121283 ** 2 1 file (return 0)
121284 ** 2 2 memory (return 1)
121285 ** 2 0 memory (return 1)
121286 ** 3 any memory (return 1)
121288 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
121289 #if SQLITE_TEMP_STORE==1
121290 return ( db->temp_store==2 );
121291 #endif
121292 #if SQLITE_TEMP_STORE==2
121293 return ( db->temp_store!=1 );
121294 #endif
121295 #if SQLITE_TEMP_STORE==3
121296 return 1;
121297 #endif
121298 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
121299 return 0;
121300 #endif
121304 ** Return UTF-8 encoded English language explanation of the most recent
121305 ** error.
121307 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
121308 const char *z;
121309 if( !db ){
121310 return sqlite3ErrStr(SQLITE_NOMEM);
121312 if( !sqlite3SafetyCheckSickOrOk(db) ){
121313 return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
121315 sqlite3_mutex_enter(db->mutex);
121316 if( db->mallocFailed ){
121317 z = sqlite3ErrStr(SQLITE_NOMEM);
121318 }else{
121319 testcase( db->pErr==0 );
121320 z = (char*)sqlite3_value_text(db->pErr);
121321 assert( !db->mallocFailed );
121322 if( z==0 ){
121323 z = sqlite3ErrStr(db->errCode);
121326 sqlite3_mutex_leave(db->mutex);
121327 return z;
121330 #ifndef SQLITE_OMIT_UTF16
121332 ** Return UTF-16 encoded English language explanation of the most recent
121333 ** error.
121335 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
121336 static const u16 outOfMem[] = {
121337 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
121339 static const u16 misuse[] = {
121340 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
121341 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
121342 'c', 'a', 'l', 'l', 'e', 'd', ' ',
121343 'o', 'u', 't', ' ',
121344 'o', 'f', ' ',
121345 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
121348 const void *z;
121349 if( !db ){
121350 return (void *)outOfMem;
121352 if( !sqlite3SafetyCheckSickOrOk(db) ){
121353 return (void *)misuse;
121355 sqlite3_mutex_enter(db->mutex);
121356 if( db->mallocFailed ){
121357 z = (void *)outOfMem;
121358 }else{
121359 z = sqlite3_value_text16(db->pErr);
121360 if( z==0 ){
121361 sqlite3Error(db, db->errCode, sqlite3ErrStr(db->errCode));
121362 z = sqlite3_value_text16(db->pErr);
121364 /* A malloc() may have failed within the call to sqlite3_value_text16()
121365 ** above. If this is the case, then the db->mallocFailed flag needs to
121366 ** be cleared before returning. Do this directly, instead of via
121367 ** sqlite3ApiExit(), to avoid setting the database handle error message.
121369 db->mallocFailed = 0;
121371 sqlite3_mutex_leave(db->mutex);
121372 return z;
121374 #endif /* SQLITE_OMIT_UTF16 */
121377 ** Return the most recent error code generated by an SQLite routine. If NULL is
121378 ** passed to this function, we assume a malloc() failed during sqlite3_open().
121380 SQLITE_API int sqlite3_errcode(sqlite3 *db){
121381 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
121382 return SQLITE_MISUSE_BKPT;
121384 if( !db || db->mallocFailed ){
121385 return SQLITE_NOMEM;
121387 return db->errCode & db->errMask;
121389 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
121390 if( db && !sqlite3SafetyCheckSickOrOk(db) ){
121391 return SQLITE_MISUSE_BKPT;
121393 if( !db || db->mallocFailed ){
121394 return SQLITE_NOMEM;
121396 return db->errCode;
121400 ** Return a string that describes the kind of error specified in the
121401 ** argument. For now, this simply calls the internal sqlite3ErrStr()
121402 ** function.
121404 SQLITE_API const char *sqlite3_errstr(int rc){
121405 return sqlite3ErrStr(rc);
121409 ** Invalidate all cached KeyInfo objects for database connection "db"
121411 static void invalidateCachedKeyInfo(sqlite3 *db){
121412 Db *pDb; /* A single database */
121413 int iDb; /* The database index number */
121414 HashElem *k; /* For looping over tables in pDb */
121415 Table *pTab; /* A table in the database */
121416 Index *pIdx; /* Each index */
121418 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
121419 if( pDb->pBt==0 ) continue;
121420 sqlite3BtreeEnter(pDb->pBt);
121421 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
121422 pTab = (Table*)sqliteHashData(k);
121423 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121424 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
121425 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
121426 pIdx->pKeyInfo = 0;
121430 sqlite3BtreeLeave(pDb->pBt);
121435 ** Create a new collating function for database "db". The name is zName
121436 ** and the encoding is enc.
121438 static int createCollation(
121439 sqlite3* db,
121440 const char *zName,
121441 u8 enc,
121442 void* pCtx,
121443 int(*xCompare)(void*,int,const void*,int,const void*),
121444 void(*xDel)(void*)
121446 CollSeq *pColl;
121447 int enc2;
121448 int nName = sqlite3Strlen30(zName);
121450 assert( sqlite3_mutex_held(db->mutex) );
121452 /* If SQLITE_UTF16 is specified as the encoding type, transform this
121453 ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
121454 ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
121456 enc2 = enc;
121457 testcase( enc2==SQLITE_UTF16 );
121458 testcase( enc2==SQLITE_UTF16_ALIGNED );
121459 if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
121460 enc2 = SQLITE_UTF16NATIVE;
121462 if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
121463 return SQLITE_MISUSE_BKPT;
121466 /* Check if this call is removing or replacing an existing collation
121467 ** sequence. If so, and there are active VMs, return busy. If there
121468 ** are no active VMs, invalidate any pre-compiled statements.
121470 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
121471 if( pColl && pColl->xCmp ){
121472 if( db->nVdbeActive ){
121473 sqlite3Error(db, SQLITE_BUSY,
121474 "unable to delete/modify collation sequence due to active statements");
121475 return SQLITE_BUSY;
121477 sqlite3ExpirePreparedStatements(db);
121478 invalidateCachedKeyInfo(db);
121480 /* If collation sequence pColl was created directly by a call to
121481 ** sqlite3_create_collation, and not generated by synthCollSeq(),
121482 ** then any copies made by synthCollSeq() need to be invalidated.
121483 ** Also, collation destructor - CollSeq.xDel() - function may need
121484 ** to be called.
121486 if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
121487 CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
121488 int j;
121489 for(j=0; j<3; j++){
121490 CollSeq *p = &aColl[j];
121491 if( p->enc==pColl->enc ){
121492 if( p->xDel ){
121493 p->xDel(p->pUser);
121495 p->xCmp = 0;
121501 pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
121502 if( pColl==0 ) return SQLITE_NOMEM;
121503 pColl->xCmp = xCompare;
121504 pColl->pUser = pCtx;
121505 pColl->xDel = xDel;
121506 pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
121507 sqlite3Error(db, SQLITE_OK, 0);
121508 return SQLITE_OK;
121513 ** This array defines hard upper bounds on limit values. The
121514 ** initializer must be kept in sync with the SQLITE_LIMIT_*
121515 ** #defines in sqlite3.h.
121517 static const int aHardLimit[] = {
121518 SQLITE_MAX_LENGTH,
121519 SQLITE_MAX_SQL_LENGTH,
121520 SQLITE_MAX_COLUMN,
121521 SQLITE_MAX_EXPR_DEPTH,
121522 SQLITE_MAX_COMPOUND_SELECT,
121523 SQLITE_MAX_VDBE_OP,
121524 SQLITE_MAX_FUNCTION_ARG,
121525 SQLITE_MAX_ATTACHED,
121526 SQLITE_MAX_LIKE_PATTERN_LENGTH,
121527 SQLITE_MAX_VARIABLE_NUMBER,
121528 SQLITE_MAX_TRIGGER_DEPTH,
121532 ** Make sure the hard limits are set to reasonable values
121534 #if SQLITE_MAX_LENGTH<100
121535 # error SQLITE_MAX_LENGTH must be at least 100
121536 #endif
121537 #if SQLITE_MAX_SQL_LENGTH<100
121538 # error SQLITE_MAX_SQL_LENGTH must be at least 100
121539 #endif
121540 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
121541 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
121542 #endif
121543 #if SQLITE_MAX_COMPOUND_SELECT<2
121544 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
121545 #endif
121546 #if SQLITE_MAX_VDBE_OP<40
121547 # error SQLITE_MAX_VDBE_OP must be at least 40
121548 #endif
121549 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
121550 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
121551 #endif
121552 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
121553 # error SQLITE_MAX_ATTACHED must be between 0 and 62
121554 #endif
121555 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
121556 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
121557 #endif
121558 #if SQLITE_MAX_COLUMN>32767
121559 # error SQLITE_MAX_COLUMN must not exceed 32767
121560 #endif
121561 #if SQLITE_MAX_TRIGGER_DEPTH<1
121562 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
121563 #endif
121567 ** Change the value of a limit. Report the old value.
121568 ** If an invalid limit index is supplied, report -1.
121569 ** Make no changes but still report the old value if the
121570 ** new limit is negative.
121572 ** A new lower limit does not shrink existing constructs.
121573 ** It merely prevents new constructs that exceed the limit
121574 ** from forming.
121576 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
121577 int oldLimit;
121580 /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
121581 ** there is a hard upper bound set at compile-time by a C preprocessor
121582 ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
121583 ** "_MAX_".)
121585 assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
121586 assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
121587 assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
121588 assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
121589 assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
121590 assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
121591 assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
121592 assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
121593 assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
121594 SQLITE_MAX_LIKE_PATTERN_LENGTH );
121595 assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
121596 assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
121597 assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
121600 if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
121601 return -1;
121603 oldLimit = db->aLimit[limitId];
121604 if( newLimit>=0 ){ /* IMP: R-52476-28732 */
121605 if( newLimit>aHardLimit[limitId] ){
121606 newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
121608 db->aLimit[limitId] = newLimit;
121610 return oldLimit; /* IMP: R-53341-35419 */
121614 ** This function is used to parse both URIs and non-URI filenames passed by the
121615 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
121616 ** URIs specified as part of ATTACH statements.
121618 ** The first argument to this function is the name of the VFS to use (or
121619 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
121620 ** query parameter. The second argument contains the URI (or non-URI filename)
121621 ** itself. When this function is called the *pFlags variable should contain
121622 ** the default flags to open the database handle with. The value stored in
121623 ** *pFlags may be updated before returning if the URI filename contains
121624 ** "cache=xxx" or "mode=xxx" query parameters.
121626 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
121627 ** the VFS that should be used to open the database file. *pzFile is set to
121628 ** point to a buffer containing the name of the file to open. It is the
121629 ** responsibility of the caller to eventually call sqlite3_free() to release
121630 ** this buffer.
121632 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
121633 ** may be set to point to a buffer containing an English language error
121634 ** message. It is the responsibility of the caller to eventually release
121635 ** this buffer by calling sqlite3_free().
121637 SQLITE_PRIVATE int sqlite3ParseUri(
121638 const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
121639 const char *zUri, /* Nul-terminated URI to parse */
121640 unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
121641 sqlite3_vfs **ppVfs, /* OUT: VFS to use */
121642 char **pzFile, /* OUT: Filename component of URI */
121643 char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
121645 int rc = SQLITE_OK;
121646 unsigned int flags = *pFlags;
121647 const char *zVfs = zDefaultVfs;
121648 char *zFile;
121649 char c;
121650 int nUri = sqlite3Strlen30(zUri);
121652 assert( *pzErrMsg==0 );
121654 if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
121655 && nUri>=5 && memcmp(zUri, "file:", 5)==0
121657 char *zOpt;
121658 int eState; /* Parser state when parsing URI */
121659 int iIn; /* Input character index */
121660 int iOut = 0; /* Output character index */
121661 int nByte = nUri+2; /* Bytes of space to allocate */
121663 /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
121664 ** method that there may be extra parameters following the file-name. */
121665 flags |= SQLITE_OPEN_URI;
121667 for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
121668 zFile = sqlite3_malloc(nByte);
121669 if( !zFile ) return SQLITE_NOMEM;
121671 iIn = 5;
121672 #ifndef SQLITE_ALLOW_URI_AUTHORITY
121673 /* Discard the scheme and authority segments of the URI. */
121674 if( zUri[5]=='/' && zUri[6]=='/' ){
121675 iIn = 7;
121676 while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
121677 if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
121678 *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
121679 iIn-7, &zUri[7]);
121680 rc = SQLITE_ERROR;
121681 goto parse_uri_out;
121684 #endif
121686 /* Copy the filename and any query parameters into the zFile buffer.
121687 ** Decode %HH escape codes along the way.
121689 ** Within this loop, variable eState may be set to 0, 1 or 2, depending
121690 ** on the parsing context. As follows:
121692 ** 0: Parsing file-name.
121693 ** 1: Parsing name section of a name=value query parameter.
121694 ** 2: Parsing value section of a name=value query parameter.
121696 eState = 0;
121697 while( (c = zUri[iIn])!=0 && c!='#' ){
121698 iIn++;
121699 if( c=='%'
121700 && sqlite3Isxdigit(zUri[iIn])
121701 && sqlite3Isxdigit(zUri[iIn+1])
121703 int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
121704 octet += sqlite3HexToInt(zUri[iIn++]);
121706 assert( octet>=0 && octet<256 );
121707 if( octet==0 ){
121708 /* This branch is taken when "%00" appears within the URI. In this
121709 ** case we ignore all text in the remainder of the path, name or
121710 ** value currently being parsed. So ignore the current character
121711 ** and skip to the next "?", "=" or "&", as appropriate. */
121712 while( (c = zUri[iIn])!=0 && c!='#'
121713 && (eState!=0 || c!='?')
121714 && (eState!=1 || (c!='=' && c!='&'))
121715 && (eState!=2 || c!='&')
121717 iIn++;
121719 continue;
121721 c = octet;
121722 }else if( eState==1 && (c=='&' || c=='=') ){
121723 if( zFile[iOut-1]==0 ){
121724 /* An empty option name. Ignore this option altogether. */
121725 while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
121726 continue;
121728 if( c=='&' ){
121729 zFile[iOut++] = '\0';
121730 }else{
121731 eState = 2;
121733 c = 0;
121734 }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
121735 c = 0;
121736 eState = 1;
121738 zFile[iOut++] = c;
121740 if( eState==1 ) zFile[iOut++] = '\0';
121741 zFile[iOut++] = '\0';
121742 zFile[iOut++] = '\0';
121744 /* Check if there were any options specified that should be interpreted
121745 ** here. Options that are interpreted here include "vfs" and those that
121746 ** correspond to flags that may be passed to the sqlite3_open_v2()
121747 ** method. */
121748 zOpt = &zFile[sqlite3Strlen30(zFile)+1];
121749 while( zOpt[0] ){
121750 int nOpt = sqlite3Strlen30(zOpt);
121751 char *zVal = &zOpt[nOpt+1];
121752 int nVal = sqlite3Strlen30(zVal);
121754 if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
121755 zVfs = zVal;
121756 }else{
121757 struct OpenMode {
121758 const char *z;
121759 int mode;
121760 } *aMode = 0;
121761 char *zModeType = 0;
121762 int mask = 0;
121763 int limit = 0;
121765 if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
121766 static struct OpenMode aCacheMode[] = {
121767 { "shared", SQLITE_OPEN_SHAREDCACHE },
121768 { "private", SQLITE_OPEN_PRIVATECACHE },
121769 { 0, 0 }
121772 mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
121773 aMode = aCacheMode;
121774 limit = mask;
121775 zModeType = "cache";
121777 if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
121778 static struct OpenMode aOpenMode[] = {
121779 { "ro", SQLITE_OPEN_READONLY },
121780 { "rw", SQLITE_OPEN_READWRITE },
121781 { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
121782 { "memory", SQLITE_OPEN_MEMORY },
121783 { 0, 0 }
121786 mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
121787 | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
121788 aMode = aOpenMode;
121789 limit = mask & flags;
121790 zModeType = "access";
121793 if( aMode ){
121794 int i;
121795 int mode = 0;
121796 for(i=0; aMode[i].z; i++){
121797 const char *z = aMode[i].z;
121798 if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
121799 mode = aMode[i].mode;
121800 break;
121803 if( mode==0 ){
121804 *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
121805 rc = SQLITE_ERROR;
121806 goto parse_uri_out;
121808 if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
121809 *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
121810 zModeType, zVal);
121811 rc = SQLITE_PERM;
121812 goto parse_uri_out;
121814 flags = (flags & ~mask) | mode;
121818 zOpt = &zVal[nVal+1];
121821 }else{
121822 zFile = sqlite3_malloc(nUri+2);
121823 if( !zFile ) return SQLITE_NOMEM;
121824 memcpy(zFile, zUri, nUri);
121825 zFile[nUri] = '\0';
121826 zFile[nUri+1] = '\0';
121827 flags &= ~SQLITE_OPEN_URI;
121830 *ppVfs = sqlite3_vfs_find(zVfs);
121831 if( *ppVfs==0 ){
121832 *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
121833 rc = SQLITE_ERROR;
121835 parse_uri_out:
121836 if( rc!=SQLITE_OK ){
121837 sqlite3_free(zFile);
121838 zFile = 0;
121840 *pFlags = flags;
121841 *pzFile = zFile;
121842 return rc;
121847 ** This routine does the work of opening a database on behalf of
121848 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
121849 ** is UTF-8 encoded.
121851 static int openDatabase(
121852 const char *zFilename, /* Database filename UTF-8 encoded */
121853 sqlite3 **ppDb, /* OUT: Returned database handle */
121854 unsigned int flags, /* Operational flags */
121855 const char *zVfs /* Name of the VFS to use */
121857 sqlite3 *db; /* Store allocated handle here */
121858 int rc; /* Return code */
121859 int isThreadsafe; /* True for threadsafe connections */
121860 char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
121861 char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
121863 *ppDb = 0;
121864 #ifndef SQLITE_OMIT_AUTOINIT
121865 rc = sqlite3_initialize();
121866 if( rc ) return rc;
121867 #endif
121869 /* Only allow sensible combinations of bits in the flags argument.
121870 ** Throw an error if any non-sense combination is used. If we
121871 ** do not block illegal combinations here, it could trigger
121872 ** assert() statements in deeper layers. Sensible combinations
121873 ** are:
121875 ** 1: SQLITE_OPEN_READONLY
121876 ** 2: SQLITE_OPEN_READWRITE
121877 ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
121879 assert( SQLITE_OPEN_READONLY == 0x01 );
121880 assert( SQLITE_OPEN_READWRITE == 0x02 );
121881 assert( SQLITE_OPEN_CREATE == 0x04 );
121882 testcase( (1<<(flags&7))==0x02 ); /* READONLY */
121883 testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
121884 testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
121885 if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
121887 if( sqlite3GlobalConfig.bCoreMutex==0 ){
121888 isThreadsafe = 0;
121889 }else if( flags & SQLITE_OPEN_NOMUTEX ){
121890 isThreadsafe = 0;
121891 }else if( flags & SQLITE_OPEN_FULLMUTEX ){
121892 isThreadsafe = 1;
121893 }else{
121894 isThreadsafe = sqlite3GlobalConfig.bFullMutex;
121896 if( flags & SQLITE_OPEN_PRIVATECACHE ){
121897 flags &= ~SQLITE_OPEN_SHAREDCACHE;
121898 }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
121899 flags |= SQLITE_OPEN_SHAREDCACHE;
121902 /* Remove harmful bits from the flags parameter
121904 ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
121905 ** dealt with in the previous code block. Besides these, the only
121906 ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
121907 ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
121908 ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
121909 ** off all other flags.
121911 flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
121912 SQLITE_OPEN_EXCLUSIVE |
121913 SQLITE_OPEN_MAIN_DB |
121914 SQLITE_OPEN_TEMP_DB |
121915 SQLITE_OPEN_TRANSIENT_DB |
121916 SQLITE_OPEN_MAIN_JOURNAL |
121917 SQLITE_OPEN_TEMP_JOURNAL |
121918 SQLITE_OPEN_SUBJOURNAL |
121919 SQLITE_OPEN_MASTER_JOURNAL |
121920 SQLITE_OPEN_NOMUTEX |
121921 SQLITE_OPEN_FULLMUTEX |
121922 SQLITE_OPEN_WAL
121925 /* Allocate the sqlite data structure */
121926 db = sqlite3MallocZero( sizeof(sqlite3) );
121927 if( db==0 ) goto opendb_out;
121928 if( isThreadsafe ){
121929 db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
121930 if( db->mutex==0 ){
121931 sqlite3_free(db);
121932 db = 0;
121933 goto opendb_out;
121936 sqlite3_mutex_enter(db->mutex);
121937 db->errMask = 0xff;
121938 db->nDb = 2;
121939 db->magic = SQLITE_MAGIC_BUSY;
121940 db->aDb = db->aDbStatic;
121942 assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
121943 memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
121944 db->autoCommit = 1;
121945 db->nextAutovac = -1;
121946 db->szMmap = sqlite3GlobalConfig.szMmap;
121947 db->nextPagesize = 0;
121948 db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
121949 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
121950 | SQLITE_AutoIndex
121951 #endif
121952 #if SQLITE_DEFAULT_FILE_FORMAT<4
121953 | SQLITE_LegacyFileFmt
121954 #endif
121955 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
121956 | SQLITE_LoadExtension
121957 #endif
121958 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
121959 | SQLITE_RecTriggers
121960 #endif
121961 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
121962 | SQLITE_ForeignKeys
121963 #endif
121965 sqlite3HashInit(&db->aCollSeq);
121966 #ifndef SQLITE_OMIT_VIRTUALTABLE
121967 sqlite3HashInit(&db->aModule);
121968 #endif
121970 /* Add the default collation sequence BINARY. BINARY works for both UTF-8
121971 ** and UTF-16, so add a version for each to avoid any unnecessary
121972 ** conversions. The only error that can occur here is a malloc() failure.
121974 createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
121975 createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
121976 createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
121977 createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
121978 if( db->mallocFailed ){
121979 goto opendb_out;
121981 db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
121982 assert( db->pDfltColl!=0 );
121984 /* Also add a UTF-8 case-insensitive collation sequence. */
121985 createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
121987 /* Parse the filename/URI argument. */
121988 db->openFlags = flags;
121989 rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
121990 if( rc!=SQLITE_OK ){
121991 if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
121992 sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
121993 sqlite3_free(zErrMsg);
121994 goto opendb_out;
121997 /* Open the backend database driver */
121998 rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
121999 flags | SQLITE_OPEN_MAIN_DB);
122000 if( rc!=SQLITE_OK ){
122001 if( rc==SQLITE_IOERR_NOMEM ){
122002 rc = SQLITE_NOMEM;
122004 sqlite3Error(db, rc, 0);
122005 goto opendb_out;
122007 db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
122008 db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
122011 /* The default safety_level for the main database is 'full'; for the temp
122012 ** database it is 'NONE'. This matches the pager layer defaults.
122014 db->aDb[0].zName = "main";
122015 db->aDb[0].safety_level = 3;
122016 db->aDb[1].zName = "temp";
122017 db->aDb[1].safety_level = 1;
122019 db->magic = SQLITE_MAGIC_OPEN;
122020 if( db->mallocFailed ){
122021 goto opendb_out;
122024 /* Register all built-in functions, but do not attempt to read the
122025 ** database schema yet. This is delayed until the first time the database
122026 ** is accessed.
122028 sqlite3Error(db, SQLITE_OK, 0);
122029 sqlite3RegisterBuiltinFunctions(db);
122031 /* Load automatic extensions - extensions that have been registered
122032 ** using the sqlite3_automatic_extension() API.
122034 rc = sqlite3_errcode(db);
122035 if( rc==SQLITE_OK ){
122036 sqlite3AutoLoadExtensions(db);
122037 rc = sqlite3_errcode(db);
122038 if( rc!=SQLITE_OK ){
122039 goto opendb_out;
122043 #ifdef SQLITE_ENABLE_FTS1
122044 if( !db->mallocFailed ){
122045 extern int sqlite3Fts1Init(sqlite3*);
122046 rc = sqlite3Fts1Init(db);
122048 #endif
122050 #ifdef SQLITE_ENABLE_FTS2
122051 if( !db->mallocFailed && rc==SQLITE_OK ){
122052 extern int sqlite3Fts2Init(sqlite3*);
122053 rc = sqlite3Fts2Init(db);
122055 #endif
122057 #ifdef SQLITE_ENABLE_FTS3
122058 if( !db->mallocFailed && rc==SQLITE_OK ){
122059 rc = sqlite3Fts3Init(db);
122061 #endif
122063 #ifdef SQLITE_ENABLE_ICU
122064 if( !db->mallocFailed && rc==SQLITE_OK ){
122065 rc = sqlite3IcuInit(db);
122067 #endif
122069 #ifdef SQLITE_ENABLE_RTREE
122070 if( !db->mallocFailed && rc==SQLITE_OK){
122071 rc = sqlite3RtreeInit(db);
122073 #endif
122075 /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
122076 ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
122077 ** mode. Doing nothing at all also makes NORMAL the default.
122079 #ifdef SQLITE_DEFAULT_LOCKING_MODE
122080 db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
122081 sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
122082 SQLITE_DEFAULT_LOCKING_MODE);
122083 #endif
122085 if( rc ) sqlite3Error(db, rc, 0);
122087 /* Enable the lookaside-malloc subsystem */
122088 setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
122089 sqlite3GlobalConfig.nLookaside);
122091 sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
122093 opendb_out:
122094 sqlite3_free(zOpen);
122095 if( db ){
122096 assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
122097 sqlite3_mutex_leave(db->mutex);
122099 rc = sqlite3_errcode(db);
122100 assert( db!=0 || rc==SQLITE_NOMEM );
122101 if( rc==SQLITE_NOMEM ){
122102 sqlite3_close(db);
122103 db = 0;
122104 }else if( rc!=SQLITE_OK ){
122105 db->magic = SQLITE_MAGIC_SICK;
122107 *ppDb = db;
122108 #ifdef SQLITE_ENABLE_SQLLOG
122109 if( sqlite3GlobalConfig.xSqllog ){
122110 /* Opening a db handle. Fourth parameter is passed 0. */
122111 void *pArg = sqlite3GlobalConfig.pSqllogArg;
122112 sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
122114 #endif
122115 return sqlite3ApiExit(0, rc);
122119 ** Open a new database handle.
122121 SQLITE_API int sqlite3_open(
122122 const char *zFilename,
122123 sqlite3 **ppDb
122125 return openDatabase(zFilename, ppDb,
122126 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
122128 SQLITE_API int sqlite3_open_v2(
122129 const char *filename, /* Database filename (UTF-8) */
122130 sqlite3 **ppDb, /* OUT: SQLite db handle */
122131 int flags, /* Flags */
122132 const char *zVfs /* Name of VFS module to use */
122134 return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
122137 #ifndef SQLITE_OMIT_UTF16
122139 ** Open a new database handle.
122141 SQLITE_API int sqlite3_open16(
122142 const void *zFilename,
122143 sqlite3 **ppDb
122145 char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
122146 sqlite3_value *pVal;
122147 int rc;
122149 assert( zFilename );
122150 assert( ppDb );
122151 *ppDb = 0;
122152 #ifndef SQLITE_OMIT_AUTOINIT
122153 rc = sqlite3_initialize();
122154 if( rc ) return rc;
122155 #endif
122156 pVal = sqlite3ValueNew(0);
122157 sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
122158 zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
122159 if( zFilename8 ){
122160 rc = openDatabase(zFilename8, ppDb,
122161 SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
122162 assert( *ppDb || rc==SQLITE_NOMEM );
122163 if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
122164 ENC(*ppDb) = SQLITE_UTF16NATIVE;
122166 }else{
122167 rc = SQLITE_NOMEM;
122169 sqlite3ValueFree(pVal);
122171 return sqlite3ApiExit(0, rc);
122173 #endif /* SQLITE_OMIT_UTF16 */
122176 ** Register a new collation sequence with the database handle db.
122178 SQLITE_API int sqlite3_create_collation(
122179 sqlite3* db,
122180 const char *zName,
122181 int enc,
122182 void* pCtx,
122183 int(*xCompare)(void*,int,const void*,int,const void*)
122185 int rc;
122186 sqlite3_mutex_enter(db->mutex);
122187 assert( !db->mallocFailed );
122188 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
122189 rc = sqlite3ApiExit(db, rc);
122190 sqlite3_mutex_leave(db->mutex);
122191 return rc;
122195 ** Register a new collation sequence with the database handle db.
122197 SQLITE_API int sqlite3_create_collation_v2(
122198 sqlite3* db,
122199 const char *zName,
122200 int enc,
122201 void* pCtx,
122202 int(*xCompare)(void*,int,const void*,int,const void*),
122203 void(*xDel)(void*)
122205 int rc;
122206 sqlite3_mutex_enter(db->mutex);
122207 assert( !db->mallocFailed );
122208 rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
122209 rc = sqlite3ApiExit(db, rc);
122210 sqlite3_mutex_leave(db->mutex);
122211 return rc;
122214 #ifndef SQLITE_OMIT_UTF16
122216 ** Register a new collation sequence with the database handle db.
122218 SQLITE_API int sqlite3_create_collation16(
122219 sqlite3* db,
122220 const void *zName,
122221 int enc,
122222 void* pCtx,
122223 int(*xCompare)(void*,int,const void*,int,const void*)
122225 int rc = SQLITE_OK;
122226 char *zName8;
122227 sqlite3_mutex_enter(db->mutex);
122228 assert( !db->mallocFailed );
122229 zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
122230 if( zName8 ){
122231 rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
122232 sqlite3DbFree(db, zName8);
122234 rc = sqlite3ApiExit(db, rc);
122235 sqlite3_mutex_leave(db->mutex);
122236 return rc;
122238 #endif /* SQLITE_OMIT_UTF16 */
122241 ** Register a collation sequence factory callback with the database handle
122242 ** db. Replace any previously installed collation sequence factory.
122244 SQLITE_API int sqlite3_collation_needed(
122245 sqlite3 *db,
122246 void *pCollNeededArg,
122247 void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
122249 sqlite3_mutex_enter(db->mutex);
122250 db->xCollNeeded = xCollNeeded;
122251 db->xCollNeeded16 = 0;
122252 db->pCollNeededArg = pCollNeededArg;
122253 sqlite3_mutex_leave(db->mutex);
122254 return SQLITE_OK;
122257 #ifndef SQLITE_OMIT_UTF16
122259 ** Register a collation sequence factory callback with the database handle
122260 ** db. Replace any previously installed collation sequence factory.
122262 SQLITE_API int sqlite3_collation_needed16(
122263 sqlite3 *db,
122264 void *pCollNeededArg,
122265 void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
122267 sqlite3_mutex_enter(db->mutex);
122268 db->xCollNeeded = 0;
122269 db->xCollNeeded16 = xCollNeeded16;
122270 db->pCollNeededArg = pCollNeededArg;
122271 sqlite3_mutex_leave(db->mutex);
122272 return SQLITE_OK;
122274 #endif /* SQLITE_OMIT_UTF16 */
122276 #ifndef SQLITE_OMIT_DEPRECATED
122278 ** This function is now an anachronism. It used to be used to recover from a
122279 ** malloc() failure, but SQLite now does this automatically.
122281 SQLITE_API int sqlite3_global_recover(void){
122282 return SQLITE_OK;
122284 #endif
122287 ** Test to see whether or not the database connection is in autocommit
122288 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
122289 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
122290 ** by the next COMMIT or ROLLBACK.
122292 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
122293 return db->autoCommit;
122297 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
122298 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
122299 ** constants. They server two purposes:
122301 ** 1. Serve as a convenient place to set a breakpoint in a debugger
122302 ** to detect when version error conditions occurs.
122304 ** 2. Invoke sqlite3_log() to provide the source code location where
122305 ** a low-level error is first detected.
122307 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
122308 testcase( sqlite3GlobalConfig.xLog!=0 );
122309 sqlite3_log(SQLITE_CORRUPT,
122310 "database corruption at line %d of [%.10s]",
122311 lineno, 20+sqlite3_sourceid());
122312 return SQLITE_CORRUPT;
122314 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
122315 testcase( sqlite3GlobalConfig.xLog!=0 );
122316 sqlite3_log(SQLITE_MISUSE,
122317 "misuse at line %d of [%.10s]",
122318 lineno, 20+sqlite3_sourceid());
122319 return SQLITE_MISUSE;
122321 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
122322 testcase( sqlite3GlobalConfig.xLog!=0 );
122323 sqlite3_log(SQLITE_CANTOPEN,
122324 "cannot open file at line %d of [%.10s]",
122325 lineno, 20+sqlite3_sourceid());
122326 return SQLITE_CANTOPEN;
122330 #ifndef SQLITE_OMIT_DEPRECATED
122332 ** This is a convenience routine that makes sure that all thread-specific
122333 ** data for this thread has been deallocated.
122335 ** SQLite no longer uses thread-specific data so this routine is now a
122336 ** no-op. It is retained for historical compatibility.
122338 SQLITE_API void sqlite3_thread_cleanup(void){
122340 #endif
122343 ** Return meta information about a specific column of a database table.
122344 ** See comment in sqlite3.h (sqlite.h.in) for details.
122346 #ifdef SQLITE_ENABLE_COLUMN_METADATA
122347 SQLITE_API int sqlite3_table_column_metadata(
122348 sqlite3 *db, /* Connection handle */
122349 const char *zDbName, /* Database name or NULL */
122350 const char *zTableName, /* Table name */
122351 const char *zColumnName, /* Column name */
122352 char const **pzDataType, /* OUTPUT: Declared data type */
122353 char const **pzCollSeq, /* OUTPUT: Collation sequence name */
122354 int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
122355 int *pPrimaryKey, /* OUTPUT: True if column part of PK */
122356 int *pAutoinc /* OUTPUT: True if column is auto-increment */
122358 int rc;
122359 char *zErrMsg = 0;
122360 Table *pTab = 0;
122361 Column *pCol = 0;
122362 int iCol;
122364 char const *zDataType = 0;
122365 char const *zCollSeq = 0;
122366 int notnull = 0;
122367 int primarykey = 0;
122368 int autoinc = 0;
122370 /* Ensure the database schema has been loaded */
122371 sqlite3_mutex_enter(db->mutex);
122372 sqlite3BtreeEnterAll(db);
122373 rc = sqlite3Init(db, &zErrMsg);
122374 if( SQLITE_OK!=rc ){
122375 goto error_out;
122378 /* Locate the table in question */
122379 pTab = sqlite3FindTable(db, zTableName, zDbName);
122380 if( !pTab || pTab->pSelect ){
122381 pTab = 0;
122382 goto error_out;
122385 /* Find the column for which info is requested */
122386 if( sqlite3IsRowid(zColumnName) ){
122387 iCol = pTab->iPKey;
122388 if( iCol>=0 ){
122389 pCol = &pTab->aCol[iCol];
122391 }else{
122392 for(iCol=0; iCol<pTab->nCol; iCol++){
122393 pCol = &pTab->aCol[iCol];
122394 if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
122395 break;
122398 if( iCol==pTab->nCol ){
122399 pTab = 0;
122400 goto error_out;
122404 /* The following block stores the meta information that will be returned
122405 ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
122406 ** and autoinc. At this point there are two possibilities:
122408 ** 1. The specified column name was rowid", "oid" or "_rowid_"
122409 ** and there is no explicitly declared IPK column.
122411 ** 2. The table is not a view and the column name identified an
122412 ** explicitly declared column. Copy meta information from *pCol.
122414 if( pCol ){
122415 zDataType = pCol->zType;
122416 zCollSeq = pCol->zColl;
122417 notnull = pCol->notNull!=0;
122418 primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
122419 autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
122420 }else{
122421 zDataType = "INTEGER";
122422 primarykey = 1;
122424 if( !zCollSeq ){
122425 zCollSeq = "BINARY";
122428 error_out:
122429 sqlite3BtreeLeaveAll(db);
122431 /* Whether the function call succeeded or failed, set the output parameters
122432 ** to whatever their local counterparts contain. If an error did occur,
122433 ** this has the effect of zeroing all output parameters.
122435 if( pzDataType ) *pzDataType = zDataType;
122436 if( pzCollSeq ) *pzCollSeq = zCollSeq;
122437 if( pNotNull ) *pNotNull = notnull;
122438 if( pPrimaryKey ) *pPrimaryKey = primarykey;
122439 if( pAutoinc ) *pAutoinc = autoinc;
122441 if( SQLITE_OK==rc && !pTab ){
122442 sqlite3DbFree(db, zErrMsg);
122443 zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
122444 zColumnName);
122445 rc = SQLITE_ERROR;
122447 sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
122448 sqlite3DbFree(db, zErrMsg);
122449 rc = sqlite3ApiExit(db, rc);
122450 sqlite3_mutex_leave(db->mutex);
122451 return rc;
122453 #endif
122456 ** Sleep for a little while. Return the amount of time slept.
122458 SQLITE_API int sqlite3_sleep(int ms){
122459 sqlite3_vfs *pVfs;
122460 int rc;
122461 pVfs = sqlite3_vfs_find(0);
122462 if( pVfs==0 ) return 0;
122464 /* This function works in milliseconds, but the underlying OsSleep()
122465 ** API uses microseconds. Hence the 1000's.
122467 rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
122468 return rc;
122472 ** Enable or disable the extended result codes.
122474 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
122475 sqlite3_mutex_enter(db->mutex);
122476 db->errMask = onoff ? 0xffffffff : 0xff;
122477 sqlite3_mutex_leave(db->mutex);
122478 return SQLITE_OK;
122482 ** Invoke the xFileControl method on a particular database.
122484 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
122485 int rc = SQLITE_ERROR;
122486 Btree *pBtree;
122488 sqlite3_mutex_enter(db->mutex);
122489 pBtree = sqlite3DbNameToBtree(db, zDbName);
122490 if( pBtree ){
122491 Pager *pPager;
122492 sqlite3_file *fd;
122493 sqlite3BtreeEnter(pBtree);
122494 pPager = sqlite3BtreePager(pBtree);
122495 assert( pPager!=0 );
122496 fd = sqlite3PagerFile(pPager);
122497 assert( fd!=0 );
122498 if( op==SQLITE_FCNTL_FILE_POINTER ){
122499 *(sqlite3_file**)pArg = fd;
122500 rc = SQLITE_OK;
122501 }else if( fd->pMethods ){
122502 rc = sqlite3OsFileControl(fd, op, pArg);
122503 }else{
122504 rc = SQLITE_NOTFOUND;
122506 sqlite3BtreeLeave(pBtree);
122508 sqlite3_mutex_leave(db->mutex);
122509 return rc;
122513 ** Interface to the testing logic.
122515 SQLITE_API int sqlite3_test_control(int op, ...){
122516 int rc = 0;
122517 #ifndef SQLITE_OMIT_BUILTIN_TEST
122518 va_list ap;
122519 va_start(ap, op);
122520 switch( op ){
122523 ** Save the current state of the PRNG.
122525 case SQLITE_TESTCTRL_PRNG_SAVE: {
122526 sqlite3PrngSaveState();
122527 break;
122531 ** Restore the state of the PRNG to the last state saved using
122532 ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
122533 ** this verb acts like PRNG_RESET.
122535 case SQLITE_TESTCTRL_PRNG_RESTORE: {
122536 sqlite3PrngRestoreState();
122537 break;
122541 ** Reset the PRNG back to its uninitialized state. The next call
122542 ** to sqlite3_randomness() will reseed the PRNG using a single call
122543 ** to the xRandomness method of the default VFS.
122545 case SQLITE_TESTCTRL_PRNG_RESET: {
122546 sqlite3_randomness(0,0);
122547 break;
122551 ** sqlite3_test_control(BITVEC_TEST, size, program)
122553 ** Run a test against a Bitvec object of size. The program argument
122554 ** is an array of integers that defines the test. Return -1 on a
122555 ** memory allocation error, 0 on success, or non-zero for an error.
122556 ** See the sqlite3BitvecBuiltinTest() for additional information.
122558 case SQLITE_TESTCTRL_BITVEC_TEST: {
122559 int sz = va_arg(ap, int);
122560 int *aProg = va_arg(ap, int*);
122561 rc = sqlite3BitvecBuiltinTest(sz, aProg);
122562 break;
122566 ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
122568 ** Register hooks to call to indicate which malloc() failures
122569 ** are benign.
122571 case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
122572 typedef void (*void_function)(void);
122573 void_function xBenignBegin;
122574 void_function xBenignEnd;
122575 xBenignBegin = va_arg(ap, void_function);
122576 xBenignEnd = va_arg(ap, void_function);
122577 sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
122578 break;
122582 ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
122584 ** Set the PENDING byte to the value in the argument, if X>0.
122585 ** Make no changes if X==0. Return the value of the pending byte
122586 ** as it existing before this routine was called.
122588 ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
122589 ** an incompatible database file format. Changing the PENDING byte
122590 ** while any database connection is open results in undefined and
122591 ** dileterious behavior.
122593 case SQLITE_TESTCTRL_PENDING_BYTE: {
122594 rc = PENDING_BYTE;
122595 #ifndef SQLITE_OMIT_WSD
122597 unsigned int newVal = va_arg(ap, unsigned int);
122598 if( newVal ) sqlite3PendingByte = newVal;
122600 #endif
122601 break;
122605 ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
122607 ** This action provides a run-time test to see whether or not
122608 ** assert() was enabled at compile-time. If X is true and assert()
122609 ** is enabled, then the return value is true. If X is true and
122610 ** assert() is disabled, then the return value is zero. If X is
122611 ** false and assert() is enabled, then the assertion fires and the
122612 ** process aborts. If X is false and assert() is disabled, then the
122613 ** return value is zero.
122615 case SQLITE_TESTCTRL_ASSERT: {
122616 volatile int x = 0;
122617 assert( (x = va_arg(ap,int))!=0 );
122618 rc = x;
122619 break;
122624 ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
122626 ** This action provides a run-time test to see how the ALWAYS and
122627 ** NEVER macros were defined at compile-time.
122629 ** The return value is ALWAYS(X).
122631 ** The recommended test is X==2. If the return value is 2, that means
122632 ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
122633 ** default setting. If the return value is 1, then ALWAYS() is either
122634 ** hard-coded to true or else it asserts if its argument is false.
122635 ** The first behavior (hard-coded to true) is the case if
122636 ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
122637 ** behavior (assert if the argument to ALWAYS() is false) is the case if
122638 ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
122640 ** The run-time test procedure might look something like this:
122642 ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
122643 ** // ALWAYS() and NEVER() are no-op pass-through macros
122644 ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
122645 ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
122646 ** }else{
122647 ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
122650 case SQLITE_TESTCTRL_ALWAYS: {
122651 int x = va_arg(ap,int);
122652 rc = ALWAYS(x);
122653 break;
122656 /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
122658 ** Set the nReserve size to N for the main database on the database
122659 ** connection db.
122661 case SQLITE_TESTCTRL_RESERVE: {
122662 sqlite3 *db = va_arg(ap, sqlite3*);
122663 int x = va_arg(ap,int);
122664 sqlite3_mutex_enter(db->mutex);
122665 sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
122666 sqlite3_mutex_leave(db->mutex);
122667 break;
122670 /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
122672 ** Enable or disable various optimizations for testing purposes. The
122673 ** argument N is a bitmask of optimizations to be disabled. For normal
122674 ** operation N should be 0. The idea is that a test program (like the
122675 ** SQL Logic Test or SLT test module) can run the same SQL multiple times
122676 ** with various optimizations disabled to verify that the same answer
122677 ** is obtained in every case.
122679 case SQLITE_TESTCTRL_OPTIMIZATIONS: {
122680 sqlite3 *db = va_arg(ap, sqlite3*);
122681 db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
122682 break;
122685 #ifdef SQLITE_N_KEYWORD
122686 /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
122688 ** If zWord is a keyword recognized by the parser, then return the
122689 ** number of keywords. Or if zWord is not a keyword, return 0.
122691 ** This test feature is only available in the amalgamation since
122692 ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
122693 ** is built using separate source files.
122695 case SQLITE_TESTCTRL_ISKEYWORD: {
122696 const char *zWord = va_arg(ap, const char*);
122697 int n = sqlite3Strlen30(zWord);
122698 rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
122699 break;
122701 #endif
122703 /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
122705 ** Pass pFree into sqlite3ScratchFree().
122706 ** If sz>0 then allocate a scratch buffer into pNew.
122708 case SQLITE_TESTCTRL_SCRATCHMALLOC: {
122709 void *pFree, **ppNew;
122710 int sz;
122711 sz = va_arg(ap, int);
122712 ppNew = va_arg(ap, void**);
122713 pFree = va_arg(ap, void*);
122714 if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
122715 sqlite3ScratchFree(pFree);
122716 break;
122719 /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
122721 ** If parameter onoff is non-zero, configure the wrappers so that all
122722 ** subsequent calls to localtime() and variants fail. If onoff is zero,
122723 ** undo this setting.
122725 case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
122726 sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
122727 break;
122730 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
122731 /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
122732 ** sqlite3_stmt*,const char**);
122734 ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
122735 ** a string that describes the optimized parse tree. This test-control
122736 ** returns a pointer to that string.
122738 case SQLITE_TESTCTRL_EXPLAIN_STMT: {
122739 sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
122740 const char **pzRet = va_arg(ap, const char**);
122741 *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
122742 break;
122744 #endif
122746 /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
122748 ** Set or clear a flag that indicates that the database file is always well-
122749 ** formed and never corrupt. This flag is clear by default, indicating that
122750 ** database files might have arbitrary corruption. Setting the flag during
122751 ** testing causes certain assert() statements in the code to be activated
122752 ** that demonstrat invariants on well-formed database files.
122754 case SQLITE_TESTCTRL_NEVER_CORRUPT: {
122755 sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
122756 break;
122760 va_end(ap);
122761 #endif /* SQLITE_OMIT_BUILTIN_TEST */
122762 return rc;
122766 ** This is a utility routine, useful to VFS implementations, that checks
122767 ** to see if a database file was a URI that contained a specific query
122768 ** parameter, and if so obtains the value of the query parameter.
122770 ** The zFilename argument is the filename pointer passed into the xOpen()
122771 ** method of a VFS implementation. The zParam argument is the name of the
122772 ** query parameter we seek. This routine returns the value of the zParam
122773 ** parameter if it exists. If the parameter does not exist, this routine
122774 ** returns a NULL pointer.
122776 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
122777 if( zFilename==0 ) return 0;
122778 zFilename += sqlite3Strlen30(zFilename) + 1;
122779 while( zFilename[0] ){
122780 int x = strcmp(zFilename, zParam);
122781 zFilename += sqlite3Strlen30(zFilename) + 1;
122782 if( x==0 ) return zFilename;
122783 zFilename += sqlite3Strlen30(zFilename) + 1;
122785 return 0;
122789 ** Return a boolean value for a query parameter.
122791 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
122792 const char *z = sqlite3_uri_parameter(zFilename, zParam);
122793 bDflt = bDflt!=0;
122794 return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
122798 ** Return a 64-bit integer value for a query parameter.
122800 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
122801 const char *zFilename, /* Filename as passed to xOpen */
122802 const char *zParam, /* URI parameter sought */
122803 sqlite3_int64 bDflt /* return if parameter is missing */
122805 const char *z = sqlite3_uri_parameter(zFilename, zParam);
122806 sqlite3_int64 v;
122807 if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
122808 bDflt = v;
122810 return bDflt;
122814 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
122816 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
122817 int i;
122818 for(i=0; i<db->nDb; i++){
122819 if( db->aDb[i].pBt
122820 && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
122822 return db->aDb[i].pBt;
122825 return 0;
122829 ** Return the filename of the database associated with a database
122830 ** connection.
122832 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
122833 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
122834 return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
122838 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
122839 ** no such database exists.
122841 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
122842 Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
122843 return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
122846 /************** End of main.c ************************************************/
122847 /************** Begin file notify.c ******************************************/
122849 ** 2009 March 3
122851 ** The author disclaims copyright to this source code. In place of
122852 ** a legal notice, here is a blessing:
122854 ** May you do good and not evil.
122855 ** May you find forgiveness for yourself and forgive others.
122856 ** May you share freely, never taking more than you give.
122858 *************************************************************************
122860 ** This file contains the implementation of the sqlite3_unlock_notify()
122861 ** API method and its associated functionality.
122864 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
122865 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
122868 ** Public interfaces:
122870 ** sqlite3ConnectionBlocked()
122871 ** sqlite3ConnectionUnlocked()
122872 ** sqlite3ConnectionClosed()
122873 ** sqlite3_unlock_notify()
122876 #define assertMutexHeld() \
122877 assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
122880 ** Head of a linked list of all sqlite3 objects created by this process
122881 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
122882 ** is not NULL. This variable may only accessed while the STATIC_MASTER
122883 ** mutex is held.
122885 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
122887 #ifndef NDEBUG
122889 ** This function is a complex assert() that verifies the following
122890 ** properties of the blocked connections list:
122892 ** 1) Each entry in the list has a non-NULL value for either
122893 ** pUnlockConnection or pBlockingConnection, or both.
122895 ** 2) All entries in the list that share a common value for
122896 ** xUnlockNotify are grouped together.
122898 ** 3) If the argument db is not NULL, then none of the entries in the
122899 ** blocked connections list have pUnlockConnection or pBlockingConnection
122900 ** set to db. This is used when closing connection db.
122902 static void checkListProperties(sqlite3 *db){
122903 sqlite3 *p;
122904 for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
122905 int seen = 0;
122906 sqlite3 *p2;
122908 /* Verify property (1) */
122909 assert( p->pUnlockConnection || p->pBlockingConnection );
122911 /* Verify property (2) */
122912 for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
122913 if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
122914 assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
122915 assert( db==0 || p->pUnlockConnection!=db );
122916 assert( db==0 || p->pBlockingConnection!=db );
122920 #else
122921 # define checkListProperties(x)
122922 #endif
122925 ** Remove connection db from the blocked connections list. If connection
122926 ** db is not currently a part of the list, this function is a no-op.
122928 static void removeFromBlockedList(sqlite3 *db){
122929 sqlite3 **pp;
122930 assertMutexHeld();
122931 for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
122932 if( *pp==db ){
122933 *pp = (*pp)->pNextBlocked;
122934 break;
122940 ** Add connection db to the blocked connections list. It is assumed
122941 ** that it is not already a part of the list.
122943 static void addToBlockedList(sqlite3 *db){
122944 sqlite3 **pp;
122945 assertMutexHeld();
122947 pp=&sqlite3BlockedList;
122948 *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
122949 pp=&(*pp)->pNextBlocked
122951 db->pNextBlocked = *pp;
122952 *pp = db;
122956 ** Obtain the STATIC_MASTER mutex.
122958 static void enterMutex(void){
122959 sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
122960 checkListProperties(0);
122964 ** Release the STATIC_MASTER mutex.
122966 static void leaveMutex(void){
122967 assertMutexHeld();
122968 checkListProperties(0);
122969 sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
122973 ** Register an unlock-notify callback.
122975 ** This is called after connection "db" has attempted some operation
122976 ** but has received an SQLITE_LOCKED error because another connection
122977 ** (call it pOther) in the same process was busy using the same shared
122978 ** cache. pOther is found by looking at db->pBlockingConnection.
122980 ** If there is no blocking connection, the callback is invoked immediately,
122981 ** before this routine returns.
122983 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
122984 ** a deadlock.
122986 ** Otherwise, make arrangements to invoke xNotify when pOther drops
122987 ** its locks.
122989 ** Each call to this routine overrides any prior callbacks registered
122990 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
122991 ** cancelled.
122993 SQLITE_API int sqlite3_unlock_notify(
122994 sqlite3 *db,
122995 void (*xNotify)(void **, int),
122996 void *pArg
122998 int rc = SQLITE_OK;
123000 sqlite3_mutex_enter(db->mutex);
123001 enterMutex();
123003 if( xNotify==0 ){
123004 removeFromBlockedList(db);
123005 db->pBlockingConnection = 0;
123006 db->pUnlockConnection = 0;
123007 db->xUnlockNotify = 0;
123008 db->pUnlockArg = 0;
123009 }else if( 0==db->pBlockingConnection ){
123010 /* The blocking transaction has been concluded. Or there never was a
123011 ** blocking transaction. In either case, invoke the notify callback
123012 ** immediately.
123014 xNotify(&pArg, 1);
123015 }else{
123016 sqlite3 *p;
123018 for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
123019 if( p ){
123020 rc = SQLITE_LOCKED; /* Deadlock detected. */
123021 }else{
123022 db->pUnlockConnection = db->pBlockingConnection;
123023 db->xUnlockNotify = xNotify;
123024 db->pUnlockArg = pArg;
123025 removeFromBlockedList(db);
123026 addToBlockedList(db);
123030 leaveMutex();
123031 assert( !db->mallocFailed );
123032 sqlite3Error(db, rc, (rc?"database is deadlocked":0));
123033 sqlite3_mutex_leave(db->mutex);
123034 return rc;
123038 ** This function is called while stepping or preparing a statement
123039 ** associated with connection db. The operation will return SQLITE_LOCKED
123040 ** to the user because it requires a lock that will not be available
123041 ** until connection pBlocker concludes its current transaction.
123043 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
123044 enterMutex();
123045 if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
123046 addToBlockedList(db);
123048 db->pBlockingConnection = pBlocker;
123049 leaveMutex();
123053 ** This function is called when
123054 ** the transaction opened by database db has just finished. Locks held
123055 ** by database connection db have been released.
123057 ** This function loops through each entry in the blocked connections
123058 ** list and does the following:
123060 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
123061 ** set to db, then set pBlockingConnection=0.
123063 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
123064 ** set to db, then invoke the configured unlock-notify callback and
123065 ** set pUnlockConnection=0.
123067 ** 3) If the two steps above mean that pBlockingConnection==0 and
123068 ** pUnlockConnection==0, remove the entry from the blocked connections
123069 ** list.
123071 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
123072 void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
123073 int nArg = 0; /* Number of entries in aArg[] */
123074 sqlite3 **pp; /* Iterator variable */
123075 void **aArg; /* Arguments to the unlock callback */
123076 void **aDyn = 0; /* Dynamically allocated space for aArg[] */
123077 void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
123079 aArg = aStatic;
123080 enterMutex(); /* Enter STATIC_MASTER mutex */
123082 /* This loop runs once for each entry in the blocked-connections list. */
123083 for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
123084 sqlite3 *p = *pp;
123086 /* Step 1. */
123087 if( p->pBlockingConnection==db ){
123088 p->pBlockingConnection = 0;
123091 /* Step 2. */
123092 if( p->pUnlockConnection==db ){
123093 assert( p->xUnlockNotify );
123094 if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
123095 xUnlockNotify(aArg, nArg);
123096 nArg = 0;
123099 sqlite3BeginBenignMalloc();
123100 assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
123101 assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
123102 if( (!aDyn && nArg==(int)ArraySize(aStatic))
123103 || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
123105 /* The aArg[] array needs to grow. */
123106 void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
123107 if( pNew ){
123108 memcpy(pNew, aArg, nArg*sizeof(void *));
123109 sqlite3_free(aDyn);
123110 aDyn = aArg = pNew;
123111 }else{
123112 /* This occurs when the array of context pointers that need to
123113 ** be passed to the unlock-notify callback is larger than the
123114 ** aStatic[] array allocated on the stack and the attempt to
123115 ** allocate a larger array from the heap has failed.
123117 ** This is a difficult situation to handle. Returning an error
123118 ** code to the caller is insufficient, as even if an error code
123119 ** is returned the transaction on connection db will still be
123120 ** closed and the unlock-notify callbacks on blocked connections
123121 ** will go unissued. This might cause the application to wait
123122 ** indefinitely for an unlock-notify callback that will never
123123 ** arrive.
123125 ** Instead, invoke the unlock-notify callback with the context
123126 ** array already accumulated. We can then clear the array and
123127 ** begin accumulating any further context pointers without
123128 ** requiring any dynamic allocation. This is sub-optimal because
123129 ** it means that instead of one callback with a large array of
123130 ** context pointers the application will receive two or more
123131 ** callbacks with smaller arrays of context pointers, which will
123132 ** reduce the applications ability to prioritize multiple
123133 ** connections. But it is the best that can be done under the
123134 ** circumstances.
123136 xUnlockNotify(aArg, nArg);
123137 nArg = 0;
123140 sqlite3EndBenignMalloc();
123142 aArg[nArg++] = p->pUnlockArg;
123143 xUnlockNotify = p->xUnlockNotify;
123144 p->pUnlockConnection = 0;
123145 p->xUnlockNotify = 0;
123146 p->pUnlockArg = 0;
123149 /* Step 3. */
123150 if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
123151 /* Remove connection p from the blocked connections list. */
123152 *pp = p->pNextBlocked;
123153 p->pNextBlocked = 0;
123154 }else{
123155 pp = &p->pNextBlocked;
123159 if( nArg!=0 ){
123160 xUnlockNotify(aArg, nArg);
123162 sqlite3_free(aDyn);
123163 leaveMutex(); /* Leave STATIC_MASTER mutex */
123167 ** This is called when the database connection passed as an argument is
123168 ** being closed. The connection is removed from the blocked list.
123170 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
123171 sqlite3ConnectionUnlocked(db);
123172 enterMutex();
123173 removeFromBlockedList(db);
123174 checkListProperties(db);
123175 leaveMutex();
123177 #endif
123179 /************** End of notify.c **********************************************/
123180 /************** Begin file fts3.c ********************************************/
123182 ** 2006 Oct 10
123184 ** The author disclaims copyright to this source code. In place of
123185 ** a legal notice, here is a blessing:
123187 ** May you do good and not evil.
123188 ** May you find forgiveness for yourself and forgive others.
123189 ** May you share freely, never taking more than you give.
123191 ******************************************************************************
123193 ** This is an SQLite module implementing full-text search.
123197 ** The code in this file is only compiled if:
123199 ** * The FTS3 module is being built as an extension
123200 ** (in which case SQLITE_CORE is not defined), or
123202 ** * The FTS3 module is being built into the core of
123203 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123206 /* The full-text index is stored in a series of b+tree (-like)
123207 ** structures called segments which map terms to doclists. The
123208 ** structures are like b+trees in layout, but are constructed from the
123209 ** bottom up in optimal fashion and are not updatable. Since trees
123210 ** are built from the bottom up, things will be described from the
123211 ** bottom up.
123214 **** Varints ****
123215 ** The basic unit of encoding is a variable-length integer called a
123216 ** varint. We encode variable-length integers in little-endian order
123217 ** using seven bits * per byte as follows:
123219 ** KEY:
123220 ** A = 0xxxxxxx 7 bits of data and one flag bit
123221 ** B = 1xxxxxxx 7 bits of data and one flag bit
123223 ** 7 bits - A
123224 ** 14 bits - BA
123225 ** 21 bits - BBA
123226 ** and so on.
123228 ** This is similar in concept to how sqlite encodes "varints" but
123229 ** the encoding is not the same. SQLite varints are big-endian
123230 ** are are limited to 9 bytes in length whereas FTS3 varints are
123231 ** little-endian and can be up to 10 bytes in length (in theory).
123233 ** Example encodings:
123235 ** 1: 0x01
123236 ** 127: 0x7f
123237 ** 128: 0x81 0x00
123240 **** Document lists ****
123241 ** A doclist (document list) holds a docid-sorted list of hits for a
123242 ** given term. Doclists hold docids and associated token positions.
123243 ** A docid is the unique integer identifier for a single document.
123244 ** A position is the index of a word within the document. The first
123245 ** word of the document has a position of 0.
123247 ** FTS3 used to optionally store character offsets using a compile-time
123248 ** option. But that functionality is no longer supported.
123250 ** A doclist is stored like this:
123252 ** array {
123253 ** varint docid; (delta from previous doclist)
123254 ** array { (position list for column 0)
123255 ** varint position; (2 more than the delta from previous position)
123257 ** array {
123258 ** varint POS_COLUMN; (marks start of position list for new column)
123259 ** varint column; (index of new column)
123260 ** array {
123261 ** varint position; (2 more than the delta from previous position)
123264 ** varint POS_END; (marks end of positions for this document.
123267 ** Here, array { X } means zero or more occurrences of X, adjacent in
123268 ** memory. A "position" is an index of a token in the token stream
123269 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
123270 ** in the same logical place as the position element, and act as sentinals
123271 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
123272 ** The positions numbers are not stored literally but rather as two more
123273 ** than the difference from the prior position, or the just the position plus
123274 ** 2 for the first position. Example:
123276 ** label: A B C D E F G H I J K
123277 ** value: 123 5 9 1 1 14 35 0 234 72 0
123279 ** The 123 value is the first docid. For column zero in this document
123280 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
123281 ** at D signals the start of a new column; the 1 at E indicates that the
123282 ** new column is column number 1. There are two positions at 12 and 45
123283 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
123284 ** 234 at I is the delta to next docid (357). It has one position 70
123285 ** (72-2) and then terminates with the 0 at K.
123287 ** A "position-list" is the list of positions for multiple columns for
123288 ** a single docid. A "column-list" is the set of positions for a single
123289 ** column. Hence, a position-list consists of one or more column-lists,
123290 ** a document record consists of a docid followed by a position-list and
123291 ** a doclist consists of one or more document records.
123293 ** A bare doclist omits the position information, becoming an
123294 ** array of varint-encoded docids.
123296 **** Segment leaf nodes ****
123297 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
123298 ** nodes are written using LeafWriter, and read using LeafReader (to
123299 ** iterate through a single leaf node's data) and LeavesReader (to
123300 ** iterate through a segment's entire leaf layer). Leaf nodes have
123301 ** the format:
123303 ** varint iHeight; (height from leaf level, always 0)
123304 ** varint nTerm; (length of first term)
123305 ** char pTerm[nTerm]; (content of first term)
123306 ** varint nDoclist; (length of term's associated doclist)
123307 ** char pDoclist[nDoclist]; (content of doclist)
123308 ** array {
123309 ** (further terms are delta-encoded)
123310 ** varint nPrefix; (length of prefix shared with previous term)
123311 ** varint nSuffix; (length of unshared suffix)
123312 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
123313 ** varint nDoclist; (length of term's associated doclist)
123314 ** char pDoclist[nDoclist]; (content of doclist)
123317 ** Here, array { X } means zero or more occurrences of X, adjacent in
123318 ** memory.
123320 ** Leaf nodes are broken into blocks which are stored contiguously in
123321 ** the %_segments table in sorted order. This means that when the end
123322 ** of a node is reached, the next term is in the node with the next
123323 ** greater node id.
123325 ** New data is spilled to a new leaf node when the current node
123326 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
123327 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
123328 ** node (a leaf node with a single term and doclist). The goal of
123329 ** these settings is to pack together groups of small doclists while
123330 ** making it efficient to directly access large doclists. The
123331 ** assumption is that large doclists represent terms which are more
123332 ** likely to be query targets.
123334 ** TODO(shess) It may be useful for blocking decisions to be more
123335 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
123336 ** node rather than splitting into 2k and .5k nodes. My intuition is
123337 ** that this might extend through 2x or 4x the pagesize.
123340 **** Segment interior nodes ****
123341 ** Segment interior nodes store blockids for subtree nodes and terms
123342 ** to describe what data is stored by the each subtree. Interior
123343 ** nodes are written using InteriorWriter, and read using
123344 ** InteriorReader. InteriorWriters are created as needed when
123345 ** SegmentWriter creates new leaf nodes, or when an interior node
123346 ** itself grows too big and must be split. The format of interior
123347 ** nodes:
123349 ** varint iHeight; (height from leaf level, always >0)
123350 ** varint iBlockid; (block id of node's leftmost subtree)
123351 ** optional {
123352 ** varint nTerm; (length of first term)
123353 ** char pTerm[nTerm]; (content of first term)
123354 ** array {
123355 ** (further terms are delta-encoded)
123356 ** varint nPrefix; (length of shared prefix with previous term)
123357 ** varint nSuffix; (length of unshared suffix)
123358 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
123362 ** Here, optional { X } means an optional element, while array { X }
123363 ** means zero or more occurrences of X, adjacent in memory.
123365 ** An interior node encodes n terms separating n+1 subtrees. The
123366 ** subtree blocks are contiguous, so only the first subtree's blockid
123367 ** is encoded. The subtree at iBlockid will contain all terms less
123368 ** than the first term encoded (or all terms if no term is encoded).
123369 ** Otherwise, for terms greater than or equal to pTerm[i] but less
123370 ** than pTerm[i+1], the subtree for that term will be rooted at
123371 ** iBlockid+i. Interior nodes only store enough term data to
123372 ** distinguish adjacent children (if the rightmost term of the left
123373 ** child is "something", and the leftmost term of the right child is
123374 ** "wicked", only "w" is stored).
123376 ** New data is spilled to a new interior node at the same height when
123377 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
123378 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
123379 ** interior nodes and making the tree too skinny. The interior nodes
123380 ** at a given height are naturally tracked by interior nodes at
123381 ** height+1, and so on.
123384 **** Segment directory ****
123385 ** The segment directory in table %_segdir stores meta-information for
123386 ** merging and deleting segments, and also the root node of the
123387 ** segment's tree.
123389 ** The root node is the top node of the segment's tree after encoding
123390 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
123391 ** This could be either a leaf node or an interior node. If the top
123392 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
123393 ** and a new root interior node is generated (which should always fit
123394 ** within ROOT_MAX because it only needs space for 2 varints, the
123395 ** height and the blockid of the previous root).
123397 ** The meta-information in the segment directory is:
123398 ** level - segment level (see below)
123399 ** idx - index within level
123400 ** - (level,idx uniquely identify a segment)
123401 ** start_block - first leaf node
123402 ** leaves_end_block - last leaf node
123403 ** end_block - last block (including interior nodes)
123404 ** root - contents of root node
123406 ** If the root node is a leaf node, then start_block,
123407 ** leaves_end_block, and end_block are all 0.
123410 **** Segment merging ****
123411 ** To amortize update costs, segments are grouped into levels and
123412 ** merged in batches. Each increase in level represents exponentially
123413 ** more documents.
123415 ** New documents (actually, document updates) are tokenized and
123416 ** written individually (using LeafWriter) to a level 0 segment, with
123417 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
123418 ** level 0 segments are merged into a single level 1 segment. Level 1
123419 ** is populated like level 0, and eventually MERGE_COUNT level 1
123420 ** segments are merged to a single level 2 segment (representing
123421 ** MERGE_COUNT^2 updates), and so on.
123423 ** A segment merge traverses all segments at a given level in
123424 ** parallel, performing a straightforward sorted merge. Since segment
123425 ** leaf nodes are written in to the %_segments table in order, this
123426 ** merge traverses the underlying sqlite disk structures efficiently.
123427 ** After the merge, all segment blocks from the merged level are
123428 ** deleted.
123430 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
123431 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
123432 ** very similar performance numbers to 16 on insertion, though they're
123433 ** a tiny bit slower (perhaps due to more overhead in merge-time
123434 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
123435 ** 16, 2 about 66% slower than 16.
123437 ** At query time, high MERGE_COUNT increases the number of segments
123438 ** which need to be scanned and merged. For instance, with 100k docs
123439 ** inserted:
123441 ** MERGE_COUNT segments
123442 ** 16 25
123443 ** 8 12
123444 ** 4 10
123445 ** 2 6
123447 ** This appears to have only a moderate impact on queries for very
123448 ** frequent terms (which are somewhat dominated by segment merge
123449 ** costs), and infrequent and non-existent terms still seem to be fast
123450 ** even with many segments.
123452 ** TODO(shess) That said, it would be nice to have a better query-side
123453 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
123454 ** optimizations to things like doclist merging will swing the sweet
123455 ** spot around.
123459 **** Handling of deletions and updates ****
123460 ** Since we're using a segmented structure, with no docid-oriented
123461 ** index into the term index, we clearly cannot simply update the term
123462 ** index when a document is deleted or updated. For deletions, we
123463 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
123464 ** we simply write the new doclist. Segment merges overwrite older
123465 ** data for a particular docid with newer data, so deletes or updates
123466 ** will eventually overtake the earlier data and knock it out. The
123467 ** query logic likewise merges doclists so that newer data knocks out
123468 ** older data.
123471 /************** Include fts3Int.h in the middle of fts3.c ********************/
123472 /************** Begin file fts3Int.h *****************************************/
123474 ** 2009 Nov 12
123476 ** The author disclaims copyright to this source code. In place of
123477 ** a legal notice, here is a blessing:
123479 ** May you do good and not evil.
123480 ** May you find forgiveness for yourself and forgive others.
123481 ** May you share freely, never taking more than you give.
123483 ******************************************************************************
123486 #ifndef _FTSINT_H
123487 #define _FTSINT_H
123489 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
123490 # define NDEBUG 1
123491 #endif
123494 ** FTS4 is really an extension for FTS3. It is enabled using the
123495 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
123496 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
123498 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
123499 # define SQLITE_ENABLE_FTS3
123500 #endif
123502 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123504 /* If not building as part of the core, include sqlite3ext.h. */
123505 #ifndef SQLITE_CORE
123506 SQLITE_EXTENSION_INIT3
123507 #endif
123509 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
123510 /************** Begin file fts3_tokenizer.h **********************************/
123512 ** 2006 July 10
123514 ** The author disclaims copyright to this source code.
123516 *************************************************************************
123517 ** Defines the interface to tokenizers used by fulltext-search. There
123518 ** are three basic components:
123520 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
123521 ** interface functions. This is essentially the class structure for
123522 ** tokenizers.
123524 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
123525 ** including customization information defined at creation time.
123527 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
123528 ** tokens from a particular input.
123530 #ifndef _FTS3_TOKENIZER_H_
123531 #define _FTS3_TOKENIZER_H_
123533 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
123534 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
123535 ** we will need a way to register the API consistently.
123539 ** Structures used by the tokenizer interface. When a new tokenizer
123540 ** implementation is registered, the caller provides a pointer to
123541 ** an sqlite3_tokenizer_module containing pointers to the callback
123542 ** functions that make up an implementation.
123544 ** When an fts3 table is created, it passes any arguments passed to
123545 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
123546 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
123547 ** implementation. The xCreate() function in turn returns an
123548 ** sqlite3_tokenizer structure representing the specific tokenizer to
123549 ** be used for the fts3 table (customized by the tokenizer clause arguments).
123551 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
123552 ** method is called. It returns an sqlite3_tokenizer_cursor object
123553 ** that may be used to tokenize a specific input buffer based on
123554 ** the tokenization rules supplied by a specific sqlite3_tokenizer
123555 ** object.
123557 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
123558 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
123559 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
123561 struct sqlite3_tokenizer_module {
123564 ** Structure version. Should always be set to 0 or 1.
123566 int iVersion;
123569 ** Create a new tokenizer. The values in the argv[] array are the
123570 ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
123571 ** TABLE statement that created the fts3 table. For example, if
123572 ** the following SQL is executed:
123574 ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
123576 ** then argc is set to 2, and the argv[] array contains pointers
123577 ** to the strings "arg1" and "arg2".
123579 ** This method should return either SQLITE_OK (0), or an SQLite error
123580 ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
123581 ** to point at the newly created tokenizer structure. The generic
123582 ** sqlite3_tokenizer.pModule variable should not be initialized by
123583 ** this callback. The caller will do so.
123585 int (*xCreate)(
123586 int argc, /* Size of argv array */
123587 const char *const*argv, /* Tokenizer argument strings */
123588 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
123592 ** Destroy an existing tokenizer. The fts3 module calls this method
123593 ** exactly once for each successful call to xCreate().
123595 int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
123598 ** Create a tokenizer cursor to tokenize an input buffer. The caller
123599 ** is responsible for ensuring that the input buffer remains valid
123600 ** until the cursor is closed (using the xClose() method).
123602 int (*xOpen)(
123603 sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
123604 const char *pInput, int nBytes, /* Input buffer */
123605 sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
123609 ** Destroy an existing tokenizer cursor. The fts3 module calls this
123610 ** method exactly once for each successful call to xOpen().
123612 int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
123615 ** Retrieve the next token from the tokenizer cursor pCursor. This
123616 ** method should either return SQLITE_OK and set the values of the
123617 ** "OUT" variables identified below, or SQLITE_DONE to indicate that
123618 ** the end of the buffer has been reached, or an SQLite error code.
123620 ** *ppToken should be set to point at a buffer containing the
123621 ** normalized version of the token (i.e. after any case-folding and/or
123622 ** stemming has been performed). *pnBytes should be set to the length
123623 ** of this buffer in bytes. The input text that generated the token is
123624 ** identified by the byte offsets returned in *piStartOffset and
123625 ** *piEndOffset. *piStartOffset should be set to the index of the first
123626 ** byte of the token in the input buffer. *piEndOffset should be set
123627 ** to the index of the first byte just past the end of the token in
123628 ** the input buffer.
123630 ** The buffer *ppToken is set to point at is managed by the tokenizer
123631 ** implementation. It is only required to be valid until the next call
123632 ** to xNext() or xClose().
123634 /* TODO(shess) current implementation requires pInput to be
123635 ** nul-terminated. This should either be fixed, or pInput/nBytes
123636 ** should be converted to zInput.
123638 int (*xNext)(
123639 sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
123640 const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
123641 int *piStartOffset, /* OUT: Byte offset of token in input buffer */
123642 int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
123643 int *piPosition /* OUT: Number of tokens returned before this one */
123646 /***********************************************************************
123647 ** Methods below this point are only available if iVersion>=1.
123651 ** Configure the language id of a tokenizer cursor.
123653 int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
123656 struct sqlite3_tokenizer {
123657 const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
123658 /* Tokenizer implementations will typically add additional fields */
123661 struct sqlite3_tokenizer_cursor {
123662 sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
123663 /* Tokenizer implementations will typically add additional fields */
123666 int fts3_global_term_cnt(int iTerm, int iCol);
123667 int fts3_term_cnt(int iTerm, int iCol);
123670 #endif /* _FTS3_TOKENIZER_H_ */
123672 /************** End of fts3_tokenizer.h **************************************/
123673 /************** Continuing where we left off in fts3Int.h ********************/
123674 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
123675 /************** Begin file fts3_hash.h ***************************************/
123677 ** 2001 September 22
123679 ** The author disclaims copyright to this source code. In place of
123680 ** a legal notice, here is a blessing:
123682 ** May you do good and not evil.
123683 ** May you find forgiveness for yourself and forgive others.
123684 ** May you share freely, never taking more than you give.
123686 *************************************************************************
123687 ** This is the header file for the generic hash-table implementation
123688 ** used in SQLite. We've modified it slightly to serve as a standalone
123689 ** hash table implementation for the full-text indexing module.
123692 #ifndef _FTS3_HASH_H_
123693 #define _FTS3_HASH_H_
123695 /* Forward declarations of structures. */
123696 typedef struct Fts3Hash Fts3Hash;
123697 typedef struct Fts3HashElem Fts3HashElem;
123699 /* A complete hash table is an instance of the following structure.
123700 ** The internals of this structure are intended to be opaque -- client
123701 ** code should not attempt to access or modify the fields of this structure
123702 ** directly. Change this structure only by using the routines below.
123703 ** However, many of the "procedures" and "functions" for modifying and
123704 ** accessing this structure are really macros, so we can't really make
123705 ** this structure opaque.
123707 struct Fts3Hash {
123708 char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
123709 char copyKey; /* True if copy of key made on insert */
123710 int count; /* Number of entries in this table */
123711 Fts3HashElem *first; /* The first element of the array */
123712 int htsize; /* Number of buckets in the hash table */
123713 struct _fts3ht { /* the hash table */
123714 int count; /* Number of entries with this hash */
123715 Fts3HashElem *chain; /* Pointer to first entry with this hash */
123716 } *ht;
123719 /* Each element in the hash table is an instance of the following
123720 ** structure. All elements are stored on a single doubly-linked list.
123722 ** Again, this structure is intended to be opaque, but it can't really
123723 ** be opaque because it is used by macros.
123725 struct Fts3HashElem {
123726 Fts3HashElem *next, *prev; /* Next and previous elements in the table */
123727 void *data; /* Data associated with this element */
123728 void *pKey; int nKey; /* Key associated with this element */
123732 ** There are 2 different modes of operation for a hash table:
123734 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
123735 ** (including the null-terminator, if any). Case
123736 ** is respected in comparisons.
123738 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
123739 ** memcmp() is used to compare keys.
123741 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
123743 #define FTS3_HASH_STRING 1
123744 #define FTS3_HASH_BINARY 2
123747 ** Access routines. To delete, insert a NULL pointer.
123749 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
123750 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
123751 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
123752 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
123753 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
123756 ** Shorthand for the functions above
123758 #define fts3HashInit sqlite3Fts3HashInit
123759 #define fts3HashInsert sqlite3Fts3HashInsert
123760 #define fts3HashFind sqlite3Fts3HashFind
123761 #define fts3HashClear sqlite3Fts3HashClear
123762 #define fts3HashFindElem sqlite3Fts3HashFindElem
123765 ** Macros for looping over all elements of a hash table. The idiom is
123766 ** like this:
123768 ** Fts3Hash h;
123769 ** Fts3HashElem *p;
123770 ** ...
123771 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
123772 ** SomeStructure *pData = fts3HashData(p);
123773 ** // do something with pData
123776 #define fts3HashFirst(H) ((H)->first)
123777 #define fts3HashNext(E) ((E)->next)
123778 #define fts3HashData(E) ((E)->data)
123779 #define fts3HashKey(E) ((E)->pKey)
123780 #define fts3HashKeysize(E) ((E)->nKey)
123783 ** Number of entries in a hash table
123785 #define fts3HashCount(H) ((H)->count)
123787 #endif /* _FTS3_HASH_H_ */
123789 /************** End of fts3_hash.h *******************************************/
123790 /************** Continuing where we left off in fts3Int.h ********************/
123793 ** This constant determines the maximum depth of an FTS expression tree
123794 ** that the library will create and use. FTS uses recursion to perform
123795 ** various operations on the query tree, so the disadvantage of a large
123796 ** limit is that it may allow very large queries to use large amounts
123797 ** of stack space (perhaps causing a stack overflow).
123799 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
123800 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
123801 #endif
123805 ** This constant controls how often segments are merged. Once there are
123806 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
123807 ** segment of level N+1.
123809 #define FTS3_MERGE_COUNT 16
123812 ** This is the maximum amount of data (in bytes) to store in the
123813 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
123814 ** populated as documents are inserted/updated/deleted in a transaction
123815 ** and used to create a new segment when the transaction is committed.
123816 ** However if this limit is reached midway through a transaction, a new
123817 ** segment is created and the hash table cleared immediately.
123819 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
123822 ** Macro to return the number of elements in an array. SQLite has a
123823 ** similar macro called ArraySize(). Use a different name to avoid
123824 ** a collision when building an amalgamation with built-in FTS3.
123826 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
123829 #ifndef MIN
123830 # define MIN(x,y) ((x)<(y)?(x):(y))
123831 #endif
123832 #ifndef MAX
123833 # define MAX(x,y) ((x)>(y)?(x):(y))
123834 #endif
123837 ** Maximum length of a varint encoded integer. The varint format is different
123838 ** from that used by SQLite, so the maximum length is 10, not 9.
123840 #define FTS3_VARINT_MAX 10
123843 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
123844 ** in the document set and zero or more prefix indexes. All indexes are stored
123845 ** as one or more b+-trees in the %_segments and %_segdir tables.
123847 ** It is possible to determine which index a b+-tree belongs to based on the
123848 ** value stored in the "%_segdir.level" column. Given this value L, the index
123849 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
123850 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
123851 ** between 1024 and 2047 to index 1, and so on.
123853 ** It is considered impossible for an index to use more than 1024 levels. In
123854 ** theory though this may happen, but only after at least
123855 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
123857 #define FTS3_SEGDIR_MAXLEVEL 1024
123858 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
123861 ** The testcase() macro is only used by the amalgamation. If undefined,
123862 ** make it a no-op.
123864 #ifndef testcase
123865 # define testcase(X)
123866 #endif
123869 ** Terminator values for position-lists and column-lists.
123871 #define POS_COLUMN (1) /* Column-list terminator */
123872 #define POS_END (0) /* Position-list terminator */
123875 ** This section provides definitions to allow the
123876 ** FTS3 extension to be compiled outside of the
123877 ** amalgamation.
123879 #ifndef SQLITE_AMALGAMATION
123881 ** Macros indicating that conditional expressions are always true or
123882 ** false.
123884 #ifdef SQLITE_COVERAGE_TEST
123885 # define ALWAYS(x) (1)
123886 # define NEVER(X) (0)
123887 #else
123888 # define ALWAYS(x) (x)
123889 # define NEVER(x) (x)
123890 #endif
123893 ** Internal types used by SQLite.
123895 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
123896 typedef short int i16; /* 2-byte (or larger) signed integer */
123897 typedef unsigned int u32; /* 4-byte unsigned integer */
123898 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
123899 typedef sqlite3_int64 i64; /* 8-byte signed integer */
123902 ** Macro used to suppress compiler warnings for unused parameters.
123904 #define UNUSED_PARAMETER(x) (void)(x)
123907 ** Activate assert() only if SQLITE_TEST is enabled.
123909 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
123910 # define NDEBUG 1
123911 #endif
123914 ** The TESTONLY macro is used to enclose variable declarations or
123915 ** other bits of code that are needed to support the arguments
123916 ** within testcase() and assert() macros.
123918 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
123919 # define TESTONLY(X) X
123920 #else
123921 # define TESTONLY(X)
123922 #endif
123924 #endif /* SQLITE_AMALGAMATION */
123926 #ifdef SQLITE_DEBUG
123927 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
123928 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
123929 #else
123930 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
123931 #endif
123933 typedef struct Fts3Table Fts3Table;
123934 typedef struct Fts3Cursor Fts3Cursor;
123935 typedef struct Fts3Expr Fts3Expr;
123936 typedef struct Fts3Phrase Fts3Phrase;
123937 typedef struct Fts3PhraseToken Fts3PhraseToken;
123939 typedef struct Fts3Doclist Fts3Doclist;
123940 typedef struct Fts3SegFilter Fts3SegFilter;
123941 typedef struct Fts3DeferredToken Fts3DeferredToken;
123942 typedef struct Fts3SegReader Fts3SegReader;
123943 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
123946 ** A connection to a fulltext index is an instance of the following
123947 ** structure. The xCreate and xConnect methods create an instance
123948 ** of this structure and xDestroy and xDisconnect free that instance.
123949 ** All other methods receive a pointer to the structure as one of their
123950 ** arguments.
123952 struct Fts3Table {
123953 sqlite3_vtab base; /* Base class used by SQLite core */
123954 sqlite3 *db; /* The database connection */
123955 const char *zDb; /* logical database name */
123956 const char *zName; /* virtual table name */
123957 int nColumn; /* number of named columns in virtual table */
123958 char **azColumn; /* column names. malloced */
123959 u8 *abNotindexed; /* True for 'notindexed' columns */
123960 sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
123961 char *zContentTbl; /* content=xxx option, or NULL */
123962 char *zLanguageid; /* languageid=xxx option, or NULL */
123963 u8 bAutoincrmerge; /* True if automerge=1 */
123964 u32 nLeafAdd; /* Number of leaf blocks added this trans */
123966 /* Precompiled statements used by the implementation. Each of these
123967 ** statements is run and reset within a single virtual table API call.
123969 sqlite3_stmt *aStmt[37];
123971 char *zReadExprlist;
123972 char *zWriteExprlist;
123974 int nNodeSize; /* Soft limit for node size */
123975 u8 bFts4; /* True for FTS4, false for FTS3 */
123976 u8 bHasStat; /* True if %_stat table exists */
123977 u8 bHasDocsize; /* True if %_docsize table exists */
123978 u8 bDescIdx; /* True if doclists are in reverse order */
123979 u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
123980 int nPgsz; /* Page size for host database */
123981 char *zSegmentsTbl; /* Name of %_segments table */
123982 sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
123985 ** The following array of hash tables is used to buffer pending index
123986 ** updates during transactions. All pending updates buffered at any one
123987 ** time must share a common language-id (see the FTS4 langid= feature).
123988 ** The current language id is stored in variable iPrevLangid.
123990 ** A single FTS4 table may have multiple full-text indexes. For each index
123991 ** there is an entry in the aIndex[] array. Index 0 is an index of all the
123992 ** terms that appear in the document set. Each subsequent index in aIndex[]
123993 ** is an index of prefixes of a specific length.
123995 ** Variable nPendingData contains an estimate the memory consumed by the
123996 ** pending data structures, including hash table overhead, but not including
123997 ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
123998 ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
123999 ** recently inserted record.
124001 int nIndex; /* Size of aIndex[] */
124002 struct Fts3Index {
124003 int nPrefix; /* Prefix length (0 for main terms index) */
124004 Fts3Hash hPending; /* Pending terms table for this index */
124005 } *aIndex;
124006 int nMaxPendingData; /* Max pending data before flush to disk */
124007 int nPendingData; /* Current bytes of pending data */
124008 sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
124009 int iPrevLangid; /* Langid of recently inserted document */
124011 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
124012 /* State variables used for validating that the transaction control
124013 ** methods of the virtual table are called at appropriate times. These
124014 ** values do not contribute to FTS functionality; they are used for
124015 ** verifying the operation of the SQLite core.
124017 int inTransaction; /* True after xBegin but before xCommit/xRollback */
124018 int mxSavepoint; /* Largest valid xSavepoint integer */
124019 #endif
124021 #ifdef SQLITE_TEST
124022 /* True to disable the incremental doclist optimization. This is controled
124023 ** by special insert command 'test-no-incr-doclist'. */
124024 int bNoIncrDoclist;
124025 #endif
124029 ** When the core wants to read from the virtual table, it creates a
124030 ** virtual table cursor (an instance of the following structure) using
124031 ** the xOpen method. Cursors are destroyed using the xClose method.
124033 struct Fts3Cursor {
124034 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
124035 i16 eSearch; /* Search strategy (see below) */
124036 u8 isEof; /* True if at End Of Results */
124037 u8 isRequireSeek; /* True if must seek pStmt to %_content row */
124038 sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
124039 Fts3Expr *pExpr; /* Parsed MATCH query string */
124040 int iLangid; /* Language being queried for */
124041 int nPhrase; /* Number of matchable phrases in query */
124042 Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
124043 sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
124044 char *pNextId; /* Pointer into the body of aDoclist */
124045 char *aDoclist; /* List of docids for full-text queries */
124046 int nDoclist; /* Size of buffer at aDoclist */
124047 u8 bDesc; /* True to sort in descending order */
124048 int eEvalmode; /* An FTS3_EVAL_XX constant */
124049 int nRowAvg; /* Average size of database rows, in pages */
124050 sqlite3_int64 nDoc; /* Documents in table */
124051 i64 iMinDocid; /* Minimum docid to return */
124052 i64 iMaxDocid; /* Maximum docid to return */
124053 int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
124054 u32 *aMatchinfo; /* Information about most recent match */
124055 int nMatchinfo; /* Number of elements in aMatchinfo[] */
124056 char *zMatchinfo; /* Matchinfo specification */
124059 #define FTS3_EVAL_FILTER 0
124060 #define FTS3_EVAL_NEXT 1
124061 #define FTS3_EVAL_MATCHINFO 2
124064 ** The Fts3Cursor.eSearch member is always set to one of the following.
124065 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
124066 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
124067 ** of the column to be searched. For example, in
124069 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
124070 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
124072 ** Because the LHS of the MATCH operator is 2nd column "b",
124073 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
124074 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
124075 ** indicating that all columns should be searched,
124076 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
124078 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
124079 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
124080 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
124083 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
124084 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
124085 ** above. The upper 16-bits contain a combination of the following
124086 ** bits, used to describe extra constraints on full-text searches.
124088 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
124089 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
124090 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
124092 struct Fts3Doclist {
124093 char *aAll; /* Array containing doclist (or NULL) */
124094 int nAll; /* Size of a[] in bytes */
124095 char *pNextDocid; /* Pointer to next docid */
124097 sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
124098 int bFreeList; /* True if pList should be sqlite3_free()d */
124099 char *pList; /* Pointer to position list following iDocid */
124100 int nList; /* Length of position list */
124104 ** A "phrase" is a sequence of one or more tokens that must match in
124105 ** sequence. A single token is the base case and the most common case.
124106 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
124107 ** nToken will be the number of tokens in the string.
124109 struct Fts3PhraseToken {
124110 char *z; /* Text of the token */
124111 int n; /* Number of bytes in buffer z */
124112 int isPrefix; /* True if token ends with a "*" character */
124113 int bFirst; /* True if token must appear at position 0 */
124115 /* Variables above this point are populated when the expression is
124116 ** parsed (by code in fts3_expr.c). Below this point the variables are
124117 ** used when evaluating the expression. */
124118 Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
124119 Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
124122 struct Fts3Phrase {
124123 /* Cache of doclist for this phrase. */
124124 Fts3Doclist doclist;
124125 int bIncr; /* True if doclist is loaded incrementally */
124126 int iDoclistToken;
124128 /* Variables below this point are populated by fts3_expr.c when parsing
124129 ** a MATCH expression. Everything above is part of the evaluation phase.
124131 int nToken; /* Number of tokens in the phrase */
124132 int iColumn; /* Index of column this phrase must match */
124133 Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
124137 ** A tree of these objects forms the RHS of a MATCH operator.
124139 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
124140 ** points to a malloced buffer, size nDoclist bytes, containing the results
124141 ** of this phrase query in FTS3 doclist format. As usual, the initial
124142 ** "Length" field found in doclists stored on disk is omitted from this
124143 ** buffer.
124145 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
124146 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
124147 ** where nCol is the number of columns in the queried FTS table. The array
124148 ** is populated as follows:
124150 ** aMI[iCol*3 + 0] = Undefined
124151 ** aMI[iCol*3 + 1] = Number of occurrences
124152 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
124154 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
124155 ** when the expression node is.
124157 struct Fts3Expr {
124158 int eType; /* One of the FTSQUERY_XXX values defined below */
124159 int nNear; /* Valid if eType==FTSQUERY_NEAR */
124160 Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
124161 Fts3Expr *pLeft; /* Left operand */
124162 Fts3Expr *pRight; /* Right operand */
124163 Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
124165 /* The following are used by the fts3_eval.c module. */
124166 sqlite3_int64 iDocid; /* Current docid */
124167 u8 bEof; /* True this expression is at EOF already */
124168 u8 bStart; /* True if iDocid is valid */
124169 u8 bDeferred; /* True if this expression is entirely deferred */
124171 u32 *aMI;
124175 ** Candidate values for Fts3Query.eType. Note that the order of the first
124176 ** four values is in order of precedence when parsing expressions. For
124177 ** example, the following:
124179 ** "a OR b AND c NOT d NEAR e"
124181 ** is equivalent to:
124183 ** "a OR (b AND (c NOT (d NEAR e)))"
124185 #define FTSQUERY_NEAR 1
124186 #define FTSQUERY_NOT 2
124187 #define FTSQUERY_AND 3
124188 #define FTSQUERY_OR 4
124189 #define FTSQUERY_PHRASE 5
124192 /* fts3_write.c */
124193 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
124194 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
124195 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
124196 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
124197 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
124198 sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
124199 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
124200 Fts3Table*,int,const char*,int,int,Fts3SegReader**);
124201 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
124202 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
124203 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
124205 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
124206 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
124208 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
124209 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
124210 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
124211 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
124212 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
124213 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
124214 #else
124215 # define sqlite3Fts3FreeDeferredTokens(x)
124216 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
124217 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
124218 # define sqlite3Fts3FreeDeferredDoclists(x)
124219 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
124220 #endif
124222 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
124223 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
124225 /* Special values interpreted by sqlite3SegReaderCursor() */
124226 #define FTS3_SEGCURSOR_PENDING -1
124227 #define FTS3_SEGCURSOR_ALL -2
124229 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
124230 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
124231 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
124233 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
124234 int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
124236 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
124237 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
124238 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
124239 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
124240 #define FTS3_SEGMENT_PREFIX 0x00000008
124241 #define FTS3_SEGMENT_SCAN 0x00000010
124242 #define FTS3_SEGMENT_FIRST 0x00000020
124244 /* Type passed as 4th argument to SegmentReaderIterate() */
124245 struct Fts3SegFilter {
124246 const char *zTerm;
124247 int nTerm;
124248 int iCol;
124249 int flags;
124252 struct Fts3MultiSegReader {
124253 /* Used internally by sqlite3Fts3SegReaderXXX() calls */
124254 Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
124255 int nSegment; /* Size of apSegment array */
124256 int nAdvance; /* How many seg-readers to advance */
124257 Fts3SegFilter *pFilter; /* Pointer to filter object */
124258 char *aBuffer; /* Buffer to merge doclists in */
124259 int nBuffer; /* Allocated size of aBuffer[] in bytes */
124261 int iColFilter; /* If >=0, filter for this column */
124262 int bRestart;
124264 /* Used by fts3.c only. */
124265 int nCost; /* Cost of running iterator */
124266 int bLookup; /* True if a lookup of a single entry. */
124268 /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
124269 char *zTerm; /* Pointer to term buffer */
124270 int nTerm; /* Size of zTerm in bytes */
124271 char *aDoclist; /* Pointer to doclist buffer */
124272 int nDoclist; /* Size of aDoclist[] in bytes */
124275 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
124277 #define fts3GetVarint32(p, piVal) ( \
124278 (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
124281 /* fts3.c */
124282 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
124283 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
124284 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
124285 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
124286 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
124287 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
124288 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
124289 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
124290 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
124292 /* fts3_tokenizer.c */
124293 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
124294 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
124295 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
124296 sqlite3_tokenizer **, char **
124298 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
124300 /* fts3_snippet.c */
124301 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
124302 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
124303 const char *, const char *, int, int
124305 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
124307 /* fts3_expr.c */
124308 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
124309 char **, int, int, int, const char *, int, Fts3Expr **, char **
124311 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
124312 #ifdef SQLITE_TEST
124313 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
124314 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
124315 #endif
124317 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
124318 sqlite3_tokenizer_cursor **
124321 /* fts3_aux.c */
124322 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
124324 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
124326 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
124327 Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
124328 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
124329 Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
124330 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
124331 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
124332 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
124334 /* fts3_tokenize_vtab.c */
124335 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
124337 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
124338 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
124339 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
124340 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
124341 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
124342 #endif
124344 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
124345 #endif /* _FTSINT_H */
124347 /************** End of fts3Int.h *********************************************/
124348 /************** Continuing where we left off in fts3.c ***********************/
124349 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124351 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
124352 # define SQLITE_CORE 1
124353 #endif
124355 /* #include <assert.h> */
124356 /* #include <stdlib.h> */
124357 /* #include <stddef.h> */
124358 /* #include <stdio.h> */
124359 /* #include <string.h> */
124360 /* #include <stdarg.h> */
124362 #ifndef SQLITE_CORE
124363 SQLITE_EXTENSION_INIT1
124364 #endif
124366 static int fts3EvalNext(Fts3Cursor *pCsr);
124367 static int fts3EvalStart(Fts3Cursor *pCsr);
124368 static int fts3TermSegReaderCursor(
124369 Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
124372 ** Write a 64-bit variable-length integer to memory starting at p[0].
124373 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
124374 ** The number of bytes written is returned.
124376 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
124377 unsigned char *q = (unsigned char *) p;
124378 sqlite_uint64 vu = v;
124380 *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
124381 vu >>= 7;
124382 }while( vu!=0 );
124383 q[-1] &= 0x7f; /* turn off high bit in final byte */
124384 assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
124385 return (int) (q - (unsigned char *)p);
124388 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
124389 v = (v & mask1) | ( (*ptr++) << shift ); \
124390 if( (v & mask2)==0 ){ var = v; return ret; }
124391 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
124392 v = (*ptr++); \
124393 if( (v & mask2)==0 ){ var = v; return ret; }
124396 ** Read a 64-bit variable-length integer from memory starting at p[0].
124397 ** Return the number of bytes read, or 0 on error.
124398 ** The value is stored in *v.
124400 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
124401 const char *pStart = p;
124402 u32 a;
124403 u64 b;
124404 int shift;
124406 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
124407 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
124408 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
124409 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
124410 b = (a & 0x0FFFFFFF );
124412 for(shift=28; shift<=63; shift+=7){
124413 u64 c = *p++;
124414 b += (c&0x7F) << shift;
124415 if( (c & 0x80)==0 ) break;
124417 *v = b;
124418 return (int)(p - pStart);
124422 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
124423 ** 32-bit integer before it is returned.
124425 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
124426 u32 a;
124428 #ifndef fts3GetVarint32
124429 GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
124430 #else
124431 a = (*p++);
124432 assert( a & 0x80 );
124433 #endif
124435 GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
124436 GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
124437 GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
124438 a = (a & 0x0FFFFFFF );
124439 *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
124440 return 5;
124444 ** Return the number of bytes required to encode v as a varint
124446 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
124447 int i = 0;
124450 v >>= 7;
124451 }while( v!=0 );
124452 return i;
124456 ** Convert an SQL-style quoted string into a normal string by removing
124457 ** the quote characters. The conversion is done in-place. If the
124458 ** input does not begin with a quote character, then this routine
124459 ** is a no-op.
124461 ** Examples:
124463 ** "abc" becomes abc
124464 ** 'xyz' becomes xyz
124465 ** [pqr] becomes pqr
124466 ** `mno` becomes mno
124469 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
124470 char quote; /* Quote character (if any ) */
124472 quote = z[0];
124473 if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
124474 int iIn = 1; /* Index of next byte to read from input */
124475 int iOut = 0; /* Index of next byte to write to output */
124477 /* If the first byte was a '[', then the close-quote character is a ']' */
124478 if( quote=='[' ) quote = ']';
124480 while( ALWAYS(z[iIn]) ){
124481 if( z[iIn]==quote ){
124482 if( z[iIn+1]!=quote ) break;
124483 z[iOut++] = quote;
124484 iIn += 2;
124485 }else{
124486 z[iOut++] = z[iIn++];
124489 z[iOut] = '\0';
124494 ** Read a single varint from the doclist at *pp and advance *pp to point
124495 ** to the first byte past the end of the varint. Add the value of the varint
124496 ** to *pVal.
124498 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
124499 sqlite3_int64 iVal;
124500 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
124501 *pVal += iVal;
124505 ** When this function is called, *pp points to the first byte following a
124506 ** varint that is part of a doclist (or position-list, or any other list
124507 ** of varints). This function moves *pp to point to the start of that varint,
124508 ** and sets *pVal by the varint value.
124510 ** Argument pStart points to the first byte of the doclist that the
124511 ** varint is part of.
124513 static void fts3GetReverseVarint(
124514 char **pp,
124515 char *pStart,
124516 sqlite3_int64 *pVal
124518 sqlite3_int64 iVal;
124519 char *p;
124521 /* Pointer p now points at the first byte past the varint we are
124522 ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
124523 ** clear on character p[-1]. */
124524 for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
124526 *pp = p;
124528 sqlite3Fts3GetVarint(p, &iVal);
124529 *pVal = iVal;
124533 ** The xDisconnect() virtual table method.
124535 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
124536 Fts3Table *p = (Fts3Table *)pVtab;
124537 int i;
124539 assert( p->nPendingData==0 );
124540 assert( p->pSegments==0 );
124542 /* Free any prepared statements held */
124543 for(i=0; i<SizeofArray(p->aStmt); i++){
124544 sqlite3_finalize(p->aStmt[i]);
124546 sqlite3_free(p->zSegmentsTbl);
124547 sqlite3_free(p->zReadExprlist);
124548 sqlite3_free(p->zWriteExprlist);
124549 sqlite3_free(p->zContentTbl);
124550 sqlite3_free(p->zLanguageid);
124552 /* Invoke the tokenizer destructor to free the tokenizer. */
124553 p->pTokenizer->pModule->xDestroy(p->pTokenizer);
124555 sqlite3_free(p);
124556 return SQLITE_OK;
124560 ** Construct one or more SQL statements from the format string given
124561 ** and then evaluate those statements. The success code is written
124562 ** into *pRc.
124564 ** If *pRc is initially non-zero then this routine is a no-op.
124566 static void fts3DbExec(
124567 int *pRc, /* Success code */
124568 sqlite3 *db, /* Database in which to run SQL */
124569 const char *zFormat, /* Format string for SQL */
124570 ... /* Arguments to the format string */
124572 va_list ap;
124573 char *zSql;
124574 if( *pRc ) return;
124575 va_start(ap, zFormat);
124576 zSql = sqlite3_vmprintf(zFormat, ap);
124577 va_end(ap);
124578 if( zSql==0 ){
124579 *pRc = SQLITE_NOMEM;
124580 }else{
124581 *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
124582 sqlite3_free(zSql);
124587 ** The xDestroy() virtual table method.
124589 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
124590 Fts3Table *p = (Fts3Table *)pVtab;
124591 int rc = SQLITE_OK; /* Return code */
124592 const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
124593 sqlite3 *db = p->db; /* Database handle */
124595 /* Drop the shadow tables */
124596 if( p->zContentTbl==0 ){
124597 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
124599 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
124600 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
124601 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
124602 fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
124604 /* If everything has worked, invoke fts3DisconnectMethod() to free the
124605 ** memory associated with the Fts3Table structure and return SQLITE_OK.
124606 ** Otherwise, return an SQLite error code.
124608 return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
124613 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
124614 ** passed as the first argument. This is done as part of the xConnect()
124615 ** and xCreate() methods.
124617 ** If *pRc is non-zero when this function is called, it is a no-op.
124618 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
124619 ** before returning.
124621 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
124622 if( *pRc==SQLITE_OK ){
124623 int i; /* Iterator variable */
124624 int rc; /* Return code */
124625 char *zSql; /* SQL statement passed to declare_vtab() */
124626 char *zCols; /* List of user defined columns */
124627 const char *zLanguageid;
124629 zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
124630 sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
124632 /* Create a list of user columns for the virtual table */
124633 zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
124634 for(i=1; zCols && i<p->nColumn; i++){
124635 zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
124638 /* Create the whole "CREATE TABLE" statement to pass to SQLite */
124639 zSql = sqlite3_mprintf(
124640 "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
124641 zCols, p->zName, zLanguageid
124643 if( !zCols || !zSql ){
124644 rc = SQLITE_NOMEM;
124645 }else{
124646 rc = sqlite3_declare_vtab(p->db, zSql);
124649 sqlite3_free(zSql);
124650 sqlite3_free(zCols);
124651 *pRc = rc;
124656 ** Create the %_stat table if it does not already exist.
124658 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
124659 fts3DbExec(pRc, p->db,
124660 "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
124661 "(id INTEGER PRIMARY KEY, value BLOB);",
124662 p->zDb, p->zName
124664 if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
124668 ** Create the backing store tables (%_content, %_segments and %_segdir)
124669 ** required by the FTS3 table passed as the only argument. This is done
124670 ** as part of the vtab xCreate() method.
124672 ** If the p->bHasDocsize boolean is true (indicating that this is an
124673 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
124674 ** %_stat tables required by FTS4.
124676 static int fts3CreateTables(Fts3Table *p){
124677 int rc = SQLITE_OK; /* Return code */
124678 int i; /* Iterator variable */
124679 sqlite3 *db = p->db; /* The database connection */
124681 if( p->zContentTbl==0 ){
124682 const char *zLanguageid = p->zLanguageid;
124683 char *zContentCols; /* Columns of %_content table */
124685 /* Create a list of user columns for the content table */
124686 zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
124687 for(i=0; zContentCols && i<p->nColumn; i++){
124688 char *z = p->azColumn[i];
124689 zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
124691 if( zLanguageid && zContentCols ){
124692 zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
124694 if( zContentCols==0 ) rc = SQLITE_NOMEM;
124696 /* Create the content table */
124697 fts3DbExec(&rc, db,
124698 "CREATE TABLE %Q.'%q_content'(%s)",
124699 p->zDb, p->zName, zContentCols
124701 sqlite3_free(zContentCols);
124704 /* Create other tables */
124705 fts3DbExec(&rc, db,
124706 "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
124707 p->zDb, p->zName
124709 fts3DbExec(&rc, db,
124710 "CREATE TABLE %Q.'%q_segdir'("
124711 "level INTEGER,"
124712 "idx INTEGER,"
124713 "start_block INTEGER,"
124714 "leaves_end_block INTEGER,"
124715 "end_block INTEGER,"
124716 "root BLOB,"
124717 "PRIMARY KEY(level, idx)"
124718 ");",
124719 p->zDb, p->zName
124721 if( p->bHasDocsize ){
124722 fts3DbExec(&rc, db,
124723 "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
124724 p->zDb, p->zName
124727 assert( p->bHasStat==p->bFts4 );
124728 if( p->bHasStat ){
124729 sqlite3Fts3CreateStatTable(&rc, p);
124731 return rc;
124735 ** Store the current database page-size in bytes in p->nPgsz.
124737 ** If *pRc is non-zero when this function is called, it is a no-op.
124738 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
124739 ** before returning.
124741 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
124742 if( *pRc==SQLITE_OK ){
124743 int rc; /* Return code */
124744 char *zSql; /* SQL text "PRAGMA %Q.page_size" */
124745 sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
124747 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
124748 if( !zSql ){
124749 rc = SQLITE_NOMEM;
124750 }else{
124751 rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
124752 if( rc==SQLITE_OK ){
124753 sqlite3_step(pStmt);
124754 p->nPgsz = sqlite3_column_int(pStmt, 0);
124755 rc = sqlite3_finalize(pStmt);
124756 }else if( rc==SQLITE_AUTH ){
124757 p->nPgsz = 1024;
124758 rc = SQLITE_OK;
124761 assert( p->nPgsz>0 || rc!=SQLITE_OK );
124762 sqlite3_free(zSql);
124763 *pRc = rc;
124768 ** "Special" FTS4 arguments are column specifications of the following form:
124770 ** <key> = <value>
124772 ** There may not be whitespace surrounding the "=" character. The <value>
124773 ** term may be quoted, but the <key> may not.
124775 static int fts3IsSpecialColumn(
124776 const char *z,
124777 int *pnKey,
124778 char **pzValue
124780 char *zValue;
124781 const char *zCsr = z;
124783 while( *zCsr!='=' ){
124784 if( *zCsr=='\0' ) return 0;
124785 zCsr++;
124788 *pnKey = (int)(zCsr-z);
124789 zValue = sqlite3_mprintf("%s", &zCsr[1]);
124790 if( zValue ){
124791 sqlite3Fts3Dequote(zValue);
124793 *pzValue = zValue;
124794 return 1;
124798 ** Append the output of a printf() style formatting to an existing string.
124800 static void fts3Appendf(
124801 int *pRc, /* IN/OUT: Error code */
124802 char **pz, /* IN/OUT: Pointer to string buffer */
124803 const char *zFormat, /* Printf format string to append */
124804 ... /* Arguments for printf format string */
124806 if( *pRc==SQLITE_OK ){
124807 va_list ap;
124808 char *z;
124809 va_start(ap, zFormat);
124810 z = sqlite3_vmprintf(zFormat, ap);
124811 va_end(ap);
124812 if( z && *pz ){
124813 char *z2 = sqlite3_mprintf("%s%s", *pz, z);
124814 sqlite3_free(z);
124815 z = z2;
124817 if( z==0 ) *pRc = SQLITE_NOMEM;
124818 sqlite3_free(*pz);
124819 *pz = z;
124824 ** Return a copy of input string zInput enclosed in double-quotes (") and
124825 ** with all double quote characters escaped. For example:
124827 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
124829 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
124830 ** is the callers responsibility to call sqlite3_free() to release this
124831 ** memory.
124833 static char *fts3QuoteId(char const *zInput){
124834 int nRet;
124835 char *zRet;
124836 nRet = 2 + (int)strlen(zInput)*2 + 1;
124837 zRet = sqlite3_malloc(nRet);
124838 if( zRet ){
124839 int i;
124840 char *z = zRet;
124841 *(z++) = '"';
124842 for(i=0; zInput[i]; i++){
124843 if( zInput[i]=='"' ) *(z++) = '"';
124844 *(z++) = zInput[i];
124846 *(z++) = '"';
124847 *(z++) = '\0';
124849 return zRet;
124853 ** Return a list of comma separated SQL expressions and a FROM clause that
124854 ** could be used in a SELECT statement such as the following:
124856 ** SELECT <list of expressions> FROM %_content AS x ...
124858 ** to return the docid, followed by each column of text data in order
124859 ** from left to write. If parameter zFunc is not NULL, then instead of
124860 ** being returned directly each column of text data is passed to an SQL
124861 ** function named zFunc first. For example, if zFunc is "unzip" and the
124862 ** table has the three user-defined columns "a", "b", and "c", the following
124863 ** string is returned:
124865 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
124867 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
124868 ** is the responsibility of the caller to eventually free it.
124870 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
124871 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
124872 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
124873 ** no error occurs, *pRc is left unmodified.
124875 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
124876 char *zRet = 0;
124877 char *zFree = 0;
124878 char *zFunction;
124879 int i;
124881 if( p->zContentTbl==0 ){
124882 if( !zFunc ){
124883 zFunction = "";
124884 }else{
124885 zFree = zFunction = fts3QuoteId(zFunc);
124887 fts3Appendf(pRc, &zRet, "docid");
124888 for(i=0; i<p->nColumn; i++){
124889 fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
124891 if( p->zLanguageid ){
124892 fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
124894 sqlite3_free(zFree);
124895 }else{
124896 fts3Appendf(pRc, &zRet, "rowid");
124897 for(i=0; i<p->nColumn; i++){
124898 fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
124900 if( p->zLanguageid ){
124901 fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
124904 fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
124905 p->zDb,
124906 (p->zContentTbl ? p->zContentTbl : p->zName),
124907 (p->zContentTbl ? "" : "_content")
124909 return zRet;
124913 ** Return a list of N comma separated question marks, where N is the number
124914 ** of columns in the %_content table (one for the docid plus one for each
124915 ** user-defined text column).
124917 ** If argument zFunc is not NULL, then all but the first question mark
124918 ** is preceded by zFunc and an open bracket, and followed by a closed
124919 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
124920 ** user-defined text columns, the following string is returned:
124922 ** "?, zip(?), zip(?), zip(?)"
124924 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
124925 ** is the responsibility of the caller to eventually free it.
124927 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
124928 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
124929 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
124930 ** no error occurs, *pRc is left unmodified.
124932 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
124933 char *zRet = 0;
124934 char *zFree = 0;
124935 char *zFunction;
124936 int i;
124938 if( !zFunc ){
124939 zFunction = "";
124940 }else{
124941 zFree = zFunction = fts3QuoteId(zFunc);
124943 fts3Appendf(pRc, &zRet, "?");
124944 for(i=0; i<p->nColumn; i++){
124945 fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
124947 if( p->zLanguageid ){
124948 fts3Appendf(pRc, &zRet, ", ?");
124950 sqlite3_free(zFree);
124951 return zRet;
124955 ** This function interprets the string at (*pp) as a non-negative integer
124956 ** value. It reads the integer and sets *pnOut to the value read, then
124957 ** sets *pp to point to the byte immediately following the last byte of
124958 ** the integer value.
124960 ** Only decimal digits ('0'..'9') may be part of an integer value.
124962 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
124963 ** the output value undefined. Otherwise SQLITE_OK is returned.
124965 ** This function is used when parsing the "prefix=" FTS4 parameter.
124967 static int fts3GobbleInt(const char **pp, int *pnOut){
124968 const char *p; /* Iterator pointer */
124969 int nInt = 0; /* Output value */
124971 for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
124972 nInt = nInt * 10 + (p[0] - '0');
124974 if( p==*pp ) return SQLITE_ERROR;
124975 *pnOut = nInt;
124976 *pp = p;
124977 return SQLITE_OK;
124981 ** This function is called to allocate an array of Fts3Index structures
124982 ** representing the indexes maintained by the current FTS table. FTS tables
124983 ** always maintain the main "terms" index, but may also maintain one or
124984 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
124985 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
124987 ** Argument zParam is passed the value of the "prefix=" option if one was
124988 ** specified, or NULL otherwise.
124990 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
124991 ** the allocated array. *pnIndex is set to the number of elements in the
124992 ** array. If an error does occur, an SQLite error code is returned.
124994 ** Regardless of whether or not an error is returned, it is the responsibility
124995 ** of the caller to call sqlite3_free() on the output array to free it.
124997 static int fts3PrefixParameter(
124998 const char *zParam, /* ABC in prefix=ABC parameter to parse */
124999 int *pnIndex, /* OUT: size of *apIndex[] array */
125000 struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
125002 struct Fts3Index *aIndex; /* Allocated array */
125003 int nIndex = 1; /* Number of entries in array */
125005 if( zParam && zParam[0] ){
125006 const char *p;
125007 nIndex++;
125008 for(p=zParam; *p; p++){
125009 if( *p==',' ) nIndex++;
125013 aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
125014 *apIndex = aIndex;
125015 *pnIndex = nIndex;
125016 if( !aIndex ){
125017 return SQLITE_NOMEM;
125020 memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
125021 if( zParam ){
125022 const char *p = zParam;
125023 int i;
125024 for(i=1; i<nIndex; i++){
125025 int nPrefix;
125026 if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
125027 aIndex[i].nPrefix = nPrefix;
125032 return SQLITE_OK;
125036 ** This function is called when initializing an FTS4 table that uses the
125037 ** content=xxx option. It determines the number of and names of the columns
125038 ** of the new FTS4 table.
125040 ** The third argument passed to this function is the value passed to the
125041 ** config=xxx option (i.e. "xxx"). This function queries the database for
125042 ** a table of that name. If found, the output variables are populated
125043 ** as follows:
125045 ** *pnCol: Set to the number of columns table xxx has,
125047 ** *pnStr: Set to the total amount of space required to store a copy
125048 ** of each columns name, including the nul-terminator.
125050 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
125051 ** the name of the corresponding column in table xxx. The array
125052 ** and its contents are allocated using a single allocation. It
125053 ** is the responsibility of the caller to free this allocation
125054 ** by eventually passing the *pazCol value to sqlite3_free().
125056 ** If the table cannot be found, an error code is returned and the output
125057 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
125058 ** returned (and the output variables are undefined).
125060 static int fts3ContentColumns(
125061 sqlite3 *db, /* Database handle */
125062 const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
125063 const char *zTbl, /* Name of content table */
125064 const char ***pazCol, /* OUT: Malloc'd array of column names */
125065 int *pnCol, /* OUT: Size of array *pazCol */
125066 int *pnStr /* OUT: Bytes of string content */
125068 int rc = SQLITE_OK; /* Return code */
125069 char *zSql; /* "SELECT *" statement on zTbl */
125070 sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
125072 zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
125073 if( !zSql ){
125074 rc = SQLITE_NOMEM;
125075 }else{
125076 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
125078 sqlite3_free(zSql);
125080 if( rc==SQLITE_OK ){
125081 const char **azCol; /* Output array */
125082 int nStr = 0; /* Size of all column names (incl. 0x00) */
125083 int nCol; /* Number of table columns */
125084 int i; /* Used to iterate through columns */
125086 /* Loop through the returned columns. Set nStr to the number of bytes of
125087 ** space required to store a copy of each column name, including the
125088 ** nul-terminator byte. */
125089 nCol = sqlite3_column_count(pStmt);
125090 for(i=0; i<nCol; i++){
125091 const char *zCol = sqlite3_column_name(pStmt, i);
125092 nStr += (int)strlen(zCol) + 1;
125095 /* Allocate and populate the array to return. */
125096 azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
125097 if( azCol==0 ){
125098 rc = SQLITE_NOMEM;
125099 }else{
125100 char *p = (char *)&azCol[nCol];
125101 for(i=0; i<nCol; i++){
125102 const char *zCol = sqlite3_column_name(pStmt, i);
125103 int n = (int)strlen(zCol)+1;
125104 memcpy(p, zCol, n);
125105 azCol[i] = p;
125106 p += n;
125109 sqlite3_finalize(pStmt);
125111 /* Set the output variables. */
125112 *pnCol = nCol;
125113 *pnStr = nStr;
125114 *pazCol = azCol;
125117 return rc;
125121 ** This function is the implementation of both the xConnect and xCreate
125122 ** methods of the FTS3 virtual table.
125124 ** The argv[] array contains the following:
125126 ** argv[0] -> module name ("fts3" or "fts4")
125127 ** argv[1] -> database name
125128 ** argv[2] -> table name
125129 ** argv[...] -> "column name" and other module argument fields.
125131 static int fts3InitVtab(
125132 int isCreate, /* True for xCreate, false for xConnect */
125133 sqlite3 *db, /* The SQLite database connection */
125134 void *pAux, /* Hash table containing tokenizers */
125135 int argc, /* Number of elements in argv array */
125136 const char * const *argv, /* xCreate/xConnect argument array */
125137 sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
125138 char **pzErr /* Write any error message here */
125140 Fts3Hash *pHash = (Fts3Hash *)pAux;
125141 Fts3Table *p = 0; /* Pointer to allocated vtab */
125142 int rc = SQLITE_OK; /* Return code */
125143 int i; /* Iterator variable */
125144 int nByte; /* Size of allocation used for *p */
125145 int iCol; /* Column index */
125146 int nString = 0; /* Bytes required to hold all column names */
125147 int nCol = 0; /* Number of columns in the FTS table */
125148 char *zCsr; /* Space for holding column names */
125149 int nDb; /* Bytes required to hold database name */
125150 int nName; /* Bytes required to hold table name */
125151 int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
125152 const char **aCol; /* Array of column names */
125153 sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
125155 int nIndex; /* Size of aIndex[] array */
125156 struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
125158 /* The results of parsing supported FTS4 key=value options: */
125159 int bNoDocsize = 0; /* True to omit %_docsize table */
125160 int bDescIdx = 0; /* True to store descending indexes */
125161 char *zPrefix = 0; /* Prefix parameter value (or NULL) */
125162 char *zCompress = 0; /* compress=? parameter (or NULL) */
125163 char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
125164 char *zContent = 0; /* content=? parameter (or NULL) */
125165 char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
125166 char **azNotindexed = 0; /* The set of notindexed= columns */
125167 int nNotindexed = 0; /* Size of azNotindexed[] array */
125169 assert( strlen(argv[0])==4 );
125170 assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
125171 || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
125174 nDb = (int)strlen(argv[1]) + 1;
125175 nName = (int)strlen(argv[2]) + 1;
125177 nByte = sizeof(const char *) * (argc-2);
125178 aCol = (const char **)sqlite3_malloc(nByte);
125179 if( aCol ){
125180 memset((void*)aCol, 0, nByte);
125181 azNotindexed = (char **)sqlite3_malloc(nByte);
125183 if( azNotindexed ){
125184 memset(azNotindexed, 0, nByte);
125186 if( !aCol || !azNotindexed ){
125187 rc = SQLITE_NOMEM;
125188 goto fts3_init_out;
125191 /* Loop through all of the arguments passed by the user to the FTS3/4
125192 ** module (i.e. all the column names and special arguments). This loop
125193 ** does the following:
125195 ** + Figures out the number of columns the FTSX table will have, and
125196 ** the number of bytes of space that must be allocated to store copies
125197 ** of the column names.
125199 ** + If there is a tokenizer specification included in the arguments,
125200 ** initializes the tokenizer pTokenizer.
125202 for(i=3; rc==SQLITE_OK && i<argc; i++){
125203 char const *z = argv[i];
125204 int nKey;
125205 char *zVal;
125207 /* Check if this is a tokenizer specification */
125208 if( !pTokenizer
125209 && strlen(z)>8
125210 && 0==sqlite3_strnicmp(z, "tokenize", 8)
125211 && 0==sqlite3Fts3IsIdChar(z[8])
125213 rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
125216 /* Check if it is an FTS4 special argument. */
125217 else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
125218 struct Fts4Option {
125219 const char *zOpt;
125220 int nOpt;
125221 } aFts4Opt[] = {
125222 { "matchinfo", 9 }, /* 0 -> MATCHINFO */
125223 { "prefix", 6 }, /* 1 -> PREFIX */
125224 { "compress", 8 }, /* 2 -> COMPRESS */
125225 { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
125226 { "order", 5 }, /* 4 -> ORDER */
125227 { "content", 7 }, /* 5 -> CONTENT */
125228 { "languageid", 10 }, /* 6 -> LANGUAGEID */
125229 { "notindexed", 10 } /* 7 -> NOTINDEXED */
125232 int iOpt;
125233 if( !zVal ){
125234 rc = SQLITE_NOMEM;
125235 }else{
125236 for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
125237 struct Fts4Option *pOp = &aFts4Opt[iOpt];
125238 if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
125239 break;
125242 if( iOpt==SizeofArray(aFts4Opt) ){
125243 *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
125244 rc = SQLITE_ERROR;
125245 }else{
125246 switch( iOpt ){
125247 case 0: /* MATCHINFO */
125248 if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
125249 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
125250 rc = SQLITE_ERROR;
125252 bNoDocsize = 1;
125253 break;
125255 case 1: /* PREFIX */
125256 sqlite3_free(zPrefix);
125257 zPrefix = zVal;
125258 zVal = 0;
125259 break;
125261 case 2: /* COMPRESS */
125262 sqlite3_free(zCompress);
125263 zCompress = zVal;
125264 zVal = 0;
125265 break;
125267 case 3: /* UNCOMPRESS */
125268 sqlite3_free(zUncompress);
125269 zUncompress = zVal;
125270 zVal = 0;
125271 break;
125273 case 4: /* ORDER */
125274 if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
125275 && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
125277 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
125278 rc = SQLITE_ERROR;
125280 bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
125281 break;
125283 case 5: /* CONTENT */
125284 sqlite3_free(zContent);
125285 zContent = zVal;
125286 zVal = 0;
125287 break;
125289 case 6: /* LANGUAGEID */
125290 assert( iOpt==6 );
125291 sqlite3_free(zLanguageid);
125292 zLanguageid = zVal;
125293 zVal = 0;
125294 break;
125296 case 7: /* NOTINDEXED */
125297 azNotindexed[nNotindexed++] = zVal;
125298 zVal = 0;
125299 break;
125302 sqlite3_free(zVal);
125306 /* Otherwise, the argument is a column name. */
125307 else {
125308 nString += (int)(strlen(z) + 1);
125309 aCol[nCol++] = z;
125313 /* If a content=xxx option was specified, the following:
125315 ** 1. Ignore any compress= and uncompress= options.
125317 ** 2. If no column names were specified as part of the CREATE VIRTUAL
125318 ** TABLE statement, use all columns from the content table.
125320 if( rc==SQLITE_OK && zContent ){
125321 sqlite3_free(zCompress);
125322 sqlite3_free(zUncompress);
125323 zCompress = 0;
125324 zUncompress = 0;
125325 if( nCol==0 ){
125326 sqlite3_free((void*)aCol);
125327 aCol = 0;
125328 rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
125330 /* If a languageid= option was specified, remove the language id
125331 ** column from the aCol[] array. */
125332 if( rc==SQLITE_OK && zLanguageid ){
125333 int j;
125334 for(j=0; j<nCol; j++){
125335 if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
125336 int k;
125337 for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
125338 nCol--;
125339 break;
125345 if( rc!=SQLITE_OK ) goto fts3_init_out;
125347 if( nCol==0 ){
125348 assert( nString==0 );
125349 aCol[0] = "content";
125350 nString = 8;
125351 nCol = 1;
125354 if( pTokenizer==0 ){
125355 rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
125356 if( rc!=SQLITE_OK ) goto fts3_init_out;
125358 assert( pTokenizer );
125360 rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
125361 if( rc==SQLITE_ERROR ){
125362 assert( zPrefix );
125363 *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
125365 if( rc!=SQLITE_OK ) goto fts3_init_out;
125367 /* Allocate and populate the Fts3Table structure. */
125368 nByte = sizeof(Fts3Table) + /* Fts3Table */
125369 nCol * sizeof(char *) + /* azColumn */
125370 nIndex * sizeof(struct Fts3Index) + /* aIndex */
125371 nCol * sizeof(u8) + /* abNotindexed */
125372 nName + /* zName */
125373 nDb + /* zDb */
125374 nString; /* Space for azColumn strings */
125375 p = (Fts3Table*)sqlite3_malloc(nByte);
125376 if( p==0 ){
125377 rc = SQLITE_NOMEM;
125378 goto fts3_init_out;
125380 memset(p, 0, nByte);
125381 p->db = db;
125382 p->nColumn = nCol;
125383 p->nPendingData = 0;
125384 p->azColumn = (char **)&p[1];
125385 p->pTokenizer = pTokenizer;
125386 p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
125387 p->bHasDocsize = (isFts4 && bNoDocsize==0);
125388 p->bHasStat = isFts4;
125389 p->bFts4 = isFts4;
125390 p->bDescIdx = bDescIdx;
125391 p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
125392 p->zContentTbl = zContent;
125393 p->zLanguageid = zLanguageid;
125394 zContent = 0;
125395 zLanguageid = 0;
125396 TESTONLY( p->inTransaction = -1 );
125397 TESTONLY( p->mxSavepoint = -1 );
125399 p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
125400 memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
125401 p->nIndex = nIndex;
125402 for(i=0; i<nIndex; i++){
125403 fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
125405 p->abNotindexed = (u8 *)&p->aIndex[nIndex];
125407 /* Fill in the zName and zDb fields of the vtab structure. */
125408 zCsr = (char *)&p->abNotindexed[nCol];
125409 p->zName = zCsr;
125410 memcpy(zCsr, argv[2], nName);
125411 zCsr += nName;
125412 p->zDb = zCsr;
125413 memcpy(zCsr, argv[1], nDb);
125414 zCsr += nDb;
125416 /* Fill in the azColumn array */
125417 for(iCol=0; iCol<nCol; iCol++){
125418 char *z;
125419 int n = 0;
125420 z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
125421 memcpy(zCsr, z, n);
125422 zCsr[n] = '\0';
125423 sqlite3Fts3Dequote(zCsr);
125424 p->azColumn[iCol] = zCsr;
125425 zCsr += n+1;
125426 assert( zCsr <= &((char *)p)[nByte] );
125429 /* Fill in the abNotindexed array */
125430 for(iCol=0; iCol<nCol; iCol++){
125431 int n = (int)strlen(p->azColumn[iCol]);
125432 for(i=0; i<nNotindexed; i++){
125433 char *zNot = azNotindexed[i];
125434 if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
125435 p->abNotindexed[iCol] = 1;
125436 sqlite3_free(zNot);
125437 azNotindexed[i] = 0;
125441 for(i=0; i<nNotindexed; i++){
125442 if( azNotindexed[i] ){
125443 *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
125444 rc = SQLITE_ERROR;
125448 if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
125449 char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
125450 rc = SQLITE_ERROR;
125451 *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
125453 p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
125454 p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
125455 if( rc!=SQLITE_OK ) goto fts3_init_out;
125457 /* If this is an xCreate call, create the underlying tables in the
125458 ** database. TODO: For xConnect(), it could verify that said tables exist.
125460 if( isCreate ){
125461 rc = fts3CreateTables(p);
125464 /* Check to see if a legacy fts3 table has been "upgraded" by the
125465 ** addition of a %_stat table so that it can use incremental merge.
125467 if( !isFts4 && !isCreate ){
125468 int rc2 = SQLITE_OK;
125469 fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
125470 p->zDb, p->zName);
125471 if( rc2==SQLITE_OK ) p->bHasStat = 1;
125474 /* Figure out the page-size for the database. This is required in order to
125475 ** estimate the cost of loading large doclists from the database. */
125476 fts3DatabasePageSize(&rc, p);
125477 p->nNodeSize = p->nPgsz-35;
125479 /* Declare the table schema to SQLite. */
125480 fts3DeclareVtab(&rc, p);
125482 fts3_init_out:
125483 sqlite3_free(zPrefix);
125484 sqlite3_free(aIndex);
125485 sqlite3_free(zCompress);
125486 sqlite3_free(zUncompress);
125487 sqlite3_free(zContent);
125488 sqlite3_free(zLanguageid);
125489 for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
125490 sqlite3_free((void *)aCol);
125491 sqlite3_free((void *)azNotindexed);
125492 if( rc!=SQLITE_OK ){
125493 if( p ){
125494 fts3DisconnectMethod((sqlite3_vtab *)p);
125495 }else if( pTokenizer ){
125496 pTokenizer->pModule->xDestroy(pTokenizer);
125498 }else{
125499 assert( p->pSegments==0 );
125500 *ppVTab = &p->base;
125502 return rc;
125506 ** The xConnect() and xCreate() methods for the virtual table. All the
125507 ** work is done in function fts3InitVtab().
125509 static int fts3ConnectMethod(
125510 sqlite3 *db, /* Database connection */
125511 void *pAux, /* Pointer to tokenizer hash table */
125512 int argc, /* Number of elements in argv array */
125513 const char * const *argv, /* xCreate/xConnect argument array */
125514 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
125515 char **pzErr /* OUT: sqlite3_malloc'd error message */
125517 return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
125519 static int fts3CreateMethod(
125520 sqlite3 *db, /* Database connection */
125521 void *pAux, /* Pointer to tokenizer hash table */
125522 int argc, /* Number of elements in argv array */
125523 const char * const *argv, /* xCreate/xConnect argument array */
125524 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
125525 char **pzErr /* OUT: sqlite3_malloc'd error message */
125527 return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
125531 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
125532 ** extension is currently being used by a version of SQLite too old to
125533 ** support estimatedRows. In that case this function is a no-op.
125535 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
125536 #if SQLITE_VERSION_NUMBER>=3008002
125537 if( sqlite3_libversion_number()>=3008002 ){
125538 pIdxInfo->estimatedRows = nRow;
125540 #endif
125544 ** Implementation of the xBestIndex method for FTS3 tables. There
125545 ** are three possible strategies, in order of preference:
125547 ** 1. Direct lookup by rowid or docid.
125548 ** 2. Full-text search using a MATCH operator on a non-docid column.
125549 ** 3. Linear scan of %_content table.
125551 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
125552 Fts3Table *p = (Fts3Table *)pVTab;
125553 int i; /* Iterator variable */
125554 int iCons = -1; /* Index of constraint to use */
125556 int iLangidCons = -1; /* Index of langid=x constraint, if present */
125557 int iDocidGe = -1; /* Index of docid>=x constraint, if present */
125558 int iDocidLe = -1; /* Index of docid<=x constraint, if present */
125559 int iIdx;
125561 /* By default use a full table scan. This is an expensive option,
125562 ** so search through the constraints to see if a more efficient
125563 ** strategy is possible.
125565 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
125566 pInfo->estimatedCost = 5000000;
125567 for(i=0; i<pInfo->nConstraint; i++){
125568 int bDocid; /* True if this constraint is on docid */
125569 struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
125570 if( pCons->usable==0 ){
125571 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
125572 /* There exists an unusable MATCH constraint. This means that if
125573 ** the planner does elect to use the results of this call as part
125574 ** of the overall query plan the user will see an "unable to use
125575 ** function MATCH in the requested context" error. To discourage
125576 ** this, return a very high cost here. */
125577 pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
125578 pInfo->estimatedCost = SQLITE_HUGE_COST;
125579 fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
125580 return SQLITE_OK;
125582 continue;
125585 bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
125587 /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
125588 if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
125589 pInfo->idxNum = FTS3_DOCID_SEARCH;
125590 pInfo->estimatedCost = 1.0;
125591 iCons = i;
125594 /* A MATCH constraint. Use a full-text search.
125596 ** If there is more than one MATCH constraint available, use the first
125597 ** one encountered. If there is both a MATCH constraint and a direct
125598 ** rowid/docid lookup, prefer the MATCH strategy. This is done even
125599 ** though the rowid/docid lookup is faster than a MATCH query, selecting
125600 ** it would lead to an "unable to use function MATCH in the requested
125601 ** context" error.
125603 if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
125604 && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
125606 pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
125607 pInfo->estimatedCost = 2.0;
125608 iCons = i;
125611 /* Equality constraint on the langid column */
125612 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
125613 && pCons->iColumn==p->nColumn + 2
125615 iLangidCons = i;
125618 if( bDocid ){
125619 switch( pCons->op ){
125620 case SQLITE_INDEX_CONSTRAINT_GE:
125621 case SQLITE_INDEX_CONSTRAINT_GT:
125622 iDocidGe = i;
125623 break;
125625 case SQLITE_INDEX_CONSTRAINT_LE:
125626 case SQLITE_INDEX_CONSTRAINT_LT:
125627 iDocidLe = i;
125628 break;
125633 iIdx = 1;
125634 if( iCons>=0 ){
125635 pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
125636 pInfo->aConstraintUsage[iCons].omit = 1;
125638 if( iLangidCons>=0 ){
125639 pInfo->idxNum |= FTS3_HAVE_LANGID;
125640 pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
125642 if( iDocidGe>=0 ){
125643 pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
125644 pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
125646 if( iDocidLe>=0 ){
125647 pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
125648 pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
125651 /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
125652 ** docid) order. Both ascending and descending are possible.
125654 if( pInfo->nOrderBy==1 ){
125655 struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
125656 if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
125657 if( pOrder->desc ){
125658 pInfo->idxStr = "DESC";
125659 }else{
125660 pInfo->idxStr = "ASC";
125662 pInfo->orderByConsumed = 1;
125666 assert( p->pSegments==0 );
125667 return SQLITE_OK;
125671 ** Implementation of xOpen method.
125673 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
125674 sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
125676 UNUSED_PARAMETER(pVTab);
125678 /* Allocate a buffer large enough for an Fts3Cursor structure. If the
125679 ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
125680 ** if the allocation fails, return SQLITE_NOMEM.
125682 *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
125683 if( !pCsr ){
125684 return SQLITE_NOMEM;
125686 memset(pCsr, 0, sizeof(Fts3Cursor));
125687 return SQLITE_OK;
125691 ** Close the cursor. For additional information see the documentation
125692 ** on the xClose method of the virtual table interface.
125694 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
125695 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
125696 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
125697 sqlite3_finalize(pCsr->pStmt);
125698 sqlite3Fts3ExprFree(pCsr->pExpr);
125699 sqlite3Fts3FreeDeferredTokens(pCsr);
125700 sqlite3_free(pCsr->aDoclist);
125701 sqlite3_free(pCsr->aMatchinfo);
125702 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
125703 sqlite3_free(pCsr);
125704 return SQLITE_OK;
125708 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
125709 ** compose and prepare an SQL statement of the form:
125711 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
125713 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
125714 ** it. If an error occurs, return an SQLite error code.
125716 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
125718 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
125719 int rc = SQLITE_OK;
125720 if( pCsr->pStmt==0 ){
125721 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
125722 char *zSql;
125723 zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
125724 if( !zSql ) return SQLITE_NOMEM;
125725 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
125726 sqlite3_free(zSql);
125728 *ppStmt = pCsr->pStmt;
125729 return rc;
125733 ** Position the pCsr->pStmt statement so that it is on the row
125734 ** of the %_content table that contains the last match. Return
125735 ** SQLITE_OK on success.
125737 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
125738 int rc = SQLITE_OK;
125739 if( pCsr->isRequireSeek ){
125740 sqlite3_stmt *pStmt = 0;
125742 rc = fts3CursorSeekStmt(pCsr, &pStmt);
125743 if( rc==SQLITE_OK ){
125744 sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
125745 pCsr->isRequireSeek = 0;
125746 if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
125747 return SQLITE_OK;
125748 }else{
125749 rc = sqlite3_reset(pCsr->pStmt);
125750 if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
125751 /* If no row was found and no error has occurred, then the %_content
125752 ** table is missing a row that is present in the full-text index.
125753 ** The data structures are corrupt. */
125754 rc = FTS_CORRUPT_VTAB;
125755 pCsr->isEof = 1;
125761 if( rc!=SQLITE_OK && pContext ){
125762 sqlite3_result_error_code(pContext, rc);
125764 return rc;
125768 ** This function is used to process a single interior node when searching
125769 ** a b-tree for a term or term prefix. The node data is passed to this
125770 ** function via the zNode/nNode parameters. The term to search for is
125771 ** passed in zTerm/nTerm.
125773 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
125774 ** of the child node that heads the sub-tree that may contain the term.
125776 ** If piLast is not NULL, then *piLast is set to the right-most child node
125777 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
125778 ** a prefix.
125780 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
125782 static int fts3ScanInteriorNode(
125783 const char *zTerm, /* Term to select leaves for */
125784 int nTerm, /* Size of term zTerm in bytes */
125785 const char *zNode, /* Buffer containing segment interior node */
125786 int nNode, /* Size of buffer at zNode */
125787 sqlite3_int64 *piFirst, /* OUT: Selected child node */
125788 sqlite3_int64 *piLast /* OUT: Selected child node */
125790 int rc = SQLITE_OK; /* Return code */
125791 const char *zCsr = zNode; /* Cursor to iterate through node */
125792 const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
125793 char *zBuffer = 0; /* Buffer to load terms into */
125794 int nAlloc = 0; /* Size of allocated buffer */
125795 int isFirstTerm = 1; /* True when processing first term on page */
125796 sqlite3_int64 iChild; /* Block id of child node to descend to */
125798 /* Skip over the 'height' varint that occurs at the start of every
125799 ** interior node. Then load the blockid of the left-child of the b-tree
125800 ** node into variable iChild.
125802 ** Even if the data structure on disk is corrupted, this (reading two
125803 ** varints from the buffer) does not risk an overread. If zNode is a
125804 ** root node, then the buffer comes from a SELECT statement. SQLite does
125805 ** not make this guarantee explicitly, but in practice there are always
125806 ** either more than 20 bytes of allocated space following the nNode bytes of
125807 ** contents, or two zero bytes. Or, if the node is read from the %_segments
125808 ** table, then there are always 20 bytes of zeroed padding following the
125809 ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
125811 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
125812 zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
125813 if( zCsr>zEnd ){
125814 return FTS_CORRUPT_VTAB;
125817 while( zCsr<zEnd && (piFirst || piLast) ){
125818 int cmp; /* memcmp() result */
125819 int nSuffix; /* Size of term suffix */
125820 int nPrefix = 0; /* Size of term prefix */
125821 int nBuffer; /* Total term size */
125823 /* Load the next term on the node into zBuffer. Use realloc() to expand
125824 ** the size of zBuffer if required. */
125825 if( !isFirstTerm ){
125826 zCsr += fts3GetVarint32(zCsr, &nPrefix);
125828 isFirstTerm = 0;
125829 zCsr += fts3GetVarint32(zCsr, &nSuffix);
125831 if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
125832 rc = FTS_CORRUPT_VTAB;
125833 goto finish_scan;
125835 if( nPrefix+nSuffix>nAlloc ){
125836 char *zNew;
125837 nAlloc = (nPrefix+nSuffix) * 2;
125838 zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
125839 if( !zNew ){
125840 rc = SQLITE_NOMEM;
125841 goto finish_scan;
125843 zBuffer = zNew;
125845 assert( zBuffer );
125846 memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
125847 nBuffer = nPrefix + nSuffix;
125848 zCsr += nSuffix;
125850 /* Compare the term we are searching for with the term just loaded from
125851 ** the interior node. If the specified term is greater than or equal
125852 ** to the term from the interior node, then all terms on the sub-tree
125853 ** headed by node iChild are smaller than zTerm. No need to search
125854 ** iChild.
125856 ** If the interior node term is larger than the specified term, then
125857 ** the tree headed by iChild may contain the specified term.
125859 cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
125860 if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
125861 *piFirst = iChild;
125862 piFirst = 0;
125865 if( piLast && cmp<0 ){
125866 *piLast = iChild;
125867 piLast = 0;
125870 iChild++;
125873 if( piFirst ) *piFirst = iChild;
125874 if( piLast ) *piLast = iChild;
125876 finish_scan:
125877 sqlite3_free(zBuffer);
125878 return rc;
125883 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
125884 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
125885 ** contains a term. This function searches the sub-tree headed by the zNode
125886 ** node for the range of leaf nodes that may contain the specified term
125887 ** or terms for which the specified term is a prefix.
125889 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
125890 ** left-most leaf node in the tree that may contain the specified term.
125891 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
125892 ** right-most leaf node that may contain a term for which the specified
125893 ** term is a prefix.
125895 ** It is possible that the range of returned leaf nodes does not contain
125896 ** the specified term or any terms for which it is a prefix. However, if the
125897 ** segment does contain any such terms, they are stored within the identified
125898 ** range. Because this function only inspects interior segment nodes (and
125899 ** never loads leaf nodes into memory), it is not possible to be sure.
125901 ** If an error occurs, an error code other than SQLITE_OK is returned.
125903 static int fts3SelectLeaf(
125904 Fts3Table *p, /* Virtual table handle */
125905 const char *zTerm, /* Term to select leaves for */
125906 int nTerm, /* Size of term zTerm in bytes */
125907 const char *zNode, /* Buffer containing segment interior node */
125908 int nNode, /* Size of buffer at zNode */
125909 sqlite3_int64 *piLeaf, /* Selected leaf node */
125910 sqlite3_int64 *piLeaf2 /* Selected leaf node */
125912 int rc; /* Return code */
125913 int iHeight; /* Height of this node in tree */
125915 assert( piLeaf || piLeaf2 );
125917 fts3GetVarint32(zNode, &iHeight);
125918 rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
125919 assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
125921 if( rc==SQLITE_OK && iHeight>1 ){
125922 char *zBlob = 0; /* Blob read from %_segments table */
125923 int nBlob; /* Size of zBlob in bytes */
125925 if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
125926 rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
125927 if( rc==SQLITE_OK ){
125928 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
125930 sqlite3_free(zBlob);
125931 piLeaf = 0;
125932 zBlob = 0;
125935 if( rc==SQLITE_OK ){
125936 rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
125938 if( rc==SQLITE_OK ){
125939 rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
125941 sqlite3_free(zBlob);
125944 return rc;
125948 ** This function is used to create delta-encoded serialized lists of FTS3
125949 ** varints. Each call to this function appends a single varint to a list.
125951 static void fts3PutDeltaVarint(
125952 char **pp, /* IN/OUT: Output pointer */
125953 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
125954 sqlite3_int64 iVal /* Write this value to the list */
125956 assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
125957 *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
125958 *piPrev = iVal;
125962 ** When this function is called, *ppPoslist is assumed to point to the
125963 ** start of a position-list. After it returns, *ppPoslist points to the
125964 ** first byte after the position-list.
125966 ** A position list is list of positions (delta encoded) and columns for
125967 ** a single document record of a doclist. So, in other words, this
125968 ** routine advances *ppPoslist so that it points to the next docid in
125969 ** the doclist, or to the first byte past the end of the doclist.
125971 ** If pp is not NULL, then the contents of the position list are copied
125972 ** to *pp. *pp is set to point to the first byte past the last byte copied
125973 ** before this function returns.
125975 static void fts3PoslistCopy(char **pp, char **ppPoslist){
125976 char *pEnd = *ppPoslist;
125977 char c = 0;
125979 /* The end of a position list is marked by a zero encoded as an FTS3
125980 ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
125981 ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
125982 ** of some other, multi-byte, value.
125984 ** The following while-loop moves pEnd to point to the first byte that is not
125985 ** immediately preceded by a byte with the 0x80 bit set. Then increments
125986 ** pEnd once more so that it points to the byte immediately following the
125987 ** last byte in the position-list.
125989 while( *pEnd | c ){
125990 c = *pEnd++ & 0x80;
125991 testcase( c!=0 && (*pEnd)==0 );
125993 pEnd++; /* Advance past the POS_END terminator byte */
125995 if( pp ){
125996 int n = (int)(pEnd - *ppPoslist);
125997 char *p = *pp;
125998 memcpy(p, *ppPoslist, n);
125999 p += n;
126000 *pp = p;
126002 *ppPoslist = pEnd;
126006 ** When this function is called, *ppPoslist is assumed to point to the
126007 ** start of a column-list. After it returns, *ppPoslist points to the
126008 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
126010 ** A column-list is list of delta-encoded positions for a single column
126011 ** within a single document within a doclist.
126013 ** The column-list is terminated either by a POS_COLUMN varint (1) or
126014 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
126015 ** the POS_COLUMN or POS_END that terminates the column-list.
126017 ** If pp is not NULL, then the contents of the column-list are copied
126018 ** to *pp. *pp is set to point to the first byte past the last byte copied
126019 ** before this function returns. The POS_COLUMN or POS_END terminator
126020 ** is not copied into *pp.
126022 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
126023 char *pEnd = *ppPoslist;
126024 char c = 0;
126026 /* A column-list is terminated by either a 0x01 or 0x00 byte that is
126027 ** not part of a multi-byte varint.
126029 while( 0xFE & (*pEnd | c) ){
126030 c = *pEnd++ & 0x80;
126031 testcase( c!=0 && ((*pEnd)&0xfe)==0 );
126033 if( pp ){
126034 int n = (int)(pEnd - *ppPoslist);
126035 char *p = *pp;
126036 memcpy(p, *ppPoslist, n);
126037 p += n;
126038 *pp = p;
126040 *ppPoslist = pEnd;
126044 ** Value used to signify the end of an position-list. This is safe because
126045 ** it is not possible to have a document with 2^31 terms.
126047 #define POSITION_LIST_END 0x7fffffff
126050 ** This function is used to help parse position-lists. When this function is
126051 ** called, *pp may point to the start of the next varint in the position-list
126052 ** being parsed, or it may point to 1 byte past the end of the position-list
126053 ** (in which case **pp will be a terminator bytes POS_END (0) or
126054 ** (1)).
126056 ** If *pp points past the end of the current position-list, set *pi to
126057 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
126058 ** increment the current value of *pi by the value read, and set *pp to
126059 ** point to the next value before returning.
126061 ** Before calling this routine *pi must be initialized to the value of
126062 ** the previous position, or zero if we are reading the first position
126063 ** in the position-list. Because positions are delta-encoded, the value
126064 ** of the previous position is needed in order to compute the value of
126065 ** the next position.
126067 static void fts3ReadNextPos(
126068 char **pp, /* IN/OUT: Pointer into position-list buffer */
126069 sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
126071 if( (**pp)&0xFE ){
126072 fts3GetDeltaVarint(pp, pi);
126073 *pi -= 2;
126074 }else{
126075 *pi = POSITION_LIST_END;
126080 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
126081 ** the value of iCol encoded as a varint to *pp. This will start a new
126082 ** column list.
126084 ** Set *pp to point to the byte just after the last byte written before
126085 ** returning (do not modify it if iCol==0). Return the total number of bytes
126086 ** written (0 if iCol==0).
126088 static int fts3PutColNumber(char **pp, int iCol){
126089 int n = 0; /* Number of bytes written */
126090 if( iCol ){
126091 char *p = *pp; /* Output pointer */
126092 n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
126093 *p = 0x01;
126094 *pp = &p[n];
126096 return n;
126100 ** Compute the union of two position lists. The output written
126101 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
126102 ** order and with any duplicates removed. All pointers are
126103 ** updated appropriately. The caller is responsible for insuring
126104 ** that there is enough space in *pp to hold the complete output.
126106 static void fts3PoslistMerge(
126107 char **pp, /* Output buffer */
126108 char **pp1, /* Left input list */
126109 char **pp2 /* Right input list */
126111 char *p = *pp;
126112 char *p1 = *pp1;
126113 char *p2 = *pp2;
126115 while( *p1 || *p2 ){
126116 int iCol1; /* The current column index in pp1 */
126117 int iCol2; /* The current column index in pp2 */
126119 if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
126120 else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
126121 else iCol1 = 0;
126123 if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
126124 else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
126125 else iCol2 = 0;
126127 if( iCol1==iCol2 ){
126128 sqlite3_int64 i1 = 0; /* Last position from pp1 */
126129 sqlite3_int64 i2 = 0; /* Last position from pp2 */
126130 sqlite3_int64 iPrev = 0;
126131 int n = fts3PutColNumber(&p, iCol1);
126132 p1 += n;
126133 p2 += n;
126135 /* At this point, both p1 and p2 point to the start of column-lists
126136 ** for the same column (the column with index iCol1 and iCol2).
126137 ** A column-list is a list of non-negative delta-encoded varints, each
126138 ** incremented by 2 before being stored. Each list is terminated by a
126139 ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
126140 ** and writes the results to buffer p. p is left pointing to the byte
126141 ** after the list written. No terminator (POS_END or POS_COLUMN) is
126142 ** written to the output.
126144 fts3GetDeltaVarint(&p1, &i1);
126145 fts3GetDeltaVarint(&p2, &i2);
126147 fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
126148 iPrev -= 2;
126149 if( i1==i2 ){
126150 fts3ReadNextPos(&p1, &i1);
126151 fts3ReadNextPos(&p2, &i2);
126152 }else if( i1<i2 ){
126153 fts3ReadNextPos(&p1, &i1);
126154 }else{
126155 fts3ReadNextPos(&p2, &i2);
126157 }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
126158 }else if( iCol1<iCol2 ){
126159 p1 += fts3PutColNumber(&p, iCol1);
126160 fts3ColumnlistCopy(&p, &p1);
126161 }else{
126162 p2 += fts3PutColNumber(&p, iCol2);
126163 fts3ColumnlistCopy(&p, &p2);
126167 *p++ = POS_END;
126168 *pp = p;
126169 *pp1 = p1 + 1;
126170 *pp2 = p2 + 1;
126174 ** This function is used to merge two position lists into one. When it is
126175 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
126176 ** the part of a doclist that follows each document id. For example, if a row
126177 ** contains:
126179 ** 'a b c'|'x y z'|'a b b a'
126181 ** Then the position list for this row for token 'b' would consist of:
126183 ** 0x02 0x01 0x02 0x03 0x03 0x00
126185 ** When this function returns, both *pp1 and *pp2 are left pointing to the
126186 ** byte following the 0x00 terminator of their respective position lists.
126188 ** If isSaveLeft is 0, an entry is added to the output position list for
126189 ** each position in *pp2 for which there exists one or more positions in
126190 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
126191 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
126192 ** slots before it.
126194 ** e.g. nToken==1 searches for adjacent positions.
126196 static int fts3PoslistPhraseMerge(
126197 char **pp, /* IN/OUT: Preallocated output buffer */
126198 int nToken, /* Maximum difference in token positions */
126199 int isSaveLeft, /* Save the left position */
126200 int isExact, /* If *pp1 is exactly nTokens before *pp2 */
126201 char **pp1, /* IN/OUT: Left input list */
126202 char **pp2 /* IN/OUT: Right input list */
126204 char *p = *pp;
126205 char *p1 = *pp1;
126206 char *p2 = *pp2;
126207 int iCol1 = 0;
126208 int iCol2 = 0;
126210 /* Never set both isSaveLeft and isExact for the same invocation. */
126211 assert( isSaveLeft==0 || isExact==0 );
126213 assert( p!=0 && *p1!=0 && *p2!=0 );
126214 if( *p1==POS_COLUMN ){
126215 p1++;
126216 p1 += fts3GetVarint32(p1, &iCol1);
126218 if( *p2==POS_COLUMN ){
126219 p2++;
126220 p2 += fts3GetVarint32(p2, &iCol2);
126223 while( 1 ){
126224 if( iCol1==iCol2 ){
126225 char *pSave = p;
126226 sqlite3_int64 iPrev = 0;
126227 sqlite3_int64 iPos1 = 0;
126228 sqlite3_int64 iPos2 = 0;
126230 if( iCol1 ){
126231 *p++ = POS_COLUMN;
126232 p += sqlite3Fts3PutVarint(p, iCol1);
126235 assert( *p1!=POS_END && *p1!=POS_COLUMN );
126236 assert( *p2!=POS_END && *p2!=POS_COLUMN );
126237 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
126238 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
126240 while( 1 ){
126241 if( iPos2==iPos1+nToken
126242 || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
126244 sqlite3_int64 iSave;
126245 iSave = isSaveLeft ? iPos1 : iPos2;
126246 fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
126247 pSave = 0;
126248 assert( p );
126250 if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
126251 if( (*p2&0xFE)==0 ) break;
126252 fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
126253 }else{
126254 if( (*p1&0xFE)==0 ) break;
126255 fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
126259 if( pSave ){
126260 assert( pp && p );
126261 p = pSave;
126264 fts3ColumnlistCopy(0, &p1);
126265 fts3ColumnlistCopy(0, &p2);
126266 assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
126267 if( 0==*p1 || 0==*p2 ) break;
126269 p1++;
126270 p1 += fts3GetVarint32(p1, &iCol1);
126271 p2++;
126272 p2 += fts3GetVarint32(p2, &iCol2);
126275 /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
126276 ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
126277 ** end of the position list, or the 0x01 that precedes the next
126278 ** column-number in the position list.
126280 else if( iCol1<iCol2 ){
126281 fts3ColumnlistCopy(0, &p1);
126282 if( 0==*p1 ) break;
126283 p1++;
126284 p1 += fts3GetVarint32(p1, &iCol1);
126285 }else{
126286 fts3ColumnlistCopy(0, &p2);
126287 if( 0==*p2 ) break;
126288 p2++;
126289 p2 += fts3GetVarint32(p2, &iCol2);
126293 fts3PoslistCopy(0, &p2);
126294 fts3PoslistCopy(0, &p1);
126295 *pp1 = p1;
126296 *pp2 = p2;
126297 if( *pp==p ){
126298 return 0;
126300 *p++ = 0x00;
126301 *pp = p;
126302 return 1;
126306 ** Merge two position-lists as required by the NEAR operator. The argument
126307 ** position lists correspond to the left and right phrases of an expression
126308 ** like:
126310 ** "phrase 1" NEAR "phrase number 2"
126312 ** Position list *pp1 corresponds to the left-hand side of the NEAR
126313 ** expression and *pp2 to the right. As usual, the indexes in the position
126314 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
126315 ** in the example above).
126317 ** The output position list - written to *pp - is a copy of *pp2 with those
126318 ** entries that are not sufficiently NEAR entries in *pp1 removed.
126320 static int fts3PoslistNearMerge(
126321 char **pp, /* Output buffer */
126322 char *aTmp, /* Temporary buffer space */
126323 int nRight, /* Maximum difference in token positions */
126324 int nLeft, /* Maximum difference in token positions */
126325 char **pp1, /* IN/OUT: Left input list */
126326 char **pp2 /* IN/OUT: Right input list */
126328 char *p1 = *pp1;
126329 char *p2 = *pp2;
126331 char *pTmp1 = aTmp;
126332 char *pTmp2;
126333 char *aTmp2;
126334 int res = 1;
126336 fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
126337 aTmp2 = pTmp2 = pTmp1;
126338 *pp1 = p1;
126339 *pp2 = p2;
126340 fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
126341 if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
126342 fts3PoslistMerge(pp, &aTmp, &aTmp2);
126343 }else if( pTmp1!=aTmp ){
126344 fts3PoslistCopy(pp, &aTmp);
126345 }else if( pTmp2!=aTmp2 ){
126346 fts3PoslistCopy(pp, &aTmp2);
126347 }else{
126348 res = 0;
126351 return res;
126355 ** An instance of this function is used to merge together the (potentially
126356 ** large number of) doclists for each term that matches a prefix query.
126357 ** See function fts3TermSelectMerge() for details.
126359 typedef struct TermSelect TermSelect;
126360 struct TermSelect {
126361 char *aaOutput[16]; /* Malloc'd output buffers */
126362 int anOutput[16]; /* Size each output buffer in bytes */
126366 ** This function is used to read a single varint from a buffer. Parameter
126367 ** pEnd points 1 byte past the end of the buffer. When this function is
126368 ** called, if *pp points to pEnd or greater, then the end of the buffer
126369 ** has been reached. In this case *pp is set to 0 and the function returns.
126371 ** If *pp does not point to or past pEnd, then a single varint is read
126372 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
126374 ** If bDescIdx is false, the value read is added to *pVal before returning.
126375 ** If it is true, the value read is subtracted from *pVal before this
126376 ** function returns.
126378 static void fts3GetDeltaVarint3(
126379 char **pp, /* IN/OUT: Point to read varint from */
126380 char *pEnd, /* End of buffer */
126381 int bDescIdx, /* True if docids are descending */
126382 sqlite3_int64 *pVal /* IN/OUT: Integer value */
126384 if( *pp>=pEnd ){
126385 *pp = 0;
126386 }else{
126387 sqlite3_int64 iVal;
126388 *pp += sqlite3Fts3GetVarint(*pp, &iVal);
126389 if( bDescIdx ){
126390 *pVal -= iVal;
126391 }else{
126392 *pVal += iVal;
126398 ** This function is used to write a single varint to a buffer. The varint
126399 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
126400 ** end of the value written.
126402 ** If *pbFirst is zero when this function is called, the value written to
126403 ** the buffer is that of parameter iVal.
126405 ** If *pbFirst is non-zero when this function is called, then the value
126406 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
126407 ** (if bDescIdx is non-zero).
126409 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
126410 ** to the value of parameter iVal.
126412 static void fts3PutDeltaVarint3(
126413 char **pp, /* IN/OUT: Output pointer */
126414 int bDescIdx, /* True for descending docids */
126415 sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
126416 int *pbFirst, /* IN/OUT: True after first int written */
126417 sqlite3_int64 iVal /* Write this value to the list */
126419 sqlite3_int64 iWrite;
126420 if( bDescIdx==0 || *pbFirst==0 ){
126421 iWrite = iVal - *piPrev;
126422 }else{
126423 iWrite = *piPrev - iVal;
126425 assert( *pbFirst || *piPrev==0 );
126426 assert( *pbFirst==0 || iWrite>0 );
126427 *pp += sqlite3Fts3PutVarint(*pp, iWrite);
126428 *piPrev = iVal;
126429 *pbFirst = 1;
126434 ** This macro is used by various functions that merge doclists. The two
126435 ** arguments are 64-bit docid values. If the value of the stack variable
126436 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
126437 ** Otherwise, (i2-i1).
126439 ** Using this makes it easier to write code that can merge doclists that are
126440 ** sorted in either ascending or descending order.
126442 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
126445 ** This function does an "OR" merge of two doclists (output contains all
126446 ** positions contained in either argument doclist). If the docids in the
126447 ** input doclists are sorted in ascending order, parameter bDescDoclist
126448 ** should be false. If they are sorted in ascending order, it should be
126449 ** passed a non-zero value.
126451 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
126452 ** containing the output doclist and SQLITE_OK is returned. In this case
126453 ** *pnOut is set to the number of bytes in the output doclist.
126455 ** If an error occurs, an SQLite error code is returned. The output values
126456 ** are undefined in this case.
126458 static int fts3DoclistOrMerge(
126459 int bDescDoclist, /* True if arguments are desc */
126460 char *a1, int n1, /* First doclist */
126461 char *a2, int n2, /* Second doclist */
126462 char **paOut, int *pnOut /* OUT: Malloc'd doclist */
126464 sqlite3_int64 i1 = 0;
126465 sqlite3_int64 i2 = 0;
126466 sqlite3_int64 iPrev = 0;
126467 char *pEnd1 = &a1[n1];
126468 char *pEnd2 = &a2[n2];
126469 char *p1 = a1;
126470 char *p2 = a2;
126471 char *p;
126472 char *aOut;
126473 int bFirstOut = 0;
126475 *paOut = 0;
126476 *pnOut = 0;
126478 /* Allocate space for the output. Both the input and output doclists
126479 ** are delta encoded. If they are in ascending order (bDescDoclist==0),
126480 ** then the first docid in each list is simply encoded as a varint. For
126481 ** each subsequent docid, the varint stored is the difference between the
126482 ** current and previous docid (a positive number - since the list is in
126483 ** ascending order).
126485 ** The first docid written to the output is therefore encoded using the
126486 ** same number of bytes as it is in whichever of the input lists it is
126487 ** read from. And each subsequent docid read from the same input list
126488 ** consumes either the same or less bytes as it did in the input (since
126489 ** the difference between it and the previous value in the output must
126490 ** be a positive value less than or equal to the delta value read from
126491 ** the input list). The same argument applies to all but the first docid
126492 ** read from the 'other' list. And to the contents of all position lists
126493 ** that will be copied and merged from the input to the output.
126495 ** However, if the first docid copied to the output is a negative number,
126496 ** then the encoding of the first docid from the 'other' input list may
126497 ** be larger in the output than it was in the input (since the delta value
126498 ** may be a larger positive integer than the actual docid).
126500 ** The space required to store the output is therefore the sum of the
126501 ** sizes of the two inputs, plus enough space for exactly one of the input
126502 ** docids to grow.
126504 ** A symetric argument may be made if the doclists are in descending
126505 ** order.
126507 aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
126508 if( !aOut ) return SQLITE_NOMEM;
126510 p = aOut;
126511 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
126512 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
126513 while( p1 || p2 ){
126514 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
126516 if( p2 && p1 && iDiff==0 ){
126517 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
126518 fts3PoslistMerge(&p, &p1, &p2);
126519 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
126520 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
126521 }else if( !p2 || (p1 && iDiff<0) ){
126522 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
126523 fts3PoslistCopy(&p, &p1);
126524 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
126525 }else{
126526 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
126527 fts3PoslistCopy(&p, &p2);
126528 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
126532 *paOut = aOut;
126533 *pnOut = (int)(p-aOut);
126534 assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
126535 return SQLITE_OK;
126539 ** This function does a "phrase" merge of two doclists. In a phrase merge,
126540 ** the output contains a copy of each position from the right-hand input
126541 ** doclist for which there is a position in the left-hand input doclist
126542 ** exactly nDist tokens before it.
126544 ** If the docids in the input doclists are sorted in ascending order,
126545 ** parameter bDescDoclist should be false. If they are sorted in ascending
126546 ** order, it should be passed a non-zero value.
126548 ** The right-hand input doclist is overwritten by this function.
126550 static void fts3DoclistPhraseMerge(
126551 int bDescDoclist, /* True if arguments are desc */
126552 int nDist, /* Distance from left to right (1=adjacent) */
126553 char *aLeft, int nLeft, /* Left doclist */
126554 char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
126556 sqlite3_int64 i1 = 0;
126557 sqlite3_int64 i2 = 0;
126558 sqlite3_int64 iPrev = 0;
126559 char *pEnd1 = &aLeft[nLeft];
126560 char *pEnd2 = &aRight[*pnRight];
126561 char *p1 = aLeft;
126562 char *p2 = aRight;
126563 char *p;
126564 int bFirstOut = 0;
126565 char *aOut = aRight;
126567 assert( nDist>0 );
126569 p = aOut;
126570 fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
126571 fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
126573 while( p1 && p2 ){
126574 sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
126575 if( iDiff==0 ){
126576 char *pSave = p;
126577 sqlite3_int64 iPrevSave = iPrev;
126578 int bFirstOutSave = bFirstOut;
126580 fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
126581 if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
126582 p = pSave;
126583 iPrev = iPrevSave;
126584 bFirstOut = bFirstOutSave;
126586 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
126587 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
126588 }else if( iDiff<0 ){
126589 fts3PoslistCopy(0, &p1);
126590 fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
126591 }else{
126592 fts3PoslistCopy(0, &p2);
126593 fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
126597 *pnRight = (int)(p - aOut);
126601 ** Argument pList points to a position list nList bytes in size. This
126602 ** function checks to see if the position list contains any entries for
126603 ** a token in position 0 (of any column). If so, it writes argument iDelta
126604 ** to the output buffer pOut, followed by a position list consisting only
126605 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
126606 ** The value returned is the number of bytes written to pOut (if any).
126608 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
126609 sqlite3_int64 iDelta, /* Varint that may be written to pOut */
126610 char *pList, /* Position list (no 0x00 term) */
126611 int nList, /* Size of pList in bytes */
126612 char *pOut /* Write output here */
126614 int nOut = 0;
126615 int bWritten = 0; /* True once iDelta has been written */
126616 char *p = pList;
126617 char *pEnd = &pList[nList];
126619 if( *p!=0x01 ){
126620 if( *p==0x02 ){
126621 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
126622 pOut[nOut++] = 0x02;
126623 bWritten = 1;
126625 fts3ColumnlistCopy(0, &p);
126628 while( p<pEnd && *p==0x01 ){
126629 sqlite3_int64 iCol;
126631 p += sqlite3Fts3GetVarint(p, &iCol);
126632 if( *p==0x02 ){
126633 if( bWritten==0 ){
126634 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
126635 bWritten = 1;
126637 pOut[nOut++] = 0x01;
126638 nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
126639 pOut[nOut++] = 0x02;
126641 fts3ColumnlistCopy(0, &p);
126643 if( bWritten ){
126644 pOut[nOut++] = 0x00;
126647 return nOut;
126652 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
126653 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
126654 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
126656 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
126657 ** the responsibility of the caller to free any doclists left in the
126658 ** TermSelect.aaOutput[] array.
126660 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
126661 char *aOut = 0;
126662 int nOut = 0;
126663 int i;
126665 /* Loop through the doclists in the aaOutput[] array. Merge them all
126666 ** into a single doclist.
126668 for(i=0; i<SizeofArray(pTS->aaOutput); i++){
126669 if( pTS->aaOutput[i] ){
126670 if( !aOut ){
126671 aOut = pTS->aaOutput[i];
126672 nOut = pTS->anOutput[i];
126673 pTS->aaOutput[i] = 0;
126674 }else{
126675 int nNew;
126676 char *aNew;
126678 int rc = fts3DoclistOrMerge(p->bDescIdx,
126679 pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
126681 if( rc!=SQLITE_OK ){
126682 sqlite3_free(aOut);
126683 return rc;
126686 sqlite3_free(pTS->aaOutput[i]);
126687 sqlite3_free(aOut);
126688 pTS->aaOutput[i] = 0;
126689 aOut = aNew;
126690 nOut = nNew;
126695 pTS->aaOutput[0] = aOut;
126696 pTS->anOutput[0] = nOut;
126697 return SQLITE_OK;
126701 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
126702 ** as the first argument. The merge is an "OR" merge (see function
126703 ** fts3DoclistOrMerge() for details).
126705 ** This function is called with the doclist for each term that matches
126706 ** a queried prefix. It merges all these doclists into one, the doclist
126707 ** for the specified prefix. Since there can be a very large number of
126708 ** doclists to merge, the merging is done pair-wise using the TermSelect
126709 ** object.
126711 ** This function returns SQLITE_OK if the merge is successful, or an
126712 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
126714 static int fts3TermSelectMerge(
126715 Fts3Table *p, /* FTS table handle */
126716 TermSelect *pTS, /* TermSelect object to merge into */
126717 char *aDoclist, /* Pointer to doclist */
126718 int nDoclist /* Size of aDoclist in bytes */
126720 if( pTS->aaOutput[0]==0 ){
126721 /* If this is the first term selected, copy the doclist to the output
126722 ** buffer using memcpy(). */
126723 pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
126724 pTS->anOutput[0] = nDoclist;
126725 if( pTS->aaOutput[0] ){
126726 memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
126727 }else{
126728 return SQLITE_NOMEM;
126730 }else{
126731 char *aMerge = aDoclist;
126732 int nMerge = nDoclist;
126733 int iOut;
126735 for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
126736 if( pTS->aaOutput[iOut]==0 ){
126737 assert( iOut>0 );
126738 pTS->aaOutput[iOut] = aMerge;
126739 pTS->anOutput[iOut] = nMerge;
126740 break;
126741 }else{
126742 char *aNew;
126743 int nNew;
126745 int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
126746 pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
126748 if( rc!=SQLITE_OK ){
126749 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
126750 return rc;
126753 if( aMerge!=aDoclist ) sqlite3_free(aMerge);
126754 sqlite3_free(pTS->aaOutput[iOut]);
126755 pTS->aaOutput[iOut] = 0;
126757 aMerge = aNew;
126758 nMerge = nNew;
126759 if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
126760 pTS->aaOutput[iOut] = aMerge;
126761 pTS->anOutput[iOut] = nMerge;
126766 return SQLITE_OK;
126770 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
126772 static int fts3SegReaderCursorAppend(
126773 Fts3MultiSegReader *pCsr,
126774 Fts3SegReader *pNew
126776 if( (pCsr->nSegment%16)==0 ){
126777 Fts3SegReader **apNew;
126778 int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
126779 apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
126780 if( !apNew ){
126781 sqlite3Fts3SegReaderFree(pNew);
126782 return SQLITE_NOMEM;
126784 pCsr->apSegment = apNew;
126786 pCsr->apSegment[pCsr->nSegment++] = pNew;
126787 return SQLITE_OK;
126791 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
126792 ** 8th argument.
126794 ** This function returns SQLITE_OK if successful, or an SQLite error code
126795 ** otherwise.
126797 static int fts3SegReaderCursor(
126798 Fts3Table *p, /* FTS3 table handle */
126799 int iLangid, /* Language id */
126800 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
126801 int iLevel, /* Level of segments to scan */
126802 const char *zTerm, /* Term to query for */
126803 int nTerm, /* Size of zTerm in bytes */
126804 int isPrefix, /* True for a prefix search */
126805 int isScan, /* True to scan from zTerm to EOF */
126806 Fts3MultiSegReader *pCsr /* Cursor object to populate */
126808 int rc = SQLITE_OK; /* Error code */
126809 sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
126810 int rc2; /* Result of sqlite3_reset() */
126812 /* If iLevel is less than 0 and this is not a scan, include a seg-reader
126813 ** for the pending-terms. If this is a scan, then this call must be being
126814 ** made by an fts4aux module, not an FTS table. In this case calling
126815 ** Fts3SegReaderPending might segfault, as the data structures used by
126816 ** fts4aux are not completely populated. So it's easiest to filter these
126817 ** calls out here. */
126818 if( iLevel<0 && p->aIndex ){
126819 Fts3SegReader *pSeg = 0;
126820 rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
126821 if( rc==SQLITE_OK && pSeg ){
126822 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
126826 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
126827 if( rc==SQLITE_OK ){
126828 rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
126831 while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
126832 Fts3SegReader *pSeg = 0;
126834 /* Read the values returned by the SELECT into local variables. */
126835 sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
126836 sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
126837 sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
126838 int nRoot = sqlite3_column_bytes(pStmt, 4);
126839 char const *zRoot = sqlite3_column_blob(pStmt, 4);
126841 /* If zTerm is not NULL, and this segment is not stored entirely on its
126842 ** root node, the range of leaves scanned can be reduced. Do this. */
126843 if( iStartBlock && zTerm ){
126844 sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
126845 rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
126846 if( rc!=SQLITE_OK ) goto finished;
126847 if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
126850 rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
126851 (isPrefix==0 && isScan==0),
126852 iStartBlock, iLeavesEndBlock,
126853 iEndBlock, zRoot, nRoot, &pSeg
126855 if( rc!=SQLITE_OK ) goto finished;
126856 rc = fts3SegReaderCursorAppend(pCsr, pSeg);
126860 finished:
126861 rc2 = sqlite3_reset(pStmt);
126862 if( rc==SQLITE_DONE ) rc = rc2;
126864 return rc;
126868 ** Set up a cursor object for iterating through a full-text index or a
126869 ** single level therein.
126871 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
126872 Fts3Table *p, /* FTS3 table handle */
126873 int iLangid, /* Language-id to search */
126874 int iIndex, /* Index to search (from 0 to p->nIndex-1) */
126875 int iLevel, /* Level of segments to scan */
126876 const char *zTerm, /* Term to query for */
126877 int nTerm, /* Size of zTerm in bytes */
126878 int isPrefix, /* True for a prefix search */
126879 int isScan, /* True to scan from zTerm to EOF */
126880 Fts3MultiSegReader *pCsr /* Cursor object to populate */
126882 assert( iIndex>=0 && iIndex<p->nIndex );
126883 assert( iLevel==FTS3_SEGCURSOR_ALL
126884 || iLevel==FTS3_SEGCURSOR_PENDING
126885 || iLevel>=0
126887 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
126888 assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
126889 assert( isPrefix==0 || isScan==0 );
126891 memset(pCsr, 0, sizeof(Fts3MultiSegReader));
126892 return fts3SegReaderCursor(
126893 p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
126898 ** In addition to its current configuration, have the Fts3MultiSegReader
126899 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
126901 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
126903 static int fts3SegReaderCursorAddZero(
126904 Fts3Table *p, /* FTS virtual table handle */
126905 int iLangid,
126906 const char *zTerm, /* Term to scan doclist of */
126907 int nTerm, /* Number of bytes in zTerm */
126908 Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
126910 return fts3SegReaderCursor(p,
126911 iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
126916 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
126917 ** if isPrefix is true, to scan the doclist for all terms for which
126918 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
126919 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
126920 ** an SQLite error code.
126922 ** It is the responsibility of the caller to free this object by eventually
126923 ** passing it to fts3SegReaderCursorFree()
126925 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
126926 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
126928 static int fts3TermSegReaderCursor(
126929 Fts3Cursor *pCsr, /* Virtual table cursor handle */
126930 const char *zTerm, /* Term to query for */
126931 int nTerm, /* Size of zTerm in bytes */
126932 int isPrefix, /* True for a prefix search */
126933 Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
126935 Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
126936 int rc = SQLITE_NOMEM; /* Return code */
126938 pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
126939 if( pSegcsr ){
126940 int i;
126941 int bFound = 0; /* True once an index has been found */
126942 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
126944 if( isPrefix ){
126945 for(i=1; bFound==0 && i<p->nIndex; i++){
126946 if( p->aIndex[i].nPrefix==nTerm ){
126947 bFound = 1;
126948 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
126949 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
126951 pSegcsr->bLookup = 1;
126955 for(i=1; bFound==0 && i<p->nIndex; i++){
126956 if( p->aIndex[i].nPrefix==nTerm+1 ){
126957 bFound = 1;
126958 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
126959 i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
126961 if( rc==SQLITE_OK ){
126962 rc = fts3SegReaderCursorAddZero(
126963 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
126970 if( bFound==0 ){
126971 rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
126972 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
126974 pSegcsr->bLookup = !isPrefix;
126978 *ppSegcsr = pSegcsr;
126979 return rc;
126983 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
126985 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
126986 sqlite3Fts3SegReaderFinish(pSegcsr);
126987 sqlite3_free(pSegcsr);
126991 ** This function retrieves the doclist for the specified term (or term
126992 ** prefix) from the database.
126994 static int fts3TermSelect(
126995 Fts3Table *p, /* Virtual table handle */
126996 Fts3PhraseToken *pTok, /* Token to query for */
126997 int iColumn, /* Column to query (or -ve for all columns) */
126998 int *pnOut, /* OUT: Size of buffer at *ppOut */
126999 char **ppOut /* OUT: Malloced result buffer */
127001 int rc; /* Return code */
127002 Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
127003 TermSelect tsc; /* Object for pair-wise doclist merging */
127004 Fts3SegFilter filter; /* Segment term filter configuration */
127006 pSegcsr = pTok->pSegcsr;
127007 memset(&tsc, 0, sizeof(TermSelect));
127009 filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
127010 | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
127011 | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
127012 | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
127013 filter.iCol = iColumn;
127014 filter.zTerm = pTok->z;
127015 filter.nTerm = pTok->n;
127017 rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
127018 while( SQLITE_OK==rc
127019 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
127021 rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
127024 if( rc==SQLITE_OK ){
127025 rc = fts3TermSelectFinishMerge(p, &tsc);
127027 if( rc==SQLITE_OK ){
127028 *ppOut = tsc.aaOutput[0];
127029 *pnOut = tsc.anOutput[0];
127030 }else{
127031 int i;
127032 for(i=0; i<SizeofArray(tsc.aaOutput); i++){
127033 sqlite3_free(tsc.aaOutput[i]);
127037 fts3SegReaderCursorFree(pSegcsr);
127038 pTok->pSegcsr = 0;
127039 return rc;
127043 ** This function counts the total number of docids in the doclist stored
127044 ** in buffer aList[], size nList bytes.
127046 ** If the isPoslist argument is true, then it is assumed that the doclist
127047 ** contains a position-list following each docid. Otherwise, it is assumed
127048 ** that the doclist is simply a list of docids stored as delta encoded
127049 ** varints.
127051 static int fts3DoclistCountDocids(char *aList, int nList){
127052 int nDoc = 0; /* Return value */
127053 if( aList ){
127054 char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
127055 char *p = aList; /* Cursor */
127056 while( p<aEnd ){
127057 nDoc++;
127058 while( (*p++)&0x80 ); /* Skip docid varint */
127059 fts3PoslistCopy(0, &p); /* Skip over position list */
127063 return nDoc;
127067 ** Advance the cursor to the next row in the %_content table that
127068 ** matches the search criteria. For a MATCH search, this will be
127069 ** the next row that matches. For a full-table scan, this will be
127070 ** simply the next row in the %_content table. For a docid lookup,
127071 ** this routine simply sets the EOF flag.
127073 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
127074 ** even if we reach end-of-file. The fts3EofMethod() will be called
127075 ** subsequently to determine whether or not an EOF was hit.
127077 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
127078 int rc;
127079 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
127080 if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
127081 if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
127082 pCsr->isEof = 1;
127083 rc = sqlite3_reset(pCsr->pStmt);
127084 }else{
127085 pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
127086 rc = SQLITE_OK;
127088 }else{
127089 rc = fts3EvalNext((Fts3Cursor *)pCursor);
127091 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
127092 return rc;
127096 ** The following are copied from sqliteInt.h.
127098 ** Constants for the largest and smallest possible 64-bit signed integers.
127099 ** These macros are designed to work correctly on both 32-bit and 64-bit
127100 ** compilers.
127102 #ifndef SQLITE_AMALGAMATION
127103 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
127104 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
127105 #endif
127108 ** If the numeric type of argument pVal is "integer", then return it
127109 ** converted to a 64-bit signed integer. Otherwise, return a copy of
127110 ** the second parameter, iDefault.
127112 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
127113 if( pVal ){
127114 int eType = sqlite3_value_numeric_type(pVal);
127115 if( eType==SQLITE_INTEGER ){
127116 return sqlite3_value_int64(pVal);
127119 return iDefault;
127123 ** This is the xFilter interface for the virtual table. See
127124 ** the virtual table xFilter method documentation for additional
127125 ** information.
127127 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
127128 ** the %_content table.
127130 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
127131 ** in the %_content table.
127133 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
127134 ** column on the left-hand side of the MATCH operator is column
127135 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
127136 ** side of the MATCH operator.
127138 static int fts3FilterMethod(
127139 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
127140 int idxNum, /* Strategy index */
127141 const char *idxStr, /* Unused */
127142 int nVal, /* Number of elements in apVal */
127143 sqlite3_value **apVal /* Arguments for the indexing scheme */
127145 int rc;
127146 char *zSql; /* SQL statement used to access %_content */
127147 int eSearch;
127148 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
127149 Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
127151 sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
127152 sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
127153 sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
127154 sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
127155 int iIdx;
127157 UNUSED_PARAMETER(idxStr);
127158 UNUSED_PARAMETER(nVal);
127160 eSearch = (idxNum & 0x0000FFFF);
127161 assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
127162 assert( p->pSegments==0 );
127164 /* Collect arguments into local variables */
127165 iIdx = 0;
127166 if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
127167 if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
127168 if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
127169 if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
127170 assert( iIdx==nVal );
127172 /* In case the cursor has been used before, clear it now. */
127173 sqlite3_finalize(pCsr->pStmt);
127174 sqlite3_free(pCsr->aDoclist);
127175 sqlite3Fts3ExprFree(pCsr->pExpr);
127176 memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
127178 /* Set the lower and upper bounds on docids to return */
127179 pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
127180 pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
127182 if( idxStr ){
127183 pCsr->bDesc = (idxStr[0]=='D');
127184 }else{
127185 pCsr->bDesc = p->bDescIdx;
127187 pCsr->eSearch = (i16)eSearch;
127189 if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
127190 int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
127191 const char *zQuery = (const char *)sqlite3_value_text(pCons);
127193 if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
127194 return SQLITE_NOMEM;
127197 pCsr->iLangid = 0;
127198 if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
127200 assert( p->base.zErrMsg==0 );
127201 rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
127202 p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
127203 &p->base.zErrMsg
127205 if( rc!=SQLITE_OK ){
127206 return rc;
127209 rc = fts3EvalStart(pCsr);
127210 sqlite3Fts3SegmentsClose(p);
127211 if( rc!=SQLITE_OK ) return rc;
127212 pCsr->pNextId = pCsr->aDoclist;
127213 pCsr->iPrevId = 0;
127216 /* Compile a SELECT statement for this cursor. For a full-table-scan, the
127217 ** statement loops through all rows of the %_content table. For a
127218 ** full-text query or docid lookup, the statement retrieves a single
127219 ** row by docid.
127221 if( eSearch==FTS3_FULLSCAN_SEARCH ){
127222 zSql = sqlite3_mprintf(
127223 "SELECT %s ORDER BY rowid %s",
127224 p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
127226 if( zSql ){
127227 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
127228 sqlite3_free(zSql);
127229 }else{
127230 rc = SQLITE_NOMEM;
127232 }else if( eSearch==FTS3_DOCID_SEARCH ){
127233 rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
127234 if( rc==SQLITE_OK ){
127235 rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
127238 if( rc!=SQLITE_OK ) return rc;
127240 return fts3NextMethod(pCursor);
127244 ** This is the xEof method of the virtual table. SQLite calls this
127245 ** routine to find out if it has reached the end of a result set.
127247 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
127248 return ((Fts3Cursor *)pCursor)->isEof;
127252 ** This is the xRowid method. The SQLite core calls this routine to
127253 ** retrieve the rowid for the current row of the result set. fts3
127254 ** exposes %_content.docid as the rowid for the virtual table. The
127255 ** rowid should be written to *pRowid.
127257 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
127258 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
127259 *pRowid = pCsr->iPrevId;
127260 return SQLITE_OK;
127264 ** This is the xColumn method, called by SQLite to request a value from
127265 ** the row that the supplied cursor currently points to.
127267 ** If:
127269 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
127270 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
127271 ** (iCol == p->nColumn+1) -> Docid column
127272 ** (iCol == p->nColumn+2) -> Langid column
127274 static int fts3ColumnMethod(
127275 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
127276 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
127277 int iCol /* Index of column to read value from */
127279 int rc = SQLITE_OK; /* Return Code */
127280 Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
127281 Fts3Table *p = (Fts3Table *)pCursor->pVtab;
127283 /* The column value supplied by SQLite must be in range. */
127284 assert( iCol>=0 && iCol<=p->nColumn+2 );
127286 if( iCol==p->nColumn+1 ){
127287 /* This call is a request for the "docid" column. Since "docid" is an
127288 ** alias for "rowid", use the xRowid() method to obtain the value.
127290 sqlite3_result_int64(pCtx, pCsr->iPrevId);
127291 }else if( iCol==p->nColumn ){
127292 /* The extra column whose name is the same as the table.
127293 ** Return a blob which is a pointer to the cursor. */
127294 sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
127295 }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
127296 sqlite3_result_int64(pCtx, pCsr->iLangid);
127297 }else{
127298 /* The requested column is either a user column (one that contains
127299 ** indexed data), or the language-id column. */
127300 rc = fts3CursorSeek(0, pCsr);
127302 if( rc==SQLITE_OK ){
127303 if( iCol==p->nColumn+2 ){
127304 int iLangid = 0;
127305 if( p->zLanguageid ){
127306 iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
127308 sqlite3_result_int(pCtx, iLangid);
127309 }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
127310 sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
127315 assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
127316 return rc;
127320 ** This function is the implementation of the xUpdate callback used by
127321 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
127322 ** inserted, updated or deleted.
127324 static int fts3UpdateMethod(
127325 sqlite3_vtab *pVtab, /* Virtual table handle */
127326 int nArg, /* Size of argument array */
127327 sqlite3_value **apVal, /* Array of arguments */
127328 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
127330 return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
127334 ** Implementation of xSync() method. Flush the contents of the pending-terms
127335 ** hash-table to the database.
127337 static int fts3SyncMethod(sqlite3_vtab *pVtab){
127339 /* Following an incremental-merge operation, assuming that the input
127340 ** segments are not completely consumed (the usual case), they are updated
127341 ** in place to remove the entries that have already been merged. This
127342 ** involves updating the leaf block that contains the smallest unmerged
127343 ** entry and each block (if any) between the leaf and the root node. So
127344 ** if the height of the input segment b-trees is N, and input segments
127345 ** are merged eight at a time, updating the input segments at the end
127346 ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
127347 ** small - often between 0 and 2. So the overhead of the incremental
127348 ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
127349 ** dwarfing the actual productive work accomplished, the incremental merge
127350 ** is only attempted if it will write at least 64 leaf blocks. Hence
127351 ** nMinMerge.
127353 ** Of course, updating the input segments also involves deleting a bunch
127354 ** of blocks from the segments table. But this is not considered overhead
127355 ** as it would also be required by a crisis-merge that used the same input
127356 ** segments.
127358 const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
127360 Fts3Table *p = (Fts3Table*)pVtab;
127361 int rc = sqlite3Fts3PendingTermsFlush(p);
127363 if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
127364 int mxLevel = 0; /* Maximum relative level value in db */
127365 int A; /* Incr-merge parameter A */
127367 rc = sqlite3Fts3MaxLevel(p, &mxLevel);
127368 assert( rc==SQLITE_OK || mxLevel==0 );
127369 A = p->nLeafAdd * mxLevel;
127370 A += (A/2);
127371 if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
127373 sqlite3Fts3SegmentsClose(p);
127374 return rc;
127378 ** Implementation of xBegin() method. This is a no-op.
127380 static int fts3BeginMethod(sqlite3_vtab *pVtab){
127381 Fts3Table *p = (Fts3Table*)pVtab;
127382 UNUSED_PARAMETER(pVtab);
127383 assert( p->pSegments==0 );
127384 assert( p->nPendingData==0 );
127385 assert( p->inTransaction!=1 );
127386 TESTONLY( p->inTransaction = 1 );
127387 TESTONLY( p->mxSavepoint = -1; );
127388 p->nLeafAdd = 0;
127389 return SQLITE_OK;
127393 ** Implementation of xCommit() method. This is a no-op. The contents of
127394 ** the pending-terms hash-table have already been flushed into the database
127395 ** by fts3SyncMethod().
127397 static int fts3CommitMethod(sqlite3_vtab *pVtab){
127398 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
127399 UNUSED_PARAMETER(pVtab);
127400 assert( p->nPendingData==0 );
127401 assert( p->inTransaction!=0 );
127402 assert( p->pSegments==0 );
127403 TESTONLY( p->inTransaction = 0 );
127404 TESTONLY( p->mxSavepoint = -1; );
127405 return SQLITE_OK;
127409 ** Implementation of xRollback(). Discard the contents of the pending-terms
127410 ** hash-table. Any changes made to the database are reverted by SQLite.
127412 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
127413 Fts3Table *p = (Fts3Table*)pVtab;
127414 sqlite3Fts3PendingTermsClear(p);
127415 assert( p->inTransaction!=0 );
127416 TESTONLY( p->inTransaction = 0 );
127417 TESTONLY( p->mxSavepoint = -1; );
127418 return SQLITE_OK;
127422 ** When called, *ppPoslist must point to the byte immediately following the
127423 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
127424 ** moves *ppPoslist so that it instead points to the first byte of the
127425 ** same position list.
127427 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
127428 char *p = &(*ppPoslist)[-2];
127429 char c = 0;
127431 while( p>pStart && (c=*p--)==0 );
127432 while( p>pStart && (*p & 0x80) | c ){
127433 c = *p--;
127435 if( p>pStart ){ p = &p[2]; }
127436 while( *p++&0x80 );
127437 *ppPoslist = p;
127441 ** Helper function used by the implementation of the overloaded snippet(),
127442 ** offsets() and optimize() SQL functions.
127444 ** If the value passed as the third argument is a blob of size
127445 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
127446 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
127447 ** message is written to context pContext and SQLITE_ERROR returned. The
127448 ** string passed via zFunc is used as part of the error message.
127450 static int fts3FunctionArg(
127451 sqlite3_context *pContext, /* SQL function call context */
127452 const char *zFunc, /* Function name */
127453 sqlite3_value *pVal, /* argv[0] passed to function */
127454 Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
127456 Fts3Cursor *pRet;
127457 if( sqlite3_value_type(pVal)!=SQLITE_BLOB
127458 || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
127460 char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
127461 sqlite3_result_error(pContext, zErr, -1);
127462 sqlite3_free(zErr);
127463 return SQLITE_ERROR;
127465 memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
127466 *ppCsr = pRet;
127467 return SQLITE_OK;
127471 ** Implementation of the snippet() function for FTS3
127473 static void fts3SnippetFunc(
127474 sqlite3_context *pContext, /* SQLite function call context */
127475 int nVal, /* Size of apVal[] array */
127476 sqlite3_value **apVal /* Array of arguments */
127478 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
127479 const char *zStart = "<b>";
127480 const char *zEnd = "</b>";
127481 const char *zEllipsis = "<b>...</b>";
127482 int iCol = -1;
127483 int nToken = 15; /* Default number of tokens in snippet */
127485 /* There must be at least one argument passed to this function (otherwise
127486 ** the non-overloaded version would have been called instead of this one).
127488 assert( nVal>=1 );
127490 if( nVal>6 ){
127491 sqlite3_result_error(pContext,
127492 "wrong number of arguments to function snippet()", -1);
127493 return;
127495 if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
127497 switch( nVal ){
127498 case 6: nToken = sqlite3_value_int(apVal[5]);
127499 case 5: iCol = sqlite3_value_int(apVal[4]);
127500 case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
127501 case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
127502 case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
127504 if( !zEllipsis || !zEnd || !zStart ){
127505 sqlite3_result_error_nomem(pContext);
127506 }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
127507 sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
127512 ** Implementation of the offsets() function for FTS3
127514 static void fts3OffsetsFunc(
127515 sqlite3_context *pContext, /* SQLite function call context */
127516 int nVal, /* Size of argument array */
127517 sqlite3_value **apVal /* Array of arguments */
127519 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
127521 UNUSED_PARAMETER(nVal);
127523 assert( nVal==1 );
127524 if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
127525 assert( pCsr );
127526 if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
127527 sqlite3Fts3Offsets(pContext, pCsr);
127532 ** Implementation of the special optimize() function for FTS3. This
127533 ** function merges all segments in the database to a single segment.
127534 ** Example usage is:
127536 ** SELECT optimize(t) FROM t LIMIT 1;
127538 ** where 't' is the name of an FTS3 table.
127540 static void fts3OptimizeFunc(
127541 sqlite3_context *pContext, /* SQLite function call context */
127542 int nVal, /* Size of argument array */
127543 sqlite3_value **apVal /* Array of arguments */
127545 int rc; /* Return code */
127546 Fts3Table *p; /* Virtual table handle */
127547 Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
127549 UNUSED_PARAMETER(nVal);
127551 assert( nVal==1 );
127552 if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
127553 p = (Fts3Table *)pCursor->base.pVtab;
127554 assert( p );
127556 rc = sqlite3Fts3Optimize(p);
127558 switch( rc ){
127559 case SQLITE_OK:
127560 sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
127561 break;
127562 case SQLITE_DONE:
127563 sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
127564 break;
127565 default:
127566 sqlite3_result_error_code(pContext, rc);
127567 break;
127572 ** Implementation of the matchinfo() function for FTS3
127574 static void fts3MatchinfoFunc(
127575 sqlite3_context *pContext, /* SQLite function call context */
127576 int nVal, /* Size of argument array */
127577 sqlite3_value **apVal /* Array of arguments */
127579 Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
127580 assert( nVal==1 || nVal==2 );
127581 if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
127582 const char *zArg = 0;
127583 if( nVal>1 ){
127584 zArg = (const char *)sqlite3_value_text(apVal[1]);
127586 sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
127591 ** This routine implements the xFindFunction method for the FTS3
127592 ** virtual table.
127594 static int fts3FindFunctionMethod(
127595 sqlite3_vtab *pVtab, /* Virtual table handle */
127596 int nArg, /* Number of SQL function arguments */
127597 const char *zName, /* Name of SQL function */
127598 void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
127599 void **ppArg /* Unused */
127601 struct Overloaded {
127602 const char *zName;
127603 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
127604 } aOverload[] = {
127605 { "snippet", fts3SnippetFunc },
127606 { "offsets", fts3OffsetsFunc },
127607 { "optimize", fts3OptimizeFunc },
127608 { "matchinfo", fts3MatchinfoFunc },
127610 int i; /* Iterator variable */
127612 UNUSED_PARAMETER(pVtab);
127613 UNUSED_PARAMETER(nArg);
127614 UNUSED_PARAMETER(ppArg);
127616 for(i=0; i<SizeofArray(aOverload); i++){
127617 if( strcmp(zName, aOverload[i].zName)==0 ){
127618 *pxFunc = aOverload[i].xFunc;
127619 return 1;
127623 /* No function of the specified name was found. Return 0. */
127624 return 0;
127628 ** Implementation of FTS3 xRename method. Rename an fts3 table.
127630 static int fts3RenameMethod(
127631 sqlite3_vtab *pVtab, /* Virtual table handle */
127632 const char *zName /* New name of table */
127634 Fts3Table *p = (Fts3Table *)pVtab;
127635 sqlite3 *db = p->db; /* Database connection */
127636 int rc; /* Return Code */
127638 /* As it happens, the pending terms table is always empty here. This is
127639 ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
127640 ** always opens a savepoint transaction. And the xSavepoint() method
127641 ** flushes the pending terms table. But leave the (no-op) call to
127642 ** PendingTermsFlush() in in case that changes.
127644 assert( p->nPendingData==0 );
127645 rc = sqlite3Fts3PendingTermsFlush(p);
127647 if( p->zContentTbl==0 ){
127648 fts3DbExec(&rc, db,
127649 "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
127650 p->zDb, p->zName, zName
127654 if( p->bHasDocsize ){
127655 fts3DbExec(&rc, db,
127656 "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
127657 p->zDb, p->zName, zName
127660 if( p->bHasStat ){
127661 fts3DbExec(&rc, db,
127662 "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
127663 p->zDb, p->zName, zName
127666 fts3DbExec(&rc, db,
127667 "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
127668 p->zDb, p->zName, zName
127670 fts3DbExec(&rc, db,
127671 "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
127672 p->zDb, p->zName, zName
127674 return rc;
127678 ** The xSavepoint() method.
127680 ** Flush the contents of the pending-terms table to disk.
127682 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
127683 int rc = SQLITE_OK;
127684 UNUSED_PARAMETER(iSavepoint);
127685 assert( ((Fts3Table *)pVtab)->inTransaction );
127686 assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
127687 TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
127688 if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
127689 rc = fts3SyncMethod(pVtab);
127691 return rc;
127695 ** The xRelease() method.
127697 ** This is a no-op.
127699 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
127700 TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
127701 UNUSED_PARAMETER(iSavepoint);
127702 UNUSED_PARAMETER(pVtab);
127703 assert( p->inTransaction );
127704 assert( p->mxSavepoint >= iSavepoint );
127705 TESTONLY( p->mxSavepoint = iSavepoint-1 );
127706 return SQLITE_OK;
127710 ** The xRollbackTo() method.
127712 ** Discard the contents of the pending terms table.
127714 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
127715 Fts3Table *p = (Fts3Table*)pVtab;
127716 UNUSED_PARAMETER(iSavepoint);
127717 assert( p->inTransaction );
127718 assert( p->mxSavepoint >= iSavepoint );
127719 TESTONLY( p->mxSavepoint = iSavepoint );
127720 sqlite3Fts3PendingTermsClear(p);
127721 return SQLITE_OK;
127724 static const sqlite3_module fts3Module = {
127725 /* iVersion */ 2,
127726 /* xCreate */ fts3CreateMethod,
127727 /* xConnect */ fts3ConnectMethod,
127728 /* xBestIndex */ fts3BestIndexMethod,
127729 /* xDisconnect */ fts3DisconnectMethod,
127730 /* xDestroy */ fts3DestroyMethod,
127731 /* xOpen */ fts3OpenMethod,
127732 /* xClose */ fts3CloseMethod,
127733 /* xFilter */ fts3FilterMethod,
127734 /* xNext */ fts3NextMethod,
127735 /* xEof */ fts3EofMethod,
127736 /* xColumn */ fts3ColumnMethod,
127737 /* xRowid */ fts3RowidMethod,
127738 /* xUpdate */ fts3UpdateMethod,
127739 /* xBegin */ fts3BeginMethod,
127740 /* xSync */ fts3SyncMethod,
127741 /* xCommit */ fts3CommitMethod,
127742 /* xRollback */ fts3RollbackMethod,
127743 /* xFindFunction */ fts3FindFunctionMethod,
127744 /* xRename */ fts3RenameMethod,
127745 /* xSavepoint */ fts3SavepointMethod,
127746 /* xRelease */ fts3ReleaseMethod,
127747 /* xRollbackTo */ fts3RollbackToMethod,
127751 ** This function is registered as the module destructor (called when an
127752 ** FTS3 enabled database connection is closed). It frees the memory
127753 ** allocated for the tokenizer hash table.
127755 static void hashDestroy(void *p){
127756 Fts3Hash *pHash = (Fts3Hash *)p;
127757 sqlite3Fts3HashClear(pHash);
127758 sqlite3_free(pHash);
127762 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
127763 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
127764 ** respectively. The following three forward declarations are for functions
127765 ** declared in these files used to retrieve the respective implementations.
127767 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
127768 ** to by the argument to point to the "simple" tokenizer implementation.
127769 ** And so on.
127771 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
127772 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
127773 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
127774 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
127775 #endif
127776 #ifdef SQLITE_ENABLE_ICU
127777 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
127778 #endif
127781 ** Initialize the fts3 extension. If this extension is built as part
127782 ** of the sqlite library, then this function is called directly by
127783 ** SQLite. If fts3 is built as a dynamically loadable extension, this
127784 ** function is called by the sqlite3_extension_init() entry point.
127786 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
127787 int rc = SQLITE_OK;
127788 Fts3Hash *pHash = 0;
127789 const sqlite3_tokenizer_module *pSimple = 0;
127790 const sqlite3_tokenizer_module *pPorter = 0;
127791 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
127792 const sqlite3_tokenizer_module *pUnicode = 0;
127793 #endif
127795 #ifdef SQLITE_ENABLE_ICU
127796 const sqlite3_tokenizer_module *pIcu = 0;
127797 sqlite3Fts3IcuTokenizerModule(&pIcu);
127798 #endif
127800 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
127801 sqlite3Fts3UnicodeTokenizer(&pUnicode);
127802 #endif
127804 #ifdef SQLITE_TEST
127805 rc = sqlite3Fts3InitTerm(db);
127806 if( rc!=SQLITE_OK ) return rc;
127807 #endif
127809 rc = sqlite3Fts3InitAux(db);
127810 if( rc!=SQLITE_OK ) return rc;
127812 sqlite3Fts3SimpleTokenizerModule(&pSimple);
127813 sqlite3Fts3PorterTokenizerModule(&pPorter);
127815 /* Allocate and initialize the hash-table used to store tokenizers. */
127816 pHash = sqlite3_malloc(sizeof(Fts3Hash));
127817 if( !pHash ){
127818 rc = SQLITE_NOMEM;
127819 }else{
127820 sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
127823 /* Load the built-in tokenizers into the hash table */
127824 if( rc==SQLITE_OK ){
127825 if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
127826 || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
127828 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
127829 || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
127830 #endif
127831 #ifdef SQLITE_ENABLE_ICU
127832 || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
127833 #endif
127835 rc = SQLITE_NOMEM;
127839 #ifdef SQLITE_TEST
127840 if( rc==SQLITE_OK ){
127841 rc = sqlite3Fts3ExprInitTestInterface(db);
127843 #endif
127845 /* Create the virtual table wrapper around the hash-table and overload
127846 ** the two scalar functions. If this is successful, register the
127847 ** module with sqlite.
127849 if( SQLITE_OK==rc
127850 && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
127851 && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
127852 && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
127853 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
127854 && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
127855 && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
127857 rc = sqlite3_create_module_v2(
127858 db, "fts3", &fts3Module, (void *)pHash, hashDestroy
127860 if( rc==SQLITE_OK ){
127861 rc = sqlite3_create_module_v2(
127862 db, "fts4", &fts3Module, (void *)pHash, 0
127865 if( rc==SQLITE_OK ){
127866 rc = sqlite3Fts3InitTok(db, (void *)pHash);
127868 return rc;
127872 /* An error has occurred. Delete the hash table and return the error code. */
127873 assert( rc!=SQLITE_OK );
127874 if( pHash ){
127875 sqlite3Fts3HashClear(pHash);
127876 sqlite3_free(pHash);
127878 return rc;
127882 ** Allocate an Fts3MultiSegReader for each token in the expression headed
127883 ** by pExpr.
127885 ** An Fts3SegReader object is a cursor that can seek or scan a range of
127886 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
127887 ** Fts3SegReader objects internally to provide an interface to seek or scan
127888 ** within the union of all segments of a b-tree. Hence the name.
127890 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
127891 ** segment b-tree (if the term is not a prefix or it is a prefix for which
127892 ** there exists prefix b-tree of the right length) then it may be traversed
127893 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
127894 ** doclist and then traversed.
127896 static void fts3EvalAllocateReaders(
127897 Fts3Cursor *pCsr, /* FTS cursor handle */
127898 Fts3Expr *pExpr, /* Allocate readers for this expression */
127899 int *pnToken, /* OUT: Total number of tokens in phrase. */
127900 int *pnOr, /* OUT: Total number of OR nodes in expr. */
127901 int *pRc /* IN/OUT: Error code */
127903 if( pExpr && SQLITE_OK==*pRc ){
127904 if( pExpr->eType==FTSQUERY_PHRASE ){
127905 int i;
127906 int nToken = pExpr->pPhrase->nToken;
127907 *pnToken += nToken;
127908 for(i=0; i<nToken; i++){
127909 Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
127910 int rc = fts3TermSegReaderCursor(pCsr,
127911 pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
127913 if( rc!=SQLITE_OK ){
127914 *pRc = rc;
127915 return;
127918 assert( pExpr->pPhrase->iDoclistToken==0 );
127919 pExpr->pPhrase->iDoclistToken = -1;
127920 }else{
127921 *pnOr += (pExpr->eType==FTSQUERY_OR);
127922 fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
127923 fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
127929 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
127930 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
127932 ** This function assumes that pList points to a buffer allocated using
127933 ** sqlite3_malloc(). This function takes responsibility for eventually
127934 ** freeing the buffer.
127936 static void fts3EvalPhraseMergeToken(
127937 Fts3Table *pTab, /* FTS Table pointer */
127938 Fts3Phrase *p, /* Phrase to merge pList/nList into */
127939 int iToken, /* Token pList/nList corresponds to */
127940 char *pList, /* Pointer to doclist */
127941 int nList /* Number of bytes in pList */
127943 assert( iToken!=p->iDoclistToken );
127945 if( pList==0 ){
127946 sqlite3_free(p->doclist.aAll);
127947 p->doclist.aAll = 0;
127948 p->doclist.nAll = 0;
127951 else if( p->iDoclistToken<0 ){
127952 p->doclist.aAll = pList;
127953 p->doclist.nAll = nList;
127956 else if( p->doclist.aAll==0 ){
127957 sqlite3_free(pList);
127960 else {
127961 char *pLeft;
127962 char *pRight;
127963 int nLeft;
127964 int nRight;
127965 int nDiff;
127967 if( p->iDoclistToken<iToken ){
127968 pLeft = p->doclist.aAll;
127969 nLeft = p->doclist.nAll;
127970 pRight = pList;
127971 nRight = nList;
127972 nDiff = iToken - p->iDoclistToken;
127973 }else{
127974 pRight = p->doclist.aAll;
127975 nRight = p->doclist.nAll;
127976 pLeft = pList;
127977 nLeft = nList;
127978 nDiff = p->iDoclistToken - iToken;
127981 fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
127982 sqlite3_free(pLeft);
127983 p->doclist.aAll = pRight;
127984 p->doclist.nAll = nRight;
127987 if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
127991 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
127992 ** does not take deferred tokens into account.
127994 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
127996 static int fts3EvalPhraseLoad(
127997 Fts3Cursor *pCsr, /* FTS Cursor handle */
127998 Fts3Phrase *p /* Phrase object */
128000 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128001 int iToken;
128002 int rc = SQLITE_OK;
128004 for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
128005 Fts3PhraseToken *pToken = &p->aToken[iToken];
128006 assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
128008 if( pToken->pSegcsr ){
128009 int nThis = 0;
128010 char *pThis = 0;
128011 rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
128012 if( rc==SQLITE_OK ){
128013 fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
128016 assert( pToken->pSegcsr==0 );
128019 return rc;
128023 ** This function is called on each phrase after the position lists for
128024 ** any deferred tokens have been loaded into memory. It updates the phrases
128025 ** current position list to include only those positions that are really
128026 ** instances of the phrase (after considering deferred tokens). If this
128027 ** means that the phrase does not appear in the current row, doclist.pList
128028 ** and doclist.nList are both zeroed.
128030 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
128032 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
128033 int iToken; /* Used to iterate through phrase tokens */
128034 char *aPoslist = 0; /* Position list for deferred tokens */
128035 int nPoslist = 0; /* Number of bytes in aPoslist */
128036 int iPrev = -1; /* Token number of previous deferred token */
128038 assert( pPhrase->doclist.bFreeList==0 );
128040 for(iToken=0; iToken<pPhrase->nToken; iToken++){
128041 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
128042 Fts3DeferredToken *pDeferred = pToken->pDeferred;
128044 if( pDeferred ){
128045 char *pList;
128046 int nList;
128047 int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
128048 if( rc!=SQLITE_OK ) return rc;
128050 if( pList==0 ){
128051 sqlite3_free(aPoslist);
128052 pPhrase->doclist.pList = 0;
128053 pPhrase->doclist.nList = 0;
128054 return SQLITE_OK;
128056 }else if( aPoslist==0 ){
128057 aPoslist = pList;
128058 nPoslist = nList;
128060 }else{
128061 char *aOut = pList;
128062 char *p1 = aPoslist;
128063 char *p2 = aOut;
128065 assert( iPrev>=0 );
128066 fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
128067 sqlite3_free(aPoslist);
128068 aPoslist = pList;
128069 nPoslist = (int)(aOut - aPoslist);
128070 if( nPoslist==0 ){
128071 sqlite3_free(aPoslist);
128072 pPhrase->doclist.pList = 0;
128073 pPhrase->doclist.nList = 0;
128074 return SQLITE_OK;
128077 iPrev = iToken;
128081 if( iPrev>=0 ){
128082 int nMaxUndeferred = pPhrase->iDoclistToken;
128083 if( nMaxUndeferred<0 ){
128084 pPhrase->doclist.pList = aPoslist;
128085 pPhrase->doclist.nList = nPoslist;
128086 pPhrase->doclist.iDocid = pCsr->iPrevId;
128087 pPhrase->doclist.bFreeList = 1;
128088 }else{
128089 int nDistance;
128090 char *p1;
128091 char *p2;
128092 char *aOut;
128094 if( nMaxUndeferred>iPrev ){
128095 p1 = aPoslist;
128096 p2 = pPhrase->doclist.pList;
128097 nDistance = nMaxUndeferred - iPrev;
128098 }else{
128099 p1 = pPhrase->doclist.pList;
128100 p2 = aPoslist;
128101 nDistance = iPrev - nMaxUndeferred;
128104 aOut = (char *)sqlite3_malloc(nPoslist+8);
128105 if( !aOut ){
128106 sqlite3_free(aPoslist);
128107 return SQLITE_NOMEM;
128110 pPhrase->doclist.pList = aOut;
128111 if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
128112 pPhrase->doclist.bFreeList = 1;
128113 pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
128114 }else{
128115 sqlite3_free(aOut);
128116 pPhrase->doclist.pList = 0;
128117 pPhrase->doclist.nList = 0;
128119 sqlite3_free(aPoslist);
128123 return SQLITE_OK;
128127 ** Maximum number of tokens a phrase may have to be considered for the
128128 ** incremental doclists strategy.
128130 #define MAX_INCR_PHRASE_TOKENS 4
128133 ** This function is called for each Fts3Phrase in a full-text query
128134 ** expression to initialize the mechanism for returning rows. Once this
128135 ** function has been called successfully on an Fts3Phrase, it may be
128136 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
128138 ** If parameter bOptOk is true, then the phrase may (or may not) use the
128139 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
128140 ** memory within this call.
128142 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
128144 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
128145 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128146 int rc = SQLITE_OK; /* Error code */
128147 int i;
128149 /* Determine if doclists may be loaded from disk incrementally. This is
128150 ** possible if the bOptOk argument is true, the FTS doclists will be
128151 ** scanned in forward order, and the phrase consists of
128152 ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
128153 ** tokens or prefix tokens that cannot use a prefix-index. */
128154 int bHaveIncr = 0;
128155 int bIncrOk = (bOptOk
128156 && pCsr->bDesc==pTab->bDescIdx
128157 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
128158 && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
128159 #ifdef SQLITE_TEST
128160 && pTab->bNoIncrDoclist==0
128161 #endif
128163 for(i=0; bIncrOk==1 && i<p->nToken; i++){
128164 Fts3PhraseToken *pToken = &p->aToken[i];
128165 if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
128166 bIncrOk = 0;
128168 if( pToken->pSegcsr ) bHaveIncr = 1;
128171 if( bIncrOk && bHaveIncr ){
128172 /* Use the incremental approach. */
128173 int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
128174 for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
128175 Fts3PhraseToken *pToken = &p->aToken[i];
128176 Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
128177 if( pSegcsr ){
128178 rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
128181 p->bIncr = 1;
128182 }else{
128183 /* Load the full doclist for the phrase into memory. */
128184 rc = fts3EvalPhraseLoad(pCsr, p);
128185 p->bIncr = 0;
128188 assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
128189 return rc;
128193 ** This function is used to iterate backwards (from the end to start)
128194 ** through doclists. It is used by this module to iterate through phrase
128195 ** doclists in reverse and by the fts3_write.c module to iterate through
128196 ** pending-terms lists when writing to databases with "order=desc".
128198 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
128199 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
128200 ** function iterates from the end of the doclist to the beginning.
128202 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
128203 int bDescIdx, /* True if the doclist is desc */
128204 char *aDoclist, /* Pointer to entire doclist */
128205 int nDoclist, /* Length of aDoclist in bytes */
128206 char **ppIter, /* IN/OUT: Iterator pointer */
128207 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
128208 int *pnList, /* OUT: List length pointer */
128209 u8 *pbEof /* OUT: End-of-file flag */
128211 char *p = *ppIter;
128213 assert( nDoclist>0 );
128214 assert( *pbEof==0 );
128215 assert( p || *piDocid==0 );
128216 assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
128218 if( p==0 ){
128219 sqlite3_int64 iDocid = 0;
128220 char *pNext = 0;
128221 char *pDocid = aDoclist;
128222 char *pEnd = &aDoclist[nDoclist];
128223 int iMul = 1;
128225 while( pDocid<pEnd ){
128226 sqlite3_int64 iDelta;
128227 pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
128228 iDocid += (iMul * iDelta);
128229 pNext = pDocid;
128230 fts3PoslistCopy(0, &pDocid);
128231 while( pDocid<pEnd && *pDocid==0 ) pDocid++;
128232 iMul = (bDescIdx ? -1 : 1);
128235 *pnList = (int)(pEnd - pNext);
128236 *ppIter = pNext;
128237 *piDocid = iDocid;
128238 }else{
128239 int iMul = (bDescIdx ? -1 : 1);
128240 sqlite3_int64 iDelta;
128241 fts3GetReverseVarint(&p, aDoclist, &iDelta);
128242 *piDocid -= (iMul * iDelta);
128244 if( p==aDoclist ){
128245 *pbEof = 1;
128246 }else{
128247 char *pSave = p;
128248 fts3ReversePoslist(aDoclist, &p);
128249 *pnList = (int)(pSave - p);
128251 *ppIter = p;
128256 ** Iterate forwards through a doclist.
128258 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
128259 int bDescIdx, /* True if the doclist is desc */
128260 char *aDoclist, /* Pointer to entire doclist */
128261 int nDoclist, /* Length of aDoclist in bytes */
128262 char **ppIter, /* IN/OUT: Iterator pointer */
128263 sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
128264 u8 *pbEof /* OUT: End-of-file flag */
128266 char *p = *ppIter;
128268 assert( nDoclist>0 );
128269 assert( *pbEof==0 );
128270 assert( p || *piDocid==0 );
128271 assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
128273 if( p==0 ){
128274 p = aDoclist;
128275 p += sqlite3Fts3GetVarint(p, piDocid);
128276 }else{
128277 fts3PoslistCopy(0, &p);
128278 if( p>=&aDoclist[nDoclist] ){
128279 *pbEof = 1;
128280 }else{
128281 sqlite3_int64 iVar;
128282 p += sqlite3Fts3GetVarint(p, &iVar);
128283 *piDocid += ((bDescIdx ? -1 : 1) * iVar);
128287 *ppIter = p;
128291 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
128292 ** to true if EOF is reached.
128294 static void fts3EvalDlPhraseNext(
128295 Fts3Table *pTab,
128296 Fts3Doclist *pDL,
128297 u8 *pbEof
128299 char *pIter; /* Used to iterate through aAll */
128300 char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
128302 if( pDL->pNextDocid ){
128303 pIter = pDL->pNextDocid;
128304 }else{
128305 pIter = pDL->aAll;
128308 if( pIter>=pEnd ){
128309 /* We have already reached the end of this doclist. EOF. */
128310 *pbEof = 1;
128311 }else{
128312 sqlite3_int64 iDelta;
128313 pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
128314 if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
128315 pDL->iDocid += iDelta;
128316 }else{
128317 pDL->iDocid -= iDelta;
128319 pDL->pList = pIter;
128320 fts3PoslistCopy(0, &pIter);
128321 pDL->nList = (int)(pIter - pDL->pList);
128323 /* pIter now points just past the 0x00 that terminates the position-
128324 ** list for document pDL->iDocid. However, if this position-list was
128325 ** edited in place by fts3EvalNearTrim(), then pIter may not actually
128326 ** point to the start of the next docid value. The following line deals
128327 ** with this case by advancing pIter past the zero-padding added by
128328 ** fts3EvalNearTrim(). */
128329 while( pIter<pEnd && *pIter==0 ) pIter++;
128331 pDL->pNextDocid = pIter;
128332 assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
128333 *pbEof = 0;
128338 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
128340 typedef struct TokenDoclist TokenDoclist;
128341 struct TokenDoclist {
128342 int bIgnore;
128343 sqlite3_int64 iDocid;
128344 char *pList;
128345 int nList;
128349 ** Token pToken is an incrementally loaded token that is part of a
128350 ** multi-token phrase. Advance it to the next matching document in the
128351 ** database and populate output variable *p with the details of the new
128352 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
128354 ** If an error occurs, return an SQLite error code. Otherwise, return
128355 ** SQLITE_OK.
128357 static int incrPhraseTokenNext(
128358 Fts3Table *pTab, /* Virtual table handle */
128359 Fts3Phrase *pPhrase, /* Phrase to advance token of */
128360 int iToken, /* Specific token to advance */
128361 TokenDoclist *p, /* OUT: Docid and doclist for new entry */
128362 u8 *pbEof /* OUT: True if iterator is at EOF */
128364 int rc = SQLITE_OK;
128366 if( pPhrase->iDoclistToken==iToken ){
128367 assert( p->bIgnore==0 );
128368 assert( pPhrase->aToken[iToken].pSegcsr==0 );
128369 fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
128370 p->pList = pPhrase->doclist.pList;
128371 p->nList = pPhrase->doclist.nList;
128372 p->iDocid = pPhrase->doclist.iDocid;
128373 }else{
128374 Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
128375 assert( pToken->pDeferred==0 );
128376 assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
128377 if( pToken->pSegcsr ){
128378 assert( p->bIgnore==0 );
128379 rc = sqlite3Fts3MsrIncrNext(
128380 pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
128382 if( p->pList==0 ) *pbEof = 1;
128383 }else{
128384 p->bIgnore = 1;
128388 return rc;
128393 ** The phrase iterator passed as the second argument:
128395 ** * features at least one token that uses an incremental doclist, and
128397 ** * does not contain any deferred tokens.
128399 ** Advance it to the next matching documnent in the database and populate
128400 ** the Fts3Doclist.pList and nList fields.
128402 ** If there is no "next" entry and no error occurs, then *pbEof is set to
128403 ** 1 before returning. Otherwise, if no error occurs and the iterator is
128404 ** successfully advanced, *pbEof is set to 0.
128406 ** If an error occurs, return an SQLite error code. Otherwise, return
128407 ** SQLITE_OK.
128409 static int fts3EvalIncrPhraseNext(
128410 Fts3Cursor *pCsr, /* FTS Cursor handle */
128411 Fts3Phrase *p, /* Phrase object to advance to next docid */
128412 u8 *pbEof /* OUT: Set to 1 if EOF */
128414 int rc = SQLITE_OK;
128415 Fts3Doclist *pDL = &p->doclist;
128416 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128417 u8 bEof = 0;
128419 /* This is only called if it is guaranteed that the phrase has at least
128420 ** one incremental token. In which case the bIncr flag is set. */
128421 assert( p->bIncr==1 );
128423 if( p->nToken==1 && p->bIncr ){
128424 rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
128425 &pDL->iDocid, &pDL->pList, &pDL->nList
128427 if( pDL->pList==0 ) bEof = 1;
128428 }else{
128429 int bDescDoclist = pCsr->bDesc;
128430 struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
128432 memset(a, 0, sizeof(a));
128433 assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
128434 assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
128436 while( bEof==0 ){
128437 int bMaxSet = 0;
128438 sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
128439 int i; /* Used to iterate through tokens */
128441 /* Advance the iterator for each token in the phrase once. */
128442 for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
128443 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
128444 if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
128445 iMax = a[i].iDocid;
128446 bMaxSet = 1;
128449 assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
128450 assert( rc!=SQLITE_OK || bMaxSet );
128452 /* Keep advancing iterators until they all point to the same document */
128453 for(i=0; i<p->nToken; i++){
128454 while( rc==SQLITE_OK && bEof==0
128455 && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
128457 rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
128458 if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
128459 iMax = a[i].iDocid;
128460 i = 0;
128465 /* Check if the current entries really are a phrase match */
128466 if( bEof==0 ){
128467 int nList = 0;
128468 int nByte = a[p->nToken-1].nList;
128469 char *aDoclist = sqlite3_malloc(nByte+1);
128470 if( !aDoclist ) return SQLITE_NOMEM;
128471 memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
128473 for(i=0; i<(p->nToken-1); i++){
128474 if( a[i].bIgnore==0 ){
128475 char *pL = a[i].pList;
128476 char *pR = aDoclist;
128477 char *pOut = aDoclist;
128478 int nDist = p->nToken-1-i;
128479 int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
128480 if( res==0 ) break;
128481 nList = (int)(pOut - aDoclist);
128484 if( i==(p->nToken-1) ){
128485 pDL->iDocid = iMax;
128486 pDL->pList = aDoclist;
128487 pDL->nList = nList;
128488 pDL->bFreeList = 1;
128489 break;
128491 sqlite3_free(aDoclist);
128496 *pbEof = bEof;
128497 return rc;
128501 ** Attempt to move the phrase iterator to point to the next matching docid.
128502 ** If an error occurs, return an SQLite error code. Otherwise, return
128503 ** SQLITE_OK.
128505 ** If there is no "next" entry and no error occurs, then *pbEof is set to
128506 ** 1 before returning. Otherwise, if no error occurs and the iterator is
128507 ** successfully advanced, *pbEof is set to 0.
128509 static int fts3EvalPhraseNext(
128510 Fts3Cursor *pCsr, /* FTS Cursor handle */
128511 Fts3Phrase *p, /* Phrase object to advance to next docid */
128512 u8 *pbEof /* OUT: Set to 1 if EOF */
128514 int rc = SQLITE_OK;
128515 Fts3Doclist *pDL = &p->doclist;
128516 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128518 if( p->bIncr ){
128519 rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
128520 }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
128521 sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
128522 &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
128524 pDL->pList = pDL->pNextDocid;
128525 }else{
128526 fts3EvalDlPhraseNext(pTab, pDL, pbEof);
128529 return rc;
128534 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
128535 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
128536 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
128537 ** expressions for which all descendent tokens are deferred.
128539 ** If parameter bOptOk is zero, then it is guaranteed that the
128540 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
128541 ** each phrase in the expression (subject to deferred token processing).
128542 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
128543 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
128545 ** If an error occurs within this function, *pRc is set to an SQLite error
128546 ** code before returning.
128548 static void fts3EvalStartReaders(
128549 Fts3Cursor *pCsr, /* FTS Cursor handle */
128550 Fts3Expr *pExpr, /* Expression to initialize phrases in */
128551 int *pRc /* IN/OUT: Error code */
128553 if( pExpr && SQLITE_OK==*pRc ){
128554 if( pExpr->eType==FTSQUERY_PHRASE ){
128555 int i;
128556 int nToken = pExpr->pPhrase->nToken;
128557 for(i=0; i<nToken; i++){
128558 if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
128560 pExpr->bDeferred = (i==nToken);
128561 *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
128562 }else{
128563 fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
128564 fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
128565 pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
128571 ** An array of the following structures is assembled as part of the process
128572 ** of selecting tokens to defer before the query starts executing (as part
128573 ** of the xFilter() method). There is one element in the array for each
128574 ** token in the FTS expression.
128576 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
128577 ** to phrases that are connected only by AND and NEAR operators (not OR or
128578 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
128579 ** separately. The root of a tokens AND/NEAR cluster is stored in
128580 ** Fts3TokenAndCost.pRoot.
128582 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
128583 struct Fts3TokenAndCost {
128584 Fts3Phrase *pPhrase; /* The phrase the token belongs to */
128585 int iToken; /* Position of token in phrase */
128586 Fts3PhraseToken *pToken; /* The token itself */
128587 Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
128588 int nOvfl; /* Number of overflow pages to load doclist */
128589 int iCol; /* The column the token must match */
128593 ** This function is used to populate an allocated Fts3TokenAndCost array.
128595 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
128596 ** Otherwise, if an error occurs during execution, *pRc is set to an
128597 ** SQLite error code.
128599 static void fts3EvalTokenCosts(
128600 Fts3Cursor *pCsr, /* FTS Cursor handle */
128601 Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
128602 Fts3Expr *pExpr, /* Expression to consider */
128603 Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
128604 Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
128605 int *pRc /* IN/OUT: Error code */
128607 if( *pRc==SQLITE_OK ){
128608 if( pExpr->eType==FTSQUERY_PHRASE ){
128609 Fts3Phrase *pPhrase = pExpr->pPhrase;
128610 int i;
128611 for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
128612 Fts3TokenAndCost *pTC = (*ppTC)++;
128613 pTC->pPhrase = pPhrase;
128614 pTC->iToken = i;
128615 pTC->pRoot = pRoot;
128616 pTC->pToken = &pPhrase->aToken[i];
128617 pTC->iCol = pPhrase->iColumn;
128618 *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
128620 }else if( pExpr->eType!=FTSQUERY_NOT ){
128621 assert( pExpr->eType==FTSQUERY_OR
128622 || pExpr->eType==FTSQUERY_AND
128623 || pExpr->eType==FTSQUERY_NEAR
128625 assert( pExpr->pLeft && pExpr->pRight );
128626 if( pExpr->eType==FTSQUERY_OR ){
128627 pRoot = pExpr->pLeft;
128628 **ppOr = pRoot;
128629 (*ppOr)++;
128631 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
128632 if( pExpr->eType==FTSQUERY_OR ){
128633 pRoot = pExpr->pRight;
128634 **ppOr = pRoot;
128635 (*ppOr)++;
128637 fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
128643 ** Determine the average document (row) size in pages. If successful,
128644 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
128645 ** an SQLite error code.
128647 ** The average document size in pages is calculated by first calculating
128648 ** determining the average size in bytes, B. If B is less than the amount
128649 ** of data that will fit on a single leaf page of an intkey table in
128650 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
128651 ** the number of overflow pages consumed by a record B bytes in size.
128653 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
128654 if( pCsr->nRowAvg==0 ){
128655 /* The average document size, which is required to calculate the cost
128656 ** of each doclist, has not yet been determined. Read the required
128657 ** data from the %_stat table to calculate it.
128659 ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
128660 ** varints, where nCol is the number of columns in the FTS3 table.
128661 ** The first varint is the number of documents currently stored in
128662 ** the table. The following nCol varints contain the total amount of
128663 ** data stored in all rows of each column of the table, from left
128664 ** to right.
128666 int rc;
128667 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
128668 sqlite3_stmt *pStmt;
128669 sqlite3_int64 nDoc = 0;
128670 sqlite3_int64 nByte = 0;
128671 const char *pEnd;
128672 const char *a;
128674 rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
128675 if( rc!=SQLITE_OK ) return rc;
128676 a = sqlite3_column_blob(pStmt, 0);
128677 assert( a );
128679 pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
128680 a += sqlite3Fts3GetVarint(a, &nDoc);
128681 while( a<pEnd ){
128682 a += sqlite3Fts3GetVarint(a, &nByte);
128684 if( nDoc==0 || nByte==0 ){
128685 sqlite3_reset(pStmt);
128686 return FTS_CORRUPT_VTAB;
128689 pCsr->nDoc = nDoc;
128690 pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
128691 assert( pCsr->nRowAvg>0 );
128692 rc = sqlite3_reset(pStmt);
128693 if( rc!=SQLITE_OK ) return rc;
128696 *pnPage = pCsr->nRowAvg;
128697 return SQLITE_OK;
128701 ** This function is called to select the tokens (if any) that will be
128702 ** deferred. The array aTC[] has already been populated when this is
128703 ** called.
128705 ** This function is called once for each AND/NEAR cluster in the
128706 ** expression. Each invocation determines which tokens to defer within
128707 ** the cluster with root node pRoot. See comments above the definition
128708 ** of struct Fts3TokenAndCost for more details.
128710 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
128711 ** called on each token to defer. Otherwise, an SQLite error code is
128712 ** returned.
128714 static int fts3EvalSelectDeferred(
128715 Fts3Cursor *pCsr, /* FTS Cursor handle */
128716 Fts3Expr *pRoot, /* Consider tokens with this root node */
128717 Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
128718 int nTC /* Number of entries in aTC[] */
128720 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128721 int nDocSize = 0; /* Number of pages per doc loaded */
128722 int rc = SQLITE_OK; /* Return code */
128723 int ii; /* Iterator variable for various purposes */
128724 int nOvfl = 0; /* Total overflow pages used by doclists */
128725 int nToken = 0; /* Total number of tokens in cluster */
128727 int nMinEst = 0; /* The minimum count for any phrase so far. */
128728 int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
128730 /* Tokens are never deferred for FTS tables created using the content=xxx
128731 ** option. The reason being that it is not guaranteed that the content
128732 ** table actually contains the same data as the index. To prevent this from
128733 ** causing any problems, the deferred token optimization is completely
128734 ** disabled for content=xxx tables. */
128735 if( pTab->zContentTbl ){
128736 return SQLITE_OK;
128739 /* Count the tokens in this AND/NEAR cluster. If none of the doclists
128740 ** associated with the tokens spill onto overflow pages, or if there is
128741 ** only 1 token, exit early. No tokens to defer in this case. */
128742 for(ii=0; ii<nTC; ii++){
128743 if( aTC[ii].pRoot==pRoot ){
128744 nOvfl += aTC[ii].nOvfl;
128745 nToken++;
128748 if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
128750 /* Obtain the average docsize (in pages). */
128751 rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
128752 assert( rc!=SQLITE_OK || nDocSize>0 );
128755 /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
128756 ** of the number of overflow pages that will be loaded by the pager layer
128757 ** to retrieve the entire doclist for the token from the full-text index.
128758 ** Load the doclists for tokens that are either:
128760 ** a. The cheapest token in the entire query (i.e. the one visited by the
128761 ** first iteration of this loop), or
128763 ** b. Part of a multi-token phrase.
128765 ** After each token doclist is loaded, merge it with the others from the
128766 ** same phrase and count the number of documents that the merged doclist
128767 ** contains. Set variable "nMinEst" to the smallest number of documents in
128768 ** any phrase doclist for which 1 or more token doclists have been loaded.
128769 ** Let nOther be the number of other phrases for which it is certain that
128770 ** one or more tokens will not be deferred.
128772 ** Then, for each token, defer it if loading the doclist would result in
128773 ** loading N or more overflow pages into memory, where N is computed as:
128775 ** (nMinEst + 4^nOther - 1) / (4^nOther)
128777 for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
128778 int iTC; /* Used to iterate through aTC[] array. */
128779 Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
128781 /* Set pTC to point to the cheapest remaining token. */
128782 for(iTC=0; iTC<nTC; iTC++){
128783 if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
128784 && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
128786 pTC = &aTC[iTC];
128789 assert( pTC );
128791 if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
128792 /* The number of overflow pages to load for this (and therefore all
128793 ** subsequent) tokens is greater than the estimated number of pages
128794 ** that will be loaded if all subsequent tokens are deferred.
128796 Fts3PhraseToken *pToken = pTC->pToken;
128797 rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
128798 fts3SegReaderCursorFree(pToken->pSegcsr);
128799 pToken->pSegcsr = 0;
128800 }else{
128801 /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
128802 ** for-loop. Except, limit the value to 2^24 to prevent it from
128803 ** overflowing the 32-bit integer it is stored in. */
128804 if( ii<12 ) nLoad4 = nLoad4*4;
128806 if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
128807 /* Either this is the cheapest token in the entire query, or it is
128808 ** part of a multi-token phrase. Either way, the entire doclist will
128809 ** (eventually) be loaded into memory. It may as well be now. */
128810 Fts3PhraseToken *pToken = pTC->pToken;
128811 int nList = 0;
128812 char *pList = 0;
128813 rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
128814 assert( rc==SQLITE_OK || pList==0 );
128815 if( rc==SQLITE_OK ){
128816 int nCount;
128817 fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
128818 nCount = fts3DoclistCountDocids(
128819 pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
128821 if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
128825 pTC->pToken = 0;
128828 return rc;
128832 ** This function is called from within the xFilter method. It initializes
128833 ** the full-text query currently stored in pCsr->pExpr. To iterate through
128834 ** the results of a query, the caller does:
128836 ** fts3EvalStart(pCsr);
128837 ** while( 1 ){
128838 ** fts3EvalNext(pCsr);
128839 ** if( pCsr->bEof ) break;
128840 ** ... return row pCsr->iPrevId to the caller ...
128843 static int fts3EvalStart(Fts3Cursor *pCsr){
128844 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
128845 int rc = SQLITE_OK;
128846 int nToken = 0;
128847 int nOr = 0;
128849 /* Allocate a MultiSegReader for each token in the expression. */
128850 fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
128852 /* Determine which, if any, tokens in the expression should be deferred. */
128853 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
128854 if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
128855 Fts3TokenAndCost *aTC;
128856 Fts3Expr **apOr;
128857 aTC = (Fts3TokenAndCost *)sqlite3_malloc(
128858 sizeof(Fts3TokenAndCost) * nToken
128859 + sizeof(Fts3Expr *) * nOr * 2
128861 apOr = (Fts3Expr **)&aTC[nToken];
128863 if( !aTC ){
128864 rc = SQLITE_NOMEM;
128865 }else{
128866 int ii;
128867 Fts3TokenAndCost *pTC = aTC;
128868 Fts3Expr **ppOr = apOr;
128870 fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
128871 nToken = (int)(pTC-aTC);
128872 nOr = (int)(ppOr-apOr);
128874 if( rc==SQLITE_OK ){
128875 rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
128876 for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
128877 rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
128881 sqlite3_free(aTC);
128884 #endif
128886 fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
128887 return rc;
128891 ** Invalidate the current position list for phrase pPhrase.
128893 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
128894 if( pPhrase->doclist.bFreeList ){
128895 sqlite3_free(pPhrase->doclist.pList);
128897 pPhrase->doclist.pList = 0;
128898 pPhrase->doclist.nList = 0;
128899 pPhrase->doclist.bFreeList = 0;
128903 ** This function is called to edit the position list associated with
128904 ** the phrase object passed as the fifth argument according to a NEAR
128905 ** condition. For example:
128907 ** abc NEAR/5 "def ghi"
128909 ** Parameter nNear is passed the NEAR distance of the expression (5 in
128910 ** the example above). When this function is called, *paPoslist points to
128911 ** the position list, and *pnToken is the number of phrase tokens in, the
128912 ** phrase on the other side of the NEAR operator to pPhrase. For example,
128913 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
128914 ** the position list associated with phrase "abc".
128916 ** All positions in the pPhrase position list that are not sufficiently
128917 ** close to a position in the *paPoslist position list are removed. If this
128918 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
128920 ** Before returning, *paPoslist is set to point to the position lsit
128921 ** associated with pPhrase. And *pnToken is set to the number of tokens in
128922 ** pPhrase.
128924 static int fts3EvalNearTrim(
128925 int nNear, /* NEAR distance. As in "NEAR/nNear". */
128926 char *aTmp, /* Temporary space to use */
128927 char **paPoslist, /* IN/OUT: Position list */
128928 int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
128929 Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
128931 int nParam1 = nNear + pPhrase->nToken;
128932 int nParam2 = nNear + *pnToken;
128933 int nNew;
128934 char *p2;
128935 char *pOut;
128936 int res;
128938 assert( pPhrase->doclist.pList );
128940 p2 = pOut = pPhrase->doclist.pList;
128941 res = fts3PoslistNearMerge(
128942 &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
128944 if( res ){
128945 nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
128946 assert( pPhrase->doclist.pList[nNew]=='\0' );
128947 assert( nNew<=pPhrase->doclist.nList && nNew>0 );
128948 memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
128949 pPhrase->doclist.nList = nNew;
128950 *paPoslist = pPhrase->doclist.pList;
128951 *pnToken = pPhrase->nToken;
128954 return res;
128958 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
128959 ** Otherwise, it advances the expression passed as the second argument to
128960 ** point to the next matching row in the database. Expressions iterate through
128961 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
128962 ** or descending if it is non-zero.
128964 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
128965 ** successful, the following variables in pExpr are set:
128967 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
128968 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
128970 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
128971 ** at EOF, then the following variables are populated with the position list
128972 ** for the phrase for the visited row:
128974 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
128975 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
128977 ** It says above that this function advances the expression to the next
128978 ** matching row. This is usually true, but there are the following exceptions:
128980 ** 1. Deferred tokens are not taken into account. If a phrase consists
128981 ** entirely of deferred tokens, it is assumed to match every row in
128982 ** the db. In this case the position-list is not populated at all.
128984 ** Or, if a phrase contains one or more deferred tokens and one or
128985 ** more non-deferred tokens, then the expression is advanced to the
128986 ** next possible match, considering only non-deferred tokens. In other
128987 ** words, if the phrase is "A B C", and "B" is deferred, the expression
128988 ** is advanced to the next row that contains an instance of "A * C",
128989 ** where "*" may match any single token. The position list in this case
128990 ** is populated as for "A * C" before returning.
128992 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
128993 ** advanced to point to the next row that matches "x AND y".
128995 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
128996 ** really a match, taking into account deferred tokens and NEAR operators.
128998 static void fts3EvalNextRow(
128999 Fts3Cursor *pCsr, /* FTS Cursor handle */
129000 Fts3Expr *pExpr, /* Expr. to advance to next matching row */
129001 int *pRc /* IN/OUT: Error code */
129003 if( *pRc==SQLITE_OK ){
129004 int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
129005 assert( pExpr->bEof==0 );
129006 pExpr->bStart = 1;
129008 switch( pExpr->eType ){
129009 case FTSQUERY_NEAR:
129010 case FTSQUERY_AND: {
129011 Fts3Expr *pLeft = pExpr->pLeft;
129012 Fts3Expr *pRight = pExpr->pRight;
129013 assert( !pLeft->bDeferred || !pRight->bDeferred );
129015 if( pLeft->bDeferred ){
129016 /* LHS is entirely deferred. So we assume it matches every row.
129017 ** Advance the RHS iterator to find the next row visited. */
129018 fts3EvalNextRow(pCsr, pRight, pRc);
129019 pExpr->iDocid = pRight->iDocid;
129020 pExpr->bEof = pRight->bEof;
129021 }else if( pRight->bDeferred ){
129022 /* RHS is entirely deferred. So we assume it matches every row.
129023 ** Advance the LHS iterator to find the next row visited. */
129024 fts3EvalNextRow(pCsr, pLeft, pRc);
129025 pExpr->iDocid = pLeft->iDocid;
129026 pExpr->bEof = pLeft->bEof;
129027 }else{
129028 /* Neither the RHS or LHS are deferred. */
129029 fts3EvalNextRow(pCsr, pLeft, pRc);
129030 fts3EvalNextRow(pCsr, pRight, pRc);
129031 while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
129032 sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
129033 if( iDiff==0 ) break;
129034 if( iDiff<0 ){
129035 fts3EvalNextRow(pCsr, pLeft, pRc);
129036 }else{
129037 fts3EvalNextRow(pCsr, pRight, pRc);
129040 pExpr->iDocid = pLeft->iDocid;
129041 pExpr->bEof = (pLeft->bEof || pRight->bEof);
129043 break;
129046 case FTSQUERY_OR: {
129047 Fts3Expr *pLeft = pExpr->pLeft;
129048 Fts3Expr *pRight = pExpr->pRight;
129049 sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
129051 assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
129052 assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
129054 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
129055 fts3EvalNextRow(pCsr, pLeft, pRc);
129056 }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
129057 fts3EvalNextRow(pCsr, pRight, pRc);
129058 }else{
129059 fts3EvalNextRow(pCsr, pLeft, pRc);
129060 fts3EvalNextRow(pCsr, pRight, pRc);
129063 pExpr->bEof = (pLeft->bEof && pRight->bEof);
129064 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
129065 if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
129066 pExpr->iDocid = pLeft->iDocid;
129067 }else{
129068 pExpr->iDocid = pRight->iDocid;
129071 break;
129074 case FTSQUERY_NOT: {
129075 Fts3Expr *pLeft = pExpr->pLeft;
129076 Fts3Expr *pRight = pExpr->pRight;
129078 if( pRight->bStart==0 ){
129079 fts3EvalNextRow(pCsr, pRight, pRc);
129080 assert( *pRc!=SQLITE_OK || pRight->bStart );
129083 fts3EvalNextRow(pCsr, pLeft, pRc);
129084 if( pLeft->bEof==0 ){
129085 while( !*pRc
129086 && !pRight->bEof
129087 && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
129089 fts3EvalNextRow(pCsr, pRight, pRc);
129092 pExpr->iDocid = pLeft->iDocid;
129093 pExpr->bEof = pLeft->bEof;
129094 break;
129097 default: {
129098 Fts3Phrase *pPhrase = pExpr->pPhrase;
129099 fts3EvalInvalidatePoslist(pPhrase);
129100 *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
129101 pExpr->iDocid = pPhrase->doclist.iDocid;
129102 break;
129109 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
129110 ** cluster, then this function returns 1 immediately.
129112 ** Otherwise, it checks if the current row really does match the NEAR
129113 ** expression, using the data currently stored in the position lists
129114 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
129116 ** If the current row is a match, the position list associated with each
129117 ** phrase in the NEAR expression is edited in place to contain only those
129118 ** phrase instances sufficiently close to their peers to satisfy all NEAR
129119 ** constraints. In this case it returns 1. If the NEAR expression does not
129120 ** match the current row, 0 is returned. The position lists may or may not
129121 ** be edited if 0 is returned.
129123 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
129124 int res = 1;
129126 /* The following block runs if pExpr is the root of a NEAR query.
129127 ** For example, the query:
129129 ** "w" NEAR "x" NEAR "y" NEAR "z"
129131 ** which is represented in tree form as:
129134 ** +--NEAR--+ <-- root of NEAR query
129135 ** | |
129136 ** +--NEAR--+ "z"
129137 ** | |
129138 ** +--NEAR--+ "y"
129139 ** | |
129140 ** "w" "x"
129142 ** The right-hand child of a NEAR node is always a phrase. The
129143 ** left-hand child may be either a phrase or a NEAR node. There are
129144 ** no exceptions to this - it's the way the parser in fts3_expr.c works.
129146 if( *pRc==SQLITE_OK
129147 && pExpr->eType==FTSQUERY_NEAR
129148 && pExpr->bEof==0
129149 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
129151 Fts3Expr *p;
129152 int nTmp = 0; /* Bytes of temp space */
129153 char *aTmp; /* Temp space for PoslistNearMerge() */
129155 /* Allocate temporary working space. */
129156 for(p=pExpr; p->pLeft; p=p->pLeft){
129157 nTmp += p->pRight->pPhrase->doclist.nList;
129159 nTmp += p->pPhrase->doclist.nList;
129160 if( nTmp==0 ){
129161 res = 0;
129162 }else{
129163 aTmp = sqlite3_malloc(nTmp*2);
129164 if( !aTmp ){
129165 *pRc = SQLITE_NOMEM;
129166 res = 0;
129167 }else{
129168 char *aPoslist = p->pPhrase->doclist.pList;
129169 int nToken = p->pPhrase->nToken;
129171 for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
129172 Fts3Phrase *pPhrase = p->pRight->pPhrase;
129173 int nNear = p->nNear;
129174 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
129177 aPoslist = pExpr->pRight->pPhrase->doclist.pList;
129178 nToken = pExpr->pRight->pPhrase->nToken;
129179 for(p=pExpr->pLeft; p && res; p=p->pLeft){
129180 int nNear;
129181 Fts3Phrase *pPhrase;
129182 assert( p->pParent && p->pParent->pLeft==p );
129183 nNear = p->pParent->nNear;
129184 pPhrase = (
129185 p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
129187 res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
129191 sqlite3_free(aTmp);
129195 return res;
129199 ** This function is a helper function for fts3EvalTestDeferredAndNear().
129200 ** Assuming no error occurs or has occurred, It returns non-zero if the
129201 ** expression passed as the second argument matches the row that pCsr
129202 ** currently points to, or zero if it does not.
129204 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
129205 ** If an error occurs during execution of this function, *pRc is set to
129206 ** the appropriate SQLite error code. In this case the returned value is
129207 ** undefined.
129209 static int fts3EvalTestExpr(
129210 Fts3Cursor *pCsr, /* FTS cursor handle */
129211 Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
129212 int *pRc /* IN/OUT: Error code */
129214 int bHit = 1; /* Return value */
129215 if( *pRc==SQLITE_OK ){
129216 switch( pExpr->eType ){
129217 case FTSQUERY_NEAR:
129218 case FTSQUERY_AND:
129219 bHit = (
129220 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
129221 && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
129222 && fts3EvalNearTest(pExpr, pRc)
129225 /* If the NEAR expression does not match any rows, zero the doclist for
129226 ** all phrases involved in the NEAR. This is because the snippet(),
129227 ** offsets() and matchinfo() functions are not supposed to recognize
129228 ** any instances of phrases that are part of unmatched NEAR queries.
129229 ** For example if this expression:
129231 ** ... MATCH 'a OR (b NEAR c)'
129233 ** is matched against a row containing:
129235 ** 'a b d e'
129237 ** then any snippet() should ony highlight the "a" term, not the "b"
129238 ** (as "b" is part of a non-matching NEAR clause).
129240 if( bHit==0
129241 && pExpr->eType==FTSQUERY_NEAR
129242 && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
129244 Fts3Expr *p;
129245 for(p=pExpr; p->pPhrase==0; p=p->pLeft){
129246 if( p->pRight->iDocid==pCsr->iPrevId ){
129247 fts3EvalInvalidatePoslist(p->pRight->pPhrase);
129250 if( p->iDocid==pCsr->iPrevId ){
129251 fts3EvalInvalidatePoslist(p->pPhrase);
129255 break;
129257 case FTSQUERY_OR: {
129258 int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
129259 int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
129260 bHit = bHit1 || bHit2;
129261 break;
129264 case FTSQUERY_NOT:
129265 bHit = (
129266 fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
129267 && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
129269 break;
129271 default: {
129272 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
129273 if( pCsr->pDeferred
129274 && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
129276 Fts3Phrase *pPhrase = pExpr->pPhrase;
129277 assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
129278 if( pExpr->bDeferred ){
129279 fts3EvalInvalidatePoslist(pPhrase);
129281 *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
129282 bHit = (pPhrase->doclist.pList!=0);
129283 pExpr->iDocid = pCsr->iPrevId;
129284 }else
129285 #endif
129287 bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
129289 break;
129293 return bHit;
129297 ** This function is called as the second part of each xNext operation when
129298 ** iterating through the results of a full-text query. At this point the
129299 ** cursor points to a row that matches the query expression, with the
129300 ** following caveats:
129302 ** * Up until this point, "NEAR" operators in the expression have been
129303 ** treated as "AND".
129305 ** * Deferred tokens have not yet been considered.
129307 ** If *pRc is not SQLITE_OK when this function is called, it immediately
129308 ** returns 0. Otherwise, it tests whether or not after considering NEAR
129309 ** operators and deferred tokens the current row is still a match for the
129310 ** expression. It returns 1 if both of the following are true:
129312 ** 1. *pRc is SQLITE_OK when this function returns, and
129314 ** 2. After scanning the current FTS table row for the deferred tokens,
129315 ** it is determined that the row does *not* match the query.
129317 ** Or, if no error occurs and it seems the current row does match the FTS
129318 ** query, return 0.
129320 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
129321 int rc = *pRc;
129322 int bMiss = 0;
129323 if( rc==SQLITE_OK ){
129325 /* If there are one or more deferred tokens, load the current row into
129326 ** memory and scan it to determine the position list for each deferred
129327 ** token. Then, see if this row is really a match, considering deferred
129328 ** tokens and NEAR operators (neither of which were taken into account
129329 ** earlier, by fts3EvalNextRow()).
129331 if( pCsr->pDeferred ){
129332 rc = fts3CursorSeek(0, pCsr);
129333 if( rc==SQLITE_OK ){
129334 rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
129337 bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
129339 /* Free the position-lists accumulated for each deferred token above. */
129340 sqlite3Fts3FreeDeferredDoclists(pCsr);
129341 *pRc = rc;
129343 return (rc==SQLITE_OK && bMiss);
129347 ** Advance to the next document that matches the FTS expression in
129348 ** Fts3Cursor.pExpr.
129350 static int fts3EvalNext(Fts3Cursor *pCsr){
129351 int rc = SQLITE_OK; /* Return Code */
129352 Fts3Expr *pExpr = pCsr->pExpr;
129353 assert( pCsr->isEof==0 );
129354 if( pExpr==0 ){
129355 pCsr->isEof = 1;
129356 }else{
129358 if( pCsr->isRequireSeek==0 ){
129359 sqlite3_reset(pCsr->pStmt);
129361 assert( sqlite3_data_count(pCsr->pStmt)==0 );
129362 fts3EvalNextRow(pCsr, pExpr, &rc);
129363 pCsr->isEof = pExpr->bEof;
129364 pCsr->isRequireSeek = 1;
129365 pCsr->isMatchinfoNeeded = 1;
129366 pCsr->iPrevId = pExpr->iDocid;
129367 }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
129370 /* Check if the cursor is past the end of the docid range specified
129371 ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
129372 if( rc==SQLITE_OK && (
129373 (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
129374 || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
129376 pCsr->isEof = 1;
129379 return rc;
129383 ** Restart interation for expression pExpr so that the next call to
129384 ** fts3EvalNext() visits the first row. Do not allow incremental
129385 ** loading or merging of phrase doclists for this iteration.
129387 ** If *pRc is other than SQLITE_OK when this function is called, it is
129388 ** a no-op. If an error occurs within this function, *pRc is set to an
129389 ** SQLite error code before returning.
129391 static void fts3EvalRestart(
129392 Fts3Cursor *pCsr,
129393 Fts3Expr *pExpr,
129394 int *pRc
129396 if( pExpr && *pRc==SQLITE_OK ){
129397 Fts3Phrase *pPhrase = pExpr->pPhrase;
129399 if( pPhrase ){
129400 fts3EvalInvalidatePoslist(pPhrase);
129401 if( pPhrase->bIncr ){
129402 int i;
129403 for(i=0; i<pPhrase->nToken; i++){
129404 Fts3PhraseToken *pToken = &pPhrase->aToken[i];
129405 assert( pToken->pDeferred==0 );
129406 if( pToken->pSegcsr ){
129407 sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
129410 *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
129412 pPhrase->doclist.pNextDocid = 0;
129413 pPhrase->doclist.iDocid = 0;
129416 pExpr->iDocid = 0;
129417 pExpr->bEof = 0;
129418 pExpr->bStart = 0;
129420 fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
129421 fts3EvalRestart(pCsr, pExpr->pRight, pRc);
129426 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
129427 ** expression rooted at pExpr, the cursor iterates through all rows matched
129428 ** by pExpr, calling this function for each row. This function increments
129429 ** the values in Fts3Expr.aMI[] according to the position-list currently
129430 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
129431 ** expression nodes.
129433 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
129434 if( pExpr ){
129435 Fts3Phrase *pPhrase = pExpr->pPhrase;
129436 if( pPhrase && pPhrase->doclist.pList ){
129437 int iCol = 0;
129438 char *p = pPhrase->doclist.pList;
129440 assert( *p );
129441 while( 1 ){
129442 u8 c = 0;
129443 int iCnt = 0;
129444 while( 0xFE & (*p | c) ){
129445 if( (c&0x80)==0 ) iCnt++;
129446 c = *p++ & 0x80;
129449 /* aMI[iCol*3 + 1] = Number of occurrences
129450 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
129452 pExpr->aMI[iCol*3 + 1] += iCnt;
129453 pExpr->aMI[iCol*3 + 2] += (iCnt>0);
129454 if( *p==0x00 ) break;
129456 p += fts3GetVarint32(p, &iCol);
129460 fts3EvalUpdateCounts(pExpr->pLeft);
129461 fts3EvalUpdateCounts(pExpr->pRight);
129466 ** Expression pExpr must be of type FTSQUERY_PHRASE.
129468 ** If it is not already allocated and populated, this function allocates and
129469 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
129470 ** of a NEAR expression, then it also allocates and populates the same array
129471 ** for all other phrases that are part of the NEAR expression.
129473 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
129474 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
129476 static int fts3EvalGatherStats(
129477 Fts3Cursor *pCsr, /* Cursor object */
129478 Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
129480 int rc = SQLITE_OK; /* Return code */
129482 assert( pExpr->eType==FTSQUERY_PHRASE );
129483 if( pExpr->aMI==0 ){
129484 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129485 Fts3Expr *pRoot; /* Root of NEAR expression */
129486 Fts3Expr *p; /* Iterator used for several purposes */
129488 sqlite3_int64 iPrevId = pCsr->iPrevId;
129489 sqlite3_int64 iDocid;
129490 u8 bEof;
129492 /* Find the root of the NEAR expression */
129493 pRoot = pExpr;
129494 while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
129495 pRoot = pRoot->pParent;
129497 iDocid = pRoot->iDocid;
129498 bEof = pRoot->bEof;
129499 assert( pRoot->bStart );
129501 /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
129502 for(p=pRoot; p; p=p->pLeft){
129503 Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
129504 assert( pE->aMI==0 );
129505 pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
129506 if( !pE->aMI ) return SQLITE_NOMEM;
129507 memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
129510 fts3EvalRestart(pCsr, pRoot, &rc);
129512 while( pCsr->isEof==0 && rc==SQLITE_OK ){
129515 /* Ensure the %_content statement is reset. */
129516 if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
129517 assert( sqlite3_data_count(pCsr->pStmt)==0 );
129519 /* Advance to the next document */
129520 fts3EvalNextRow(pCsr, pRoot, &rc);
129521 pCsr->isEof = pRoot->bEof;
129522 pCsr->isRequireSeek = 1;
129523 pCsr->isMatchinfoNeeded = 1;
129524 pCsr->iPrevId = pRoot->iDocid;
129525 }while( pCsr->isEof==0
129526 && pRoot->eType==FTSQUERY_NEAR
129527 && fts3EvalTestDeferredAndNear(pCsr, &rc)
129530 if( rc==SQLITE_OK && pCsr->isEof==0 ){
129531 fts3EvalUpdateCounts(pRoot);
129535 pCsr->isEof = 0;
129536 pCsr->iPrevId = iPrevId;
129538 if( bEof ){
129539 pRoot->bEof = bEof;
129540 }else{
129541 /* Caution: pRoot may iterate through docids in ascending or descending
129542 ** order. For this reason, even though it seems more defensive, the
129543 ** do loop can not be written:
129545 ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
129547 fts3EvalRestart(pCsr, pRoot, &rc);
129549 fts3EvalNextRow(pCsr, pRoot, &rc);
129550 assert( pRoot->bEof==0 );
129551 }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
129552 fts3EvalTestDeferredAndNear(pCsr, &rc);
129555 return rc;
129559 ** This function is used by the matchinfo() module to query a phrase
129560 ** expression node for the following information:
129562 ** 1. The total number of occurrences of the phrase in each column of
129563 ** the FTS table (considering all rows), and
129565 ** 2. For each column, the number of rows in the table for which the
129566 ** column contains at least one instance of the phrase.
129568 ** If no error occurs, SQLITE_OK is returned and the values for each column
129569 ** written into the array aiOut as follows:
129571 ** aiOut[iCol*3 + 1] = Number of occurrences
129572 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
129574 ** Caveats:
129576 ** * If a phrase consists entirely of deferred tokens, then all output
129577 ** values are set to the number of documents in the table. In other
129578 ** words we assume that very common tokens occur exactly once in each
129579 ** column of each row of the table.
129581 ** * If a phrase contains some deferred tokens (and some non-deferred
129582 ** tokens), count the potential occurrence identified by considering
129583 ** the non-deferred tokens instead of actual phrase occurrences.
129585 ** * If the phrase is part of a NEAR expression, then only phrase instances
129586 ** that meet the NEAR constraint are included in the counts.
129588 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
129589 Fts3Cursor *pCsr, /* FTS cursor handle */
129590 Fts3Expr *pExpr, /* Phrase expression */
129591 u32 *aiOut /* Array to write results into (see above) */
129593 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129594 int rc = SQLITE_OK;
129595 int iCol;
129597 if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
129598 assert( pCsr->nDoc>0 );
129599 for(iCol=0; iCol<pTab->nColumn; iCol++){
129600 aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
129601 aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
129603 }else{
129604 rc = fts3EvalGatherStats(pCsr, pExpr);
129605 if( rc==SQLITE_OK ){
129606 assert( pExpr->aMI );
129607 for(iCol=0; iCol<pTab->nColumn; iCol++){
129608 aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
129609 aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
129614 return rc;
129618 ** The expression pExpr passed as the second argument to this function
129619 ** must be of type FTSQUERY_PHRASE.
129621 ** The returned value is either NULL or a pointer to a buffer containing
129622 ** a position-list indicating the occurrences of the phrase in column iCol
129623 ** of the current row.
129625 ** More specifically, the returned buffer contains 1 varint for each
129626 ** occurrence of the phrase in the column, stored using the normal (delta+2)
129627 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
129628 ** if the requested column contains "a b X c d X X" and the position-list
129629 ** for 'X' is requested, the buffer returned may contain:
129631 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
129633 ** This function works regardless of whether or not the phrase is deferred,
129634 ** incremental, or neither.
129636 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
129637 Fts3Cursor *pCsr, /* FTS3 cursor object */
129638 Fts3Expr *pExpr, /* Phrase to return doclist for */
129639 int iCol, /* Column to return position list for */
129640 char **ppOut /* OUT: Pointer to position list */
129642 Fts3Phrase *pPhrase = pExpr->pPhrase;
129643 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129644 char *pIter;
129645 int iThis;
129646 sqlite3_int64 iDocid;
129648 /* If this phrase is applies specifically to some column other than
129649 ** column iCol, return a NULL pointer. */
129650 *ppOut = 0;
129651 assert( iCol>=0 && iCol<pTab->nColumn );
129652 if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
129653 return SQLITE_OK;
129656 iDocid = pExpr->iDocid;
129657 pIter = pPhrase->doclist.pList;
129658 if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
129659 int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
129660 int iMul; /* +1 if csr dir matches index dir, else -1 */
129661 int bOr = 0;
129662 u8 bEof = 0;
129663 u8 bTreeEof = 0;
129664 Fts3Expr *p; /* Used to iterate from pExpr to root */
129665 Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
129667 /* Check if this phrase descends from an OR expression node. If not,
129668 ** return NULL. Otherwise, the entry that corresponds to docid
129669 ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
129670 ** tree that the node is part of has been marked as EOF, but the node
129671 ** itself is not EOF, then it may point to an earlier entry. */
129672 pNear = pExpr;
129673 for(p=pExpr->pParent; p; p=p->pParent){
129674 if( p->eType==FTSQUERY_OR ) bOr = 1;
129675 if( p->eType==FTSQUERY_NEAR ) pNear = p;
129676 if( p->bEof ) bTreeEof = 1;
129678 if( bOr==0 ) return SQLITE_OK;
129680 /* This is the descendent of an OR node. In this case we cannot use
129681 ** an incremental phrase. Load the entire doclist for the phrase
129682 ** into memory in this case. */
129683 if( pPhrase->bIncr ){
129684 int rc = SQLITE_OK;
129685 int bEofSave = pExpr->bEof;
129686 fts3EvalRestart(pCsr, pExpr, &rc);
129687 while( rc==SQLITE_OK && !pExpr->bEof ){
129688 fts3EvalNextRow(pCsr, pExpr, &rc);
129689 if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
129691 pIter = pPhrase->doclist.pList;
129692 assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
129693 if( rc!=SQLITE_OK ) return rc;
129696 iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
129697 while( bTreeEof==1
129698 && pNear->bEof==0
129699 && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
129701 int rc = SQLITE_OK;
129702 fts3EvalNextRow(pCsr, pExpr, &rc);
129703 if( rc!=SQLITE_OK ) return rc;
129704 iDocid = pExpr->iDocid;
129705 pIter = pPhrase->doclist.pList;
129708 bEof = (pPhrase->doclist.nAll==0);
129709 assert( bDescDoclist==0 || bDescDoclist==1 );
129710 assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
129712 if( bEof==0 ){
129713 if( pCsr->bDesc==bDescDoclist ){
129714 int dummy;
129715 if( pNear->bEof ){
129716 /* This expression is already at EOF. So position it to point to the
129717 ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
129718 ** iDocid is already set for this entry, so all that is required is
129719 ** to set pIter to point to the first byte of the last position-list
129720 ** in the doclist.
129722 ** It would also be correct to set pIter and iDocid to zero. In
129723 ** this case, the first call to sqltie3Fts4DoclistPrev() below
129724 ** would also move the iterator to point to the last entry in the
129725 ** doclist. However, this is expensive, as to do so it has to
129726 ** iterate through the entire doclist from start to finish (since
129727 ** it does not know the docid for the last entry). */
129728 pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
129729 fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
129731 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
129732 sqlite3Fts3DoclistPrev(
129733 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
129734 &pIter, &iDocid, &dummy, &bEof
129737 }else{
129738 if( pNear->bEof ){
129739 pIter = 0;
129740 iDocid = 0;
129742 while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
129743 sqlite3Fts3DoclistNext(
129744 bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
129745 &pIter, &iDocid, &bEof
129751 if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
129753 if( pIter==0 ) return SQLITE_OK;
129755 if( *pIter==0x01 ){
129756 pIter++;
129757 pIter += fts3GetVarint32(pIter, &iThis);
129758 }else{
129759 iThis = 0;
129761 while( iThis<iCol ){
129762 fts3ColumnlistCopy(0, &pIter);
129763 if( *pIter==0x00 ) return 0;
129764 pIter++;
129765 pIter += fts3GetVarint32(pIter, &iThis);
129768 *ppOut = ((iCol==iThis)?pIter:0);
129769 return SQLITE_OK;
129773 ** Free all components of the Fts3Phrase structure that were allocated by
129774 ** the eval module. Specifically, this means to free:
129776 ** * the contents of pPhrase->doclist, and
129777 ** * any Fts3MultiSegReader objects held by phrase tokens.
129779 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
129780 if( pPhrase ){
129781 int i;
129782 sqlite3_free(pPhrase->doclist.aAll);
129783 fts3EvalInvalidatePoslist(pPhrase);
129784 memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
129785 for(i=0; i<pPhrase->nToken; i++){
129786 fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
129787 pPhrase->aToken[i].pSegcsr = 0;
129794 ** Return SQLITE_CORRUPT_VTAB.
129796 #ifdef SQLITE_DEBUG
129797 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
129798 return SQLITE_CORRUPT_VTAB;
129800 #endif
129802 #if !SQLITE_CORE
129804 ** Initialize API pointer table, if required.
129806 #ifdef _WIN32
129807 __declspec(dllexport)
129808 #endif
129809 SQLITE_API int sqlite3_fts3_init(
129810 sqlite3 *db,
129811 char **pzErrMsg,
129812 const sqlite3_api_routines *pApi
129814 SQLITE_EXTENSION_INIT2(pApi)
129815 return sqlite3Fts3Init(db);
129817 #endif
129819 #endif
129821 /************** End of fts3.c ************************************************/
129822 /************** Begin file fts3_aux.c ****************************************/
129824 ** 2011 Jan 27
129826 ** The author disclaims copyright to this source code. In place of
129827 ** a legal notice, here is a blessing:
129829 ** May you do good and not evil.
129830 ** May you find forgiveness for yourself and forgive others.
129831 ** May you share freely, never taking more than you give.
129833 ******************************************************************************
129836 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
129838 /* #include <string.h> */
129839 /* #include <assert.h> */
129841 typedef struct Fts3auxTable Fts3auxTable;
129842 typedef struct Fts3auxCursor Fts3auxCursor;
129844 struct Fts3auxTable {
129845 sqlite3_vtab base; /* Base class used by SQLite core */
129846 Fts3Table *pFts3Tab;
129849 struct Fts3auxCursor {
129850 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
129851 Fts3MultiSegReader csr; /* Must be right after "base" */
129852 Fts3SegFilter filter;
129853 char *zStop;
129854 int nStop; /* Byte-length of string zStop */
129855 int iLangid; /* Language id to query */
129856 int isEof; /* True if cursor is at EOF */
129857 sqlite3_int64 iRowid; /* Current rowid */
129859 int iCol; /* Current value of 'col' column */
129860 int nStat; /* Size of aStat[] array */
129861 struct Fts3auxColstats {
129862 sqlite3_int64 nDoc; /* 'documents' values for current csr row */
129863 sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
129864 } *aStat;
129868 ** Schema of the terms table.
129870 #define FTS3_AUX_SCHEMA \
129871 "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
129874 ** This function does all the work for both the xConnect and xCreate methods.
129875 ** These tables have no persistent representation of their own, so xConnect
129876 ** and xCreate are identical operations.
129878 static int fts3auxConnectMethod(
129879 sqlite3 *db, /* Database connection */
129880 void *pUnused, /* Unused */
129881 int argc, /* Number of elements in argv array */
129882 const char * const *argv, /* xCreate/xConnect argument array */
129883 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
129884 char **pzErr /* OUT: sqlite3_malloc'd error message */
129886 char const *zDb; /* Name of database (e.g. "main") */
129887 char const *zFts3; /* Name of fts3 table */
129888 int nDb; /* Result of strlen(zDb) */
129889 int nFts3; /* Result of strlen(zFts3) */
129890 int nByte; /* Bytes of space to allocate here */
129891 int rc; /* value returned by declare_vtab() */
129892 Fts3auxTable *p; /* Virtual table object to return */
129894 UNUSED_PARAMETER(pUnused);
129896 /* The user should invoke this in one of two forms:
129898 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
129899 ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
129901 if( argc!=4 && argc!=5 ) goto bad_args;
129903 zDb = argv[1];
129904 nDb = (int)strlen(zDb);
129905 if( argc==5 ){
129906 if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
129907 zDb = argv[3];
129908 nDb = (int)strlen(zDb);
129909 zFts3 = argv[4];
129910 }else{
129911 goto bad_args;
129913 }else{
129914 zFts3 = argv[3];
129916 nFts3 = (int)strlen(zFts3);
129918 rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
129919 if( rc!=SQLITE_OK ) return rc;
129921 nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
129922 p = (Fts3auxTable *)sqlite3_malloc(nByte);
129923 if( !p ) return SQLITE_NOMEM;
129924 memset(p, 0, nByte);
129926 p->pFts3Tab = (Fts3Table *)&p[1];
129927 p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
129928 p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
129929 p->pFts3Tab->db = db;
129930 p->pFts3Tab->nIndex = 1;
129932 memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
129933 memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
129934 sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
129936 *ppVtab = (sqlite3_vtab *)p;
129937 return SQLITE_OK;
129939 bad_args:
129940 *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
129941 return SQLITE_ERROR;
129945 ** This function does the work for both the xDisconnect and xDestroy methods.
129946 ** These tables have no persistent representation of their own, so xDisconnect
129947 ** and xDestroy are identical operations.
129949 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
129950 Fts3auxTable *p = (Fts3auxTable *)pVtab;
129951 Fts3Table *pFts3 = p->pFts3Tab;
129952 int i;
129954 /* Free any prepared statements held */
129955 for(i=0; i<SizeofArray(pFts3->aStmt); i++){
129956 sqlite3_finalize(pFts3->aStmt[i]);
129958 sqlite3_free(pFts3->zSegmentsTbl);
129959 sqlite3_free(p);
129960 return SQLITE_OK;
129963 #define FTS4AUX_EQ_CONSTRAINT 1
129964 #define FTS4AUX_GE_CONSTRAINT 2
129965 #define FTS4AUX_LE_CONSTRAINT 4
129968 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
129970 static int fts3auxBestIndexMethod(
129971 sqlite3_vtab *pVTab,
129972 sqlite3_index_info *pInfo
129974 int i;
129975 int iEq = -1;
129976 int iGe = -1;
129977 int iLe = -1;
129978 int iLangid = -1;
129979 int iNext = 1; /* Next free argvIndex value */
129981 UNUSED_PARAMETER(pVTab);
129983 /* This vtab delivers always results in "ORDER BY term ASC" order. */
129984 if( pInfo->nOrderBy==1
129985 && pInfo->aOrderBy[0].iColumn==0
129986 && pInfo->aOrderBy[0].desc==0
129988 pInfo->orderByConsumed = 1;
129991 /* Search for equality and range constraints on the "term" column.
129992 ** And equality constraints on the hidden "languageid" column. */
129993 for(i=0; i<pInfo->nConstraint; i++){
129994 if( pInfo->aConstraint[i].usable ){
129995 int op = pInfo->aConstraint[i].op;
129996 int iCol = pInfo->aConstraint[i].iColumn;
129998 if( iCol==0 ){
129999 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
130000 if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
130001 if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
130002 if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
130003 if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
130005 if( iCol==4 ){
130006 if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
130011 if( iEq>=0 ){
130012 pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
130013 pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
130014 pInfo->estimatedCost = 5;
130015 }else{
130016 pInfo->idxNum = 0;
130017 pInfo->estimatedCost = 20000;
130018 if( iGe>=0 ){
130019 pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
130020 pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
130021 pInfo->estimatedCost /= 2;
130023 if( iLe>=0 ){
130024 pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
130025 pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
130026 pInfo->estimatedCost /= 2;
130029 if( iLangid>=0 ){
130030 pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
130031 pInfo->estimatedCost--;
130034 return SQLITE_OK;
130038 ** xOpen - Open a cursor.
130040 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
130041 Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
130043 UNUSED_PARAMETER(pVTab);
130045 pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
130046 if( !pCsr ) return SQLITE_NOMEM;
130047 memset(pCsr, 0, sizeof(Fts3auxCursor));
130049 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
130050 return SQLITE_OK;
130054 ** xClose - Close a cursor.
130056 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
130057 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
130058 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
130060 sqlite3Fts3SegmentsClose(pFts3);
130061 sqlite3Fts3SegReaderFinish(&pCsr->csr);
130062 sqlite3_free((void *)pCsr->filter.zTerm);
130063 sqlite3_free(pCsr->zStop);
130064 sqlite3_free(pCsr->aStat);
130065 sqlite3_free(pCsr);
130066 return SQLITE_OK;
130069 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
130070 if( nSize>pCsr->nStat ){
130071 struct Fts3auxColstats *aNew;
130072 aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
130073 sizeof(struct Fts3auxColstats) * nSize
130075 if( aNew==0 ) return SQLITE_NOMEM;
130076 memset(&aNew[pCsr->nStat], 0,
130077 sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
130079 pCsr->aStat = aNew;
130080 pCsr->nStat = nSize;
130082 return SQLITE_OK;
130086 ** xNext - Advance the cursor to the next row, if any.
130088 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
130089 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
130090 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
130091 int rc;
130093 /* Increment our pretend rowid value. */
130094 pCsr->iRowid++;
130096 for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
130097 if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
130100 rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
130101 if( rc==SQLITE_ROW ){
130102 int i = 0;
130103 int nDoclist = pCsr->csr.nDoclist;
130104 char *aDoclist = pCsr->csr.aDoclist;
130105 int iCol;
130107 int eState = 0;
130109 if( pCsr->zStop ){
130110 int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
130111 int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
130112 if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
130113 pCsr->isEof = 1;
130114 return SQLITE_OK;
130118 if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
130119 memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
130120 iCol = 0;
130122 while( i<nDoclist ){
130123 sqlite3_int64 v = 0;
130125 i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
130126 switch( eState ){
130127 /* State 0. In this state the integer just read was a docid. */
130128 case 0:
130129 pCsr->aStat[0].nDoc++;
130130 eState = 1;
130131 iCol = 0;
130132 break;
130134 /* State 1. In this state we are expecting either a 1, indicating
130135 ** that the following integer will be a column number, or the
130136 ** start of a position list for column 0.
130138 ** The only difference between state 1 and state 2 is that if the
130139 ** integer encountered in state 1 is not 0 or 1, then we need to
130140 ** increment the column 0 "nDoc" count for this term.
130142 case 1:
130143 assert( iCol==0 );
130144 if( v>1 ){
130145 pCsr->aStat[1].nDoc++;
130147 eState = 2;
130148 /* fall through */
130150 case 2:
130151 if( v==0 ){ /* 0x00. Next integer will be a docid. */
130152 eState = 0;
130153 }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
130154 eState = 3;
130155 }else{ /* 2 or greater. A position. */
130156 pCsr->aStat[iCol+1].nOcc++;
130157 pCsr->aStat[0].nOcc++;
130159 break;
130161 /* State 3. The integer just read is a column number. */
130162 default: assert( eState==3 );
130163 iCol = (int)v;
130164 if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
130165 pCsr->aStat[iCol+1].nDoc++;
130166 eState = 2;
130167 break;
130171 pCsr->iCol = 0;
130172 rc = SQLITE_OK;
130173 }else{
130174 pCsr->isEof = 1;
130176 return rc;
130180 ** xFilter - Initialize a cursor to point at the start of its data.
130182 static int fts3auxFilterMethod(
130183 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
130184 int idxNum, /* Strategy index */
130185 const char *idxStr, /* Unused */
130186 int nVal, /* Number of elements in apVal */
130187 sqlite3_value **apVal /* Arguments for the indexing scheme */
130189 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
130190 Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
130191 int rc;
130192 int isScan = 0;
130193 int iLangVal = 0; /* Language id to query */
130195 int iEq = -1; /* Index of term=? value in apVal */
130196 int iGe = -1; /* Index of term>=? value in apVal */
130197 int iLe = -1; /* Index of term<=? value in apVal */
130198 int iLangid = -1; /* Index of languageid=? value in apVal */
130199 int iNext = 0;
130201 UNUSED_PARAMETER(nVal);
130202 UNUSED_PARAMETER(idxStr);
130204 assert( idxStr==0 );
130205 assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
130206 || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
130207 || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
130210 if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
130211 iEq = iNext++;
130212 }else{
130213 isScan = 1;
130214 if( idxNum & FTS4AUX_GE_CONSTRAINT ){
130215 iGe = iNext++;
130217 if( idxNum & FTS4AUX_LE_CONSTRAINT ){
130218 iLe = iNext++;
130221 if( iNext<nVal ){
130222 iLangid = iNext++;
130225 /* In case this cursor is being reused, close and zero it. */
130226 testcase(pCsr->filter.zTerm);
130227 sqlite3Fts3SegReaderFinish(&pCsr->csr);
130228 sqlite3_free((void *)pCsr->filter.zTerm);
130229 sqlite3_free(pCsr->aStat);
130230 memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
130232 pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
130233 if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
130235 if( iEq>=0 || iGe>=0 ){
130236 const unsigned char *zStr = sqlite3_value_text(apVal[0]);
130237 assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
130238 if( zStr ){
130239 pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
130240 pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
130241 if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
130245 if( iLe>=0 ){
130246 pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
130247 pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
130248 if( pCsr->zStop==0 ) return SQLITE_NOMEM;
130251 if( iLangid>=0 ){
130252 iLangVal = sqlite3_value_int(apVal[iLangid]);
130254 /* If the user specified a negative value for the languageid, use zero
130255 ** instead. This works, as the "languageid=?" constraint will also
130256 ** be tested by the VDBE layer. The test will always be false (since
130257 ** this module will not return a row with a negative languageid), and
130258 ** so the overall query will return zero rows. */
130259 if( iLangVal<0 ) iLangVal = 0;
130261 pCsr->iLangid = iLangVal;
130263 rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
130264 pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
130266 if( rc==SQLITE_OK ){
130267 rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
130270 if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
130271 return rc;
130275 ** xEof - Return true if the cursor is at EOF, or false otherwise.
130277 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
130278 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
130279 return pCsr->isEof;
130283 ** xColumn - Return a column value.
130285 static int fts3auxColumnMethod(
130286 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
130287 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
130288 int iCol /* Index of column to read value from */
130290 Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
130292 assert( p->isEof==0 );
130293 switch( iCol ){
130294 case 0: /* term */
130295 sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
130296 break;
130298 case 1: /* col */
130299 if( p->iCol ){
130300 sqlite3_result_int(pCtx, p->iCol-1);
130301 }else{
130302 sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
130304 break;
130306 case 2: /* documents */
130307 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
130308 break;
130310 case 3: /* occurrences */
130311 sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
130312 break;
130314 default: /* languageid */
130315 assert( iCol==4 );
130316 sqlite3_result_int(pCtx, p->iLangid);
130317 break;
130320 return SQLITE_OK;
130324 ** xRowid - Return the current rowid for the cursor.
130326 static int fts3auxRowidMethod(
130327 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
130328 sqlite_int64 *pRowid /* OUT: Rowid value */
130330 Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
130331 *pRowid = pCsr->iRowid;
130332 return SQLITE_OK;
130336 ** Register the fts3aux module with database connection db. Return SQLITE_OK
130337 ** if successful or an error code if sqlite3_create_module() fails.
130339 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
130340 static const sqlite3_module fts3aux_module = {
130341 0, /* iVersion */
130342 fts3auxConnectMethod, /* xCreate */
130343 fts3auxConnectMethod, /* xConnect */
130344 fts3auxBestIndexMethod, /* xBestIndex */
130345 fts3auxDisconnectMethod, /* xDisconnect */
130346 fts3auxDisconnectMethod, /* xDestroy */
130347 fts3auxOpenMethod, /* xOpen */
130348 fts3auxCloseMethod, /* xClose */
130349 fts3auxFilterMethod, /* xFilter */
130350 fts3auxNextMethod, /* xNext */
130351 fts3auxEofMethod, /* xEof */
130352 fts3auxColumnMethod, /* xColumn */
130353 fts3auxRowidMethod, /* xRowid */
130354 0, /* xUpdate */
130355 0, /* xBegin */
130356 0, /* xSync */
130357 0, /* xCommit */
130358 0, /* xRollback */
130359 0, /* xFindFunction */
130360 0, /* xRename */
130361 0, /* xSavepoint */
130362 0, /* xRelease */
130363 0 /* xRollbackTo */
130365 int rc; /* Return code */
130367 rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
130368 return rc;
130371 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
130373 /************** End of fts3_aux.c ********************************************/
130374 /************** Begin file fts3_expr.c ***************************************/
130376 ** 2008 Nov 28
130378 ** The author disclaims copyright to this source code. In place of
130379 ** a legal notice, here is a blessing:
130381 ** May you do good and not evil.
130382 ** May you find forgiveness for yourself and forgive others.
130383 ** May you share freely, never taking more than you give.
130385 ******************************************************************************
130387 ** This module contains code that implements a parser for fts3 query strings
130388 ** (the right-hand argument to the MATCH operator). Because the supported
130389 ** syntax is relatively simple, the whole tokenizer/parser system is
130390 ** hand-coded.
130392 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
130395 ** By default, this module parses the legacy syntax that has been
130396 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
130397 ** is defined, then it uses the new syntax. The differences between
130398 ** the new and the old syntaxes are:
130400 ** a) The new syntax supports parenthesis. The old does not.
130402 ** b) The new syntax supports the AND and NOT operators. The old does not.
130404 ** c) The old syntax supports the "-" token qualifier. This is not
130405 ** supported by the new syntax (it is replaced by the NOT operator).
130407 ** d) When using the old syntax, the OR operator has a greater precedence
130408 ** than an implicit AND. When using the new, both implicity and explicit
130409 ** AND operators have a higher precedence than OR.
130411 ** If compiled with SQLITE_TEST defined, then this module exports the
130412 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
130413 ** to zero causes the module to use the old syntax. If it is set to
130414 ** non-zero the new syntax is activated. This is so both syntaxes can
130415 ** be tested using a single build of testfixture.
130417 ** The following describes the syntax supported by the fts3 MATCH
130418 ** operator in a similar format to that used by the lemon parser
130419 ** generator. This module does not use actually lemon, it uses a
130420 ** custom parser.
130422 ** query ::= andexpr (OR andexpr)*.
130424 ** andexpr ::= notexpr (AND? notexpr)*.
130426 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
130427 ** notexpr ::= LP query RP.
130429 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
130431 ** distance_opt ::= .
130432 ** distance_opt ::= / INTEGER.
130434 ** phrase ::= TOKEN.
130435 ** phrase ::= COLUMN:TOKEN.
130436 ** phrase ::= "TOKEN TOKEN TOKEN...".
130439 #ifdef SQLITE_TEST
130440 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
130441 #else
130442 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
130443 # define sqlite3_fts3_enable_parentheses 1
130444 # else
130445 # define sqlite3_fts3_enable_parentheses 0
130446 # endif
130447 #endif
130450 ** Default span for NEAR operators.
130452 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
130454 /* #include <string.h> */
130455 /* #include <assert.h> */
130458 ** isNot:
130459 ** This variable is used by function getNextNode(). When getNextNode() is
130460 ** called, it sets ParseContext.isNot to true if the 'next node' is a
130461 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
130462 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
130463 ** zero.
130465 typedef struct ParseContext ParseContext;
130466 struct ParseContext {
130467 sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
130468 int iLangid; /* Language id used with tokenizer */
130469 const char **azCol; /* Array of column names for fts3 table */
130470 int bFts4; /* True to allow FTS4-only syntax */
130471 int nCol; /* Number of entries in azCol[] */
130472 int iDefaultCol; /* Default column to query */
130473 int isNot; /* True if getNextNode() sees a unary - */
130474 sqlite3_context *pCtx; /* Write error message here */
130475 int nNest; /* Number of nested brackets */
130479 ** This function is equivalent to the standard isspace() function.
130481 ** The standard isspace() can be awkward to use safely, because although it
130482 ** is defined to accept an argument of type int, its behavior when passed
130483 ** an integer that falls outside of the range of the unsigned char type
130484 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
130485 ** is defined to accept an argument of type char, and always returns 0 for
130486 ** any values that fall outside of the range of the unsigned char type (i.e.
130487 ** negative values).
130489 static int fts3isspace(char c){
130490 return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
130494 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
130495 ** zero the memory before returning a pointer to it. If unsuccessful,
130496 ** return NULL.
130498 static void *fts3MallocZero(int nByte){
130499 void *pRet = sqlite3_malloc(nByte);
130500 if( pRet ) memset(pRet, 0, nByte);
130501 return pRet;
130504 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
130505 sqlite3_tokenizer *pTokenizer,
130506 int iLangid,
130507 const char *z,
130508 int n,
130509 sqlite3_tokenizer_cursor **ppCsr
130511 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
130512 sqlite3_tokenizer_cursor *pCsr = 0;
130513 int rc;
130515 rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
130516 assert( rc==SQLITE_OK || pCsr==0 );
130517 if( rc==SQLITE_OK ){
130518 pCsr->pTokenizer = pTokenizer;
130519 if( pModule->iVersion>=1 ){
130520 rc = pModule->xLanguageid(pCsr, iLangid);
130521 if( rc!=SQLITE_OK ){
130522 pModule->xClose(pCsr);
130523 pCsr = 0;
130527 *ppCsr = pCsr;
130528 return rc;
130532 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
130533 ** call fts3ExprParse(). So this forward declaration is required.
130535 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
130538 ** Extract the next token from buffer z (length n) using the tokenizer
130539 ** and other information (column names etc.) in pParse. Create an Fts3Expr
130540 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
130541 ** single token and set *ppExpr to point to it. If the end of the buffer is
130542 ** reached before a token is found, set *ppExpr to zero. It is the
130543 ** responsibility of the caller to eventually deallocate the allocated
130544 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
130546 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
130547 ** fails.
130549 static int getNextToken(
130550 ParseContext *pParse, /* fts3 query parse context */
130551 int iCol, /* Value for Fts3Phrase.iColumn */
130552 const char *z, int n, /* Input string */
130553 Fts3Expr **ppExpr, /* OUT: expression */
130554 int *pnConsumed /* OUT: Number of bytes consumed */
130556 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
130557 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
130558 int rc;
130559 sqlite3_tokenizer_cursor *pCursor;
130560 Fts3Expr *pRet = 0;
130561 int nConsumed = 0;
130563 rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
130564 if( rc==SQLITE_OK ){
130565 const char *zToken;
130566 int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
130567 int nByte; /* total space to allocate */
130569 rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
130571 if( (rc==SQLITE_OK || rc==SQLITE_DONE) && sqlite3_fts3_enable_parentheses ){
130572 int i;
130573 if( rc==SQLITE_DONE ) iStart = n;
130574 for(i=0; i<iStart; i++){
130575 if( z[i]=='(' ){
130576 pParse->nNest++;
130577 rc = fts3ExprParse(pParse, &z[i+1], n-i-1, &pRet, &nConsumed);
130578 if( rc==SQLITE_OK && !pRet ){
130579 rc = SQLITE_DONE;
130581 nConsumed = (int)(i + 1 + nConsumed);
130582 break;
130585 if( z[i]==')' ){
130586 rc = SQLITE_DONE;
130587 pParse->nNest--;
130588 nConsumed = i+1;
130589 break;
130594 if( nConsumed==0 && rc==SQLITE_OK ){
130595 nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
130596 pRet = (Fts3Expr *)fts3MallocZero(nByte);
130597 if( !pRet ){
130598 rc = SQLITE_NOMEM;
130599 }else{
130600 pRet->eType = FTSQUERY_PHRASE;
130601 pRet->pPhrase = (Fts3Phrase *)&pRet[1];
130602 pRet->pPhrase->nToken = 1;
130603 pRet->pPhrase->iColumn = iCol;
130604 pRet->pPhrase->aToken[0].n = nToken;
130605 pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
130606 memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
130608 if( iEnd<n && z[iEnd]=='*' ){
130609 pRet->pPhrase->aToken[0].isPrefix = 1;
130610 iEnd++;
130613 while( 1 ){
130614 if( !sqlite3_fts3_enable_parentheses
130615 && iStart>0 && z[iStart-1]=='-'
130617 pParse->isNot = 1;
130618 iStart--;
130619 }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
130620 pRet->pPhrase->aToken[0].bFirst = 1;
130621 iStart--;
130622 }else{
130623 break;
130628 nConsumed = iEnd;
130631 pModule->xClose(pCursor);
130634 *pnConsumed = nConsumed;
130635 *ppExpr = pRet;
130636 return rc;
130641 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
130642 ** then free the old allocation.
130644 static void *fts3ReallocOrFree(void *pOrig, int nNew){
130645 void *pRet = sqlite3_realloc(pOrig, nNew);
130646 if( !pRet ){
130647 sqlite3_free(pOrig);
130649 return pRet;
130653 ** Buffer zInput, length nInput, contains the contents of a quoted string
130654 ** that appeared as part of an fts3 query expression. Neither quote character
130655 ** is included in the buffer. This function attempts to tokenize the entire
130656 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
130657 ** containing the results.
130659 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
130660 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
130661 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
130662 ** to 0.
130664 static int getNextString(
130665 ParseContext *pParse, /* fts3 query parse context */
130666 const char *zInput, int nInput, /* Input string */
130667 Fts3Expr **ppExpr /* OUT: expression */
130669 sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
130670 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
130671 int rc;
130672 Fts3Expr *p = 0;
130673 sqlite3_tokenizer_cursor *pCursor = 0;
130674 char *zTemp = 0;
130675 int nTemp = 0;
130677 const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
130678 int nToken = 0;
130680 /* The final Fts3Expr data structure, including the Fts3Phrase,
130681 ** Fts3PhraseToken structures token buffers are all stored as a single
130682 ** allocation so that the expression can be freed with a single call to
130683 ** sqlite3_free(). Setting this up requires a two pass approach.
130685 ** The first pass, in the block below, uses a tokenizer cursor to iterate
130686 ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
130687 ** to assemble data in two dynamic buffers:
130689 ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
130690 ** structure, followed by the array of Fts3PhraseToken
130691 ** structures. This pass only populates the Fts3PhraseToken array.
130693 ** Buffer zTemp: Contains copies of all tokens.
130695 ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
130696 ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
130697 ** structures.
130699 rc = sqlite3Fts3OpenTokenizer(
130700 pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
130701 if( rc==SQLITE_OK ){
130702 int ii;
130703 for(ii=0; rc==SQLITE_OK; ii++){
130704 const char *zByte;
130705 int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
130706 rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
130707 if( rc==SQLITE_OK ){
130708 Fts3PhraseToken *pToken;
130710 p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
130711 if( !p ) goto no_mem;
130713 zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
130714 if( !zTemp ) goto no_mem;
130716 assert( nToken==ii );
130717 pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
130718 memset(pToken, 0, sizeof(Fts3PhraseToken));
130720 memcpy(&zTemp[nTemp], zByte, nByte);
130721 nTemp += nByte;
130723 pToken->n = nByte;
130724 pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
130725 pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
130726 nToken = ii+1;
130730 pModule->xClose(pCursor);
130731 pCursor = 0;
130734 if( rc==SQLITE_DONE ){
130735 int jj;
130736 char *zBuf = 0;
130738 p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
130739 if( !p ) goto no_mem;
130740 memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
130741 p->eType = FTSQUERY_PHRASE;
130742 p->pPhrase = (Fts3Phrase *)&p[1];
130743 p->pPhrase->iColumn = pParse->iDefaultCol;
130744 p->pPhrase->nToken = nToken;
130746 zBuf = (char *)&p->pPhrase->aToken[nToken];
130747 if( zTemp ){
130748 memcpy(zBuf, zTemp, nTemp);
130749 sqlite3_free(zTemp);
130750 }else{
130751 assert( nTemp==0 );
130754 for(jj=0; jj<p->pPhrase->nToken; jj++){
130755 p->pPhrase->aToken[jj].z = zBuf;
130756 zBuf += p->pPhrase->aToken[jj].n;
130758 rc = SQLITE_OK;
130761 *ppExpr = p;
130762 return rc;
130763 no_mem:
130765 if( pCursor ){
130766 pModule->xClose(pCursor);
130768 sqlite3_free(zTemp);
130769 sqlite3_free(p);
130770 *ppExpr = 0;
130771 return SQLITE_NOMEM;
130775 ** The output variable *ppExpr is populated with an allocated Fts3Expr
130776 ** structure, or set to 0 if the end of the input buffer is reached.
130778 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
130779 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
130780 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
130782 static int getNextNode(
130783 ParseContext *pParse, /* fts3 query parse context */
130784 const char *z, int n, /* Input string */
130785 Fts3Expr **ppExpr, /* OUT: expression */
130786 int *pnConsumed /* OUT: Number of bytes consumed */
130788 static const struct Fts3Keyword {
130789 char *z; /* Keyword text */
130790 unsigned char n; /* Length of the keyword */
130791 unsigned char parenOnly; /* Only valid in paren mode */
130792 unsigned char eType; /* Keyword code */
130793 } aKeyword[] = {
130794 { "OR" , 2, 0, FTSQUERY_OR },
130795 { "AND", 3, 1, FTSQUERY_AND },
130796 { "NOT", 3, 1, FTSQUERY_NOT },
130797 { "NEAR", 4, 0, FTSQUERY_NEAR }
130799 int ii;
130800 int iCol;
130801 int iColLen;
130802 int rc;
130803 Fts3Expr *pRet = 0;
130805 const char *zInput = z;
130806 int nInput = n;
130808 pParse->isNot = 0;
130810 /* Skip over any whitespace before checking for a keyword, an open or
130811 ** close bracket, or a quoted string.
130813 while( nInput>0 && fts3isspace(*zInput) ){
130814 nInput--;
130815 zInput++;
130817 if( nInput==0 ){
130818 return SQLITE_DONE;
130821 /* See if we are dealing with a keyword. */
130822 for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
130823 const struct Fts3Keyword *pKey = &aKeyword[ii];
130825 if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
130826 continue;
130829 if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
130830 int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
130831 int nKey = pKey->n;
130832 char cNext;
130834 /* If this is a "NEAR" keyword, check for an explicit nearness. */
130835 if( pKey->eType==FTSQUERY_NEAR ){
130836 assert( nKey==4 );
130837 if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
130838 nNear = 0;
130839 for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
130840 nNear = nNear * 10 + (zInput[nKey] - '0');
130845 /* At this point this is probably a keyword. But for that to be true,
130846 ** the next byte must contain either whitespace, an open or close
130847 ** parenthesis, a quote character, or EOF.
130849 cNext = zInput[nKey];
130850 if( fts3isspace(cNext)
130851 || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
130853 pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
130854 if( !pRet ){
130855 return SQLITE_NOMEM;
130857 pRet->eType = pKey->eType;
130858 pRet->nNear = nNear;
130859 *ppExpr = pRet;
130860 *pnConsumed = (int)((zInput - z) + nKey);
130861 return SQLITE_OK;
130864 /* Turns out that wasn't a keyword after all. This happens if the
130865 ** user has supplied a token such as "ORacle". Continue.
130870 /* See if we are dealing with a quoted phrase. If this is the case, then
130871 ** search for the closing quote and pass the whole string to getNextString()
130872 ** for processing. This is easy to do, as fts3 has no syntax for escaping
130873 ** a quote character embedded in a string.
130875 if( *zInput=='"' ){
130876 for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
130877 *pnConsumed = (int)((zInput - z) + ii + 1);
130878 if( ii==nInput ){
130879 return SQLITE_ERROR;
130881 return getNextString(pParse, &zInput[1], ii-1, ppExpr);
130885 /* If control flows to this point, this must be a regular token, or
130886 ** the end of the input. Read a regular token using the sqlite3_tokenizer
130887 ** interface. Before doing so, figure out if there is an explicit
130888 ** column specifier for the token.
130890 ** TODO: Strangely, it is not possible to associate a column specifier
130891 ** with a quoted phrase, only with a single token. Not sure if this was
130892 ** an implementation artifact or an intentional decision when fts3 was
130893 ** first implemented. Whichever it was, this module duplicates the
130894 ** limitation.
130896 iCol = pParse->iDefaultCol;
130897 iColLen = 0;
130898 for(ii=0; ii<pParse->nCol; ii++){
130899 const char *zStr = pParse->azCol[ii];
130900 int nStr = (int)strlen(zStr);
130901 if( nInput>nStr && zInput[nStr]==':'
130902 && sqlite3_strnicmp(zStr, zInput, nStr)==0
130904 iCol = ii;
130905 iColLen = (int)((zInput - z) + nStr + 1);
130906 break;
130909 rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
130910 *pnConsumed += iColLen;
130911 return rc;
130915 ** The argument is an Fts3Expr structure for a binary operator (any type
130916 ** except an FTSQUERY_PHRASE). Return an integer value representing the
130917 ** precedence of the operator. Lower values have a higher precedence (i.e.
130918 ** group more tightly). For example, in the C language, the == operator
130919 ** groups more tightly than ||, and would therefore have a higher precedence.
130921 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
130922 ** is defined), the order of the operators in precedence from highest to
130923 ** lowest is:
130925 ** NEAR
130926 ** NOT
130927 ** AND (including implicit ANDs)
130928 ** OR
130930 ** Note that when using the old query syntax, the OR operator has a higher
130931 ** precedence than the AND operator.
130933 static int opPrecedence(Fts3Expr *p){
130934 assert( p->eType!=FTSQUERY_PHRASE );
130935 if( sqlite3_fts3_enable_parentheses ){
130936 return p->eType;
130937 }else if( p->eType==FTSQUERY_NEAR ){
130938 return 1;
130939 }else if( p->eType==FTSQUERY_OR ){
130940 return 2;
130942 assert( p->eType==FTSQUERY_AND );
130943 return 3;
130947 ** Argument ppHead contains a pointer to the current head of a query
130948 ** expression tree being parsed. pPrev is the expression node most recently
130949 ** inserted into the tree. This function adds pNew, which is always a binary
130950 ** operator node, into the expression tree based on the relative precedence
130951 ** of pNew and the existing nodes of the tree. This may result in the head
130952 ** of the tree changing, in which case *ppHead is set to the new root node.
130954 static void insertBinaryOperator(
130955 Fts3Expr **ppHead, /* Pointer to the root node of a tree */
130956 Fts3Expr *pPrev, /* Node most recently inserted into the tree */
130957 Fts3Expr *pNew /* New binary node to insert into expression tree */
130959 Fts3Expr *pSplit = pPrev;
130960 while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
130961 pSplit = pSplit->pParent;
130964 if( pSplit->pParent ){
130965 assert( pSplit->pParent->pRight==pSplit );
130966 pSplit->pParent->pRight = pNew;
130967 pNew->pParent = pSplit->pParent;
130968 }else{
130969 *ppHead = pNew;
130971 pNew->pLeft = pSplit;
130972 pSplit->pParent = pNew;
130976 ** Parse the fts3 query expression found in buffer z, length n. This function
130977 ** returns either when the end of the buffer is reached or an unmatched
130978 ** closing bracket - ')' - is encountered.
130980 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
130981 ** parsed form of the expression and *pnConsumed is set to the number of
130982 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
130983 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
130985 static int fts3ExprParse(
130986 ParseContext *pParse, /* fts3 query parse context */
130987 const char *z, int n, /* Text of MATCH query */
130988 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
130989 int *pnConsumed /* OUT: Number of bytes consumed */
130991 Fts3Expr *pRet = 0;
130992 Fts3Expr *pPrev = 0;
130993 Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
130994 int nIn = n;
130995 const char *zIn = z;
130996 int rc = SQLITE_OK;
130997 int isRequirePhrase = 1;
130999 while( rc==SQLITE_OK ){
131000 Fts3Expr *p = 0;
131001 int nByte = 0;
131002 rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
131003 if( rc==SQLITE_OK ){
131004 int isPhrase;
131006 if( !sqlite3_fts3_enable_parentheses
131007 && p->eType==FTSQUERY_PHRASE && pParse->isNot
131009 /* Create an implicit NOT operator. */
131010 Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
131011 if( !pNot ){
131012 sqlite3Fts3ExprFree(p);
131013 rc = SQLITE_NOMEM;
131014 goto exprparse_out;
131016 pNot->eType = FTSQUERY_NOT;
131017 pNot->pRight = p;
131018 p->pParent = pNot;
131019 if( pNotBranch ){
131020 pNot->pLeft = pNotBranch;
131021 pNotBranch->pParent = pNot;
131023 pNotBranch = pNot;
131024 p = pPrev;
131025 }else{
131026 int eType = p->eType;
131027 isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
131029 /* The isRequirePhrase variable is set to true if a phrase or
131030 ** an expression contained in parenthesis is required. If a
131031 ** binary operator (AND, OR, NOT or NEAR) is encounted when
131032 ** isRequirePhrase is set, this is a syntax error.
131034 if( !isPhrase && isRequirePhrase ){
131035 sqlite3Fts3ExprFree(p);
131036 rc = SQLITE_ERROR;
131037 goto exprparse_out;
131040 if( isPhrase && !isRequirePhrase ){
131041 /* Insert an implicit AND operator. */
131042 Fts3Expr *pAnd;
131043 assert( pRet && pPrev );
131044 pAnd = fts3MallocZero(sizeof(Fts3Expr));
131045 if( !pAnd ){
131046 sqlite3Fts3ExprFree(p);
131047 rc = SQLITE_NOMEM;
131048 goto exprparse_out;
131050 pAnd->eType = FTSQUERY_AND;
131051 insertBinaryOperator(&pRet, pPrev, pAnd);
131052 pPrev = pAnd;
131055 /* This test catches attempts to make either operand of a NEAR
131056 ** operator something other than a phrase. For example, either of
131057 ** the following:
131059 ** (bracketed expression) NEAR phrase
131060 ** phrase NEAR (bracketed expression)
131062 ** Return an error in either case.
131064 if( pPrev && (
131065 (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
131066 || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
131068 sqlite3Fts3ExprFree(p);
131069 rc = SQLITE_ERROR;
131070 goto exprparse_out;
131073 if( isPhrase ){
131074 if( pRet ){
131075 assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
131076 pPrev->pRight = p;
131077 p->pParent = pPrev;
131078 }else{
131079 pRet = p;
131081 }else{
131082 insertBinaryOperator(&pRet, pPrev, p);
131084 isRequirePhrase = !isPhrase;
131086 assert( nByte>0 );
131088 assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
131089 nIn -= nByte;
131090 zIn += nByte;
131091 pPrev = p;
131094 if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
131095 rc = SQLITE_ERROR;
131098 if( rc==SQLITE_DONE ){
131099 rc = SQLITE_OK;
131100 if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
131101 if( !pRet ){
131102 rc = SQLITE_ERROR;
131103 }else{
131104 Fts3Expr *pIter = pNotBranch;
131105 while( pIter->pLeft ){
131106 pIter = pIter->pLeft;
131108 pIter->pLeft = pRet;
131109 pRet->pParent = pIter;
131110 pRet = pNotBranch;
131114 *pnConsumed = n - nIn;
131116 exprparse_out:
131117 if( rc!=SQLITE_OK ){
131118 sqlite3Fts3ExprFree(pRet);
131119 sqlite3Fts3ExprFree(pNotBranch);
131120 pRet = 0;
131122 *ppExpr = pRet;
131123 return rc;
131127 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
131128 ** as the only argument is more than nMaxDepth.
131130 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
131131 int rc = SQLITE_OK;
131132 if( p ){
131133 if( nMaxDepth<0 ){
131134 rc = SQLITE_TOOBIG;
131135 }else{
131136 rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
131137 if( rc==SQLITE_OK ){
131138 rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
131142 return rc;
131146 ** This function attempts to transform the expression tree at (*pp) to
131147 ** an equivalent but more balanced form. The tree is modified in place.
131148 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
131149 ** new root expression node.
131151 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
131153 ** Otherwise, if an error occurs, an SQLite error code is returned and
131154 ** expression (*pp) freed.
131156 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
131157 int rc = SQLITE_OK; /* Return code */
131158 Fts3Expr *pRoot = *pp; /* Initial root node */
131159 Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
131160 int eType = pRoot->eType; /* Type of node in this tree */
131162 if( nMaxDepth==0 ){
131163 rc = SQLITE_ERROR;
131166 if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
131167 Fts3Expr **apLeaf;
131168 apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
131169 if( 0==apLeaf ){
131170 rc = SQLITE_NOMEM;
131171 }else{
131172 memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
131175 if( rc==SQLITE_OK ){
131176 int i;
131177 Fts3Expr *p;
131179 /* Set $p to point to the left-most leaf in the tree of eType nodes. */
131180 for(p=pRoot; p->eType==eType; p=p->pLeft){
131181 assert( p->pParent==0 || p->pParent->pLeft==p );
131182 assert( p->pLeft && p->pRight );
131185 /* This loop runs once for each leaf in the tree of eType nodes. */
131186 while( 1 ){
131187 int iLvl;
131188 Fts3Expr *pParent = p->pParent; /* Current parent of p */
131190 assert( pParent==0 || pParent->pLeft==p );
131191 p->pParent = 0;
131192 if( pParent ){
131193 pParent->pLeft = 0;
131194 }else{
131195 pRoot = 0;
131197 rc = fts3ExprBalance(&p, nMaxDepth-1);
131198 if( rc!=SQLITE_OK ) break;
131200 for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
131201 if( apLeaf[iLvl]==0 ){
131202 apLeaf[iLvl] = p;
131203 p = 0;
131204 }else{
131205 assert( pFree );
131206 pFree->pLeft = apLeaf[iLvl];
131207 pFree->pRight = p;
131208 pFree->pLeft->pParent = pFree;
131209 pFree->pRight->pParent = pFree;
131211 p = pFree;
131212 pFree = pFree->pParent;
131213 p->pParent = 0;
131214 apLeaf[iLvl] = 0;
131217 if( p ){
131218 sqlite3Fts3ExprFree(p);
131219 rc = SQLITE_TOOBIG;
131220 break;
131223 /* If that was the last leaf node, break out of the loop */
131224 if( pParent==0 ) break;
131226 /* Set $p to point to the next leaf in the tree of eType nodes */
131227 for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
131229 /* Remove pParent from the original tree. */
131230 assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
131231 pParent->pRight->pParent = pParent->pParent;
131232 if( pParent->pParent ){
131233 pParent->pParent->pLeft = pParent->pRight;
131234 }else{
131235 assert( pParent==pRoot );
131236 pRoot = pParent->pRight;
131239 /* Link pParent into the free node list. It will be used as an
131240 ** internal node of the new tree. */
131241 pParent->pParent = pFree;
131242 pFree = pParent;
131245 if( rc==SQLITE_OK ){
131246 p = 0;
131247 for(i=0; i<nMaxDepth; i++){
131248 if( apLeaf[i] ){
131249 if( p==0 ){
131250 p = apLeaf[i];
131251 p->pParent = 0;
131252 }else{
131253 assert( pFree!=0 );
131254 pFree->pRight = p;
131255 pFree->pLeft = apLeaf[i];
131256 pFree->pLeft->pParent = pFree;
131257 pFree->pRight->pParent = pFree;
131259 p = pFree;
131260 pFree = pFree->pParent;
131261 p->pParent = 0;
131265 pRoot = p;
131266 }else{
131267 /* An error occurred. Delete the contents of the apLeaf[] array
131268 ** and pFree list. Everything else is cleaned up by the call to
131269 ** sqlite3Fts3ExprFree(pRoot) below. */
131270 Fts3Expr *pDel;
131271 for(i=0; i<nMaxDepth; i++){
131272 sqlite3Fts3ExprFree(apLeaf[i]);
131274 while( (pDel=pFree)!=0 ){
131275 pFree = pDel->pParent;
131276 sqlite3_free(pDel);
131280 assert( pFree==0 );
131281 sqlite3_free( apLeaf );
131285 if( rc!=SQLITE_OK ){
131286 sqlite3Fts3ExprFree(pRoot);
131287 pRoot = 0;
131289 *pp = pRoot;
131290 return rc;
131294 ** This function is similar to sqlite3Fts3ExprParse(), with the following
131295 ** differences:
131297 ** 1. It does not do expression rebalancing.
131298 ** 2. It does not check that the expression does not exceed the
131299 ** maximum allowable depth.
131300 ** 3. Even if it fails, *ppExpr may still be set to point to an
131301 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
131302 ** in this case.
131304 static int fts3ExprParseUnbalanced(
131305 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
131306 int iLangid, /* Language id for tokenizer */
131307 char **azCol, /* Array of column names for fts3 table */
131308 int bFts4, /* True to allow FTS4-only syntax */
131309 int nCol, /* Number of entries in azCol[] */
131310 int iDefaultCol, /* Default column to query */
131311 const char *z, int n, /* Text of MATCH query */
131312 Fts3Expr **ppExpr /* OUT: Parsed query structure */
131314 int nParsed;
131315 int rc;
131316 ParseContext sParse;
131318 memset(&sParse, 0, sizeof(ParseContext));
131319 sParse.pTokenizer = pTokenizer;
131320 sParse.iLangid = iLangid;
131321 sParse.azCol = (const char **)azCol;
131322 sParse.nCol = nCol;
131323 sParse.iDefaultCol = iDefaultCol;
131324 sParse.bFts4 = bFts4;
131325 if( z==0 ){
131326 *ppExpr = 0;
131327 return SQLITE_OK;
131329 if( n<0 ){
131330 n = (int)strlen(z);
131332 rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
131333 assert( rc==SQLITE_OK || *ppExpr==0 );
131335 /* Check for mismatched parenthesis */
131336 if( rc==SQLITE_OK && sParse.nNest ){
131337 rc = SQLITE_ERROR;
131340 return rc;
131344 ** Parameters z and n contain a pointer to and length of a buffer containing
131345 ** an fts3 query expression, respectively. This function attempts to parse the
131346 ** query expression and create a tree of Fts3Expr structures representing the
131347 ** parsed expression. If successful, *ppExpr is set to point to the head
131348 ** of the parsed expression tree and SQLITE_OK is returned. If an error
131349 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
131350 ** error) is returned and *ppExpr is set to 0.
131352 ** If parameter n is a negative number, then z is assumed to point to a
131353 ** nul-terminated string and the length is determined using strlen().
131355 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
131356 ** use to normalize query tokens while parsing the expression. The azCol[]
131357 ** array, which is assumed to contain nCol entries, should contain the names
131358 ** of each column in the target fts3 table, in order from left to right.
131359 ** Column names must be nul-terminated strings.
131361 ** The iDefaultCol parameter should be passed the index of the table column
131362 ** that appears on the left-hand-side of the MATCH operator (the default
131363 ** column to match against for tokens for which a column name is not explicitly
131364 ** specified as part of the query string), or -1 if tokens may by default
131365 ** match any table column.
131367 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
131368 sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
131369 int iLangid, /* Language id for tokenizer */
131370 char **azCol, /* Array of column names for fts3 table */
131371 int bFts4, /* True to allow FTS4-only syntax */
131372 int nCol, /* Number of entries in azCol[] */
131373 int iDefaultCol, /* Default column to query */
131374 const char *z, int n, /* Text of MATCH query */
131375 Fts3Expr **ppExpr, /* OUT: Parsed query structure */
131376 char **pzErr /* OUT: Error message (sqlite3_malloc) */
131378 int rc = fts3ExprParseUnbalanced(
131379 pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
131382 /* Rebalance the expression. And check that its depth does not exceed
131383 ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
131384 if( rc==SQLITE_OK && *ppExpr ){
131385 rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
131386 if( rc==SQLITE_OK ){
131387 rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
131391 if( rc!=SQLITE_OK ){
131392 sqlite3Fts3ExprFree(*ppExpr);
131393 *ppExpr = 0;
131394 if( rc==SQLITE_TOOBIG ){
131395 *pzErr = sqlite3_mprintf(
131396 "FTS expression tree is too large (maximum depth %d)",
131397 SQLITE_FTS3_MAX_EXPR_DEPTH
131399 rc = SQLITE_ERROR;
131400 }else if( rc==SQLITE_ERROR ){
131401 *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
131405 return rc;
131409 ** Free a single node of an expression tree.
131411 static void fts3FreeExprNode(Fts3Expr *p){
131412 assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
131413 sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
131414 sqlite3_free(p->aMI);
131415 sqlite3_free(p);
131419 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
131421 ** This function would be simpler if it recursively called itself. But
131422 ** that would mean passing a sufficiently large expression to ExprParse()
131423 ** could cause a stack overflow.
131425 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
131426 Fts3Expr *p;
131427 assert( pDel==0 || pDel->pParent==0 );
131428 for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
131429 assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
131431 while( p ){
131432 Fts3Expr *pParent = p->pParent;
131433 fts3FreeExprNode(p);
131434 if( pParent && p==pParent->pLeft && pParent->pRight ){
131435 p = pParent->pRight;
131436 while( p && (p->pLeft || p->pRight) ){
131437 assert( p==p->pParent->pRight || p==p->pParent->pLeft );
131438 p = (p->pLeft ? p->pLeft : p->pRight);
131440 }else{
131441 p = pParent;
131446 /****************************************************************************
131447 *****************************************************************************
131448 ** Everything after this point is just test code.
131451 #ifdef SQLITE_TEST
131453 /* #include <stdio.h> */
131456 ** Function to query the hash-table of tokenizers (see README.tokenizers).
131458 static int queryTestTokenizer(
131459 sqlite3 *db,
131460 const char *zName,
131461 const sqlite3_tokenizer_module **pp
131463 int rc;
131464 sqlite3_stmt *pStmt;
131465 const char zSql[] = "SELECT fts3_tokenizer(?)";
131467 *pp = 0;
131468 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
131469 if( rc!=SQLITE_OK ){
131470 return rc;
131473 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
131474 if( SQLITE_ROW==sqlite3_step(pStmt) ){
131475 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
131476 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
131480 return sqlite3_finalize(pStmt);
131484 ** Return a pointer to a buffer containing a text representation of the
131485 ** expression passed as the first argument. The buffer is obtained from
131486 ** sqlite3_malloc(). It is the responsibility of the caller to use
131487 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
131488 ** NULL is returned.
131490 ** If the second argument is not NULL, then its contents are prepended to
131491 ** the returned expression text and then freed using sqlite3_free().
131493 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
131494 if( pExpr==0 ){
131495 return sqlite3_mprintf("");
131497 switch( pExpr->eType ){
131498 case FTSQUERY_PHRASE: {
131499 Fts3Phrase *pPhrase = pExpr->pPhrase;
131500 int i;
131501 zBuf = sqlite3_mprintf(
131502 "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
131503 for(i=0; zBuf && i<pPhrase->nToken; i++){
131504 zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
131505 pPhrase->aToken[i].n, pPhrase->aToken[i].z,
131506 (pPhrase->aToken[i].isPrefix?"+":"")
131509 return zBuf;
131512 case FTSQUERY_NEAR:
131513 zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
131514 break;
131515 case FTSQUERY_NOT:
131516 zBuf = sqlite3_mprintf("%zNOT ", zBuf);
131517 break;
131518 case FTSQUERY_AND:
131519 zBuf = sqlite3_mprintf("%zAND ", zBuf);
131520 break;
131521 case FTSQUERY_OR:
131522 zBuf = sqlite3_mprintf("%zOR ", zBuf);
131523 break;
131526 if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
131527 if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
131528 if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
131530 if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
131531 if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
131533 return zBuf;
131537 ** This is the implementation of a scalar SQL function used to test the
131538 ** expression parser. It should be called as follows:
131540 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
131542 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
131543 ** to parse the query expression (see README.tokenizers). The second argument
131544 ** is the query expression to parse. Each subsequent argument is the name
131545 ** of a column of the fts3 table that the query expression may refer to.
131546 ** For example:
131548 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
131550 static void fts3ExprTest(
131551 sqlite3_context *context,
131552 int argc,
131553 sqlite3_value **argv
131555 sqlite3_tokenizer_module const *pModule = 0;
131556 sqlite3_tokenizer *pTokenizer = 0;
131557 int rc;
131558 char **azCol = 0;
131559 const char *zExpr;
131560 int nExpr;
131561 int nCol;
131562 int ii;
131563 Fts3Expr *pExpr;
131564 char *zBuf = 0;
131565 sqlite3 *db = sqlite3_context_db_handle(context);
131567 if( argc<3 ){
131568 sqlite3_result_error(context,
131569 "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
131571 return;
131574 rc = queryTestTokenizer(db,
131575 (const char *)sqlite3_value_text(argv[0]), &pModule);
131576 if( rc==SQLITE_NOMEM ){
131577 sqlite3_result_error_nomem(context);
131578 goto exprtest_out;
131579 }else if( !pModule ){
131580 sqlite3_result_error(context, "No such tokenizer module", -1);
131581 goto exprtest_out;
131584 rc = pModule->xCreate(0, 0, &pTokenizer);
131585 assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
131586 if( rc==SQLITE_NOMEM ){
131587 sqlite3_result_error_nomem(context);
131588 goto exprtest_out;
131590 pTokenizer->pModule = pModule;
131592 zExpr = (const char *)sqlite3_value_text(argv[1]);
131593 nExpr = sqlite3_value_bytes(argv[1]);
131594 nCol = argc-2;
131595 azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
131596 if( !azCol ){
131597 sqlite3_result_error_nomem(context);
131598 goto exprtest_out;
131600 for(ii=0; ii<nCol; ii++){
131601 azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
131604 if( sqlite3_user_data(context) ){
131605 char *zDummy = 0;
131606 rc = sqlite3Fts3ExprParse(
131607 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
131609 assert( rc==SQLITE_OK || pExpr==0 );
131610 sqlite3_free(zDummy);
131611 }else{
131612 rc = fts3ExprParseUnbalanced(
131613 pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
131617 if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
131618 sqlite3Fts3ExprFree(pExpr);
131619 sqlite3_result_error(context, "Error parsing expression", -1);
131620 }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
131621 sqlite3_result_error_nomem(context);
131622 }else{
131623 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
131624 sqlite3_free(zBuf);
131627 sqlite3Fts3ExprFree(pExpr);
131629 exprtest_out:
131630 if( pModule && pTokenizer ){
131631 rc = pModule->xDestroy(pTokenizer);
131633 sqlite3_free(azCol);
131637 ** Register the query expression parser test function fts3_exprtest()
131638 ** with database connection db.
131640 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
131641 int rc = sqlite3_create_function(
131642 db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
131644 if( rc==SQLITE_OK ){
131645 rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
131646 -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
131649 return rc;
131652 #endif
131653 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
131655 /************** End of fts3_expr.c *******************************************/
131656 /************** Begin file fts3_hash.c ***************************************/
131658 ** 2001 September 22
131660 ** The author disclaims copyright to this source code. In place of
131661 ** a legal notice, here is a blessing:
131663 ** May you do good and not evil.
131664 ** May you find forgiveness for yourself and forgive others.
131665 ** May you share freely, never taking more than you give.
131667 *************************************************************************
131668 ** This is the implementation of generic hash-tables used in SQLite.
131669 ** We've modified it slightly to serve as a standalone hash table
131670 ** implementation for the full-text indexing module.
131674 ** The code in this file is only compiled if:
131676 ** * The FTS3 module is being built as an extension
131677 ** (in which case SQLITE_CORE is not defined), or
131679 ** * The FTS3 module is being built into the core of
131680 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
131682 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131684 /* #include <assert.h> */
131685 /* #include <stdlib.h> */
131686 /* #include <string.h> */
131690 ** Malloc and Free functions
131692 static void *fts3HashMalloc(int n){
131693 void *p = sqlite3_malloc(n);
131694 if( p ){
131695 memset(p, 0, n);
131697 return p;
131699 static void fts3HashFree(void *p){
131700 sqlite3_free(p);
131703 /* Turn bulk memory into a hash table object by initializing the
131704 ** fields of the Hash structure.
131706 ** "pNew" is a pointer to the hash table that is to be initialized.
131707 ** keyClass is one of the constants
131708 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
131709 ** determines what kind of key the hash table will use. "copyKey" is
131710 ** true if the hash table should make its own private copy of keys and
131711 ** false if it should just use the supplied pointer.
131713 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
131714 assert( pNew!=0 );
131715 assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
131716 pNew->keyClass = keyClass;
131717 pNew->copyKey = copyKey;
131718 pNew->first = 0;
131719 pNew->count = 0;
131720 pNew->htsize = 0;
131721 pNew->ht = 0;
131724 /* Remove all entries from a hash table. Reclaim all memory.
131725 ** Call this routine to delete a hash table or to reset a hash table
131726 ** to the empty state.
131728 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
131729 Fts3HashElem *elem; /* For looping over all elements of the table */
131731 assert( pH!=0 );
131732 elem = pH->first;
131733 pH->first = 0;
131734 fts3HashFree(pH->ht);
131735 pH->ht = 0;
131736 pH->htsize = 0;
131737 while( elem ){
131738 Fts3HashElem *next_elem = elem->next;
131739 if( pH->copyKey && elem->pKey ){
131740 fts3HashFree(elem->pKey);
131742 fts3HashFree(elem);
131743 elem = next_elem;
131745 pH->count = 0;
131749 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
131751 static int fts3StrHash(const void *pKey, int nKey){
131752 const char *z = (const char *)pKey;
131753 unsigned h = 0;
131754 if( nKey<=0 ) nKey = (int) strlen(z);
131755 while( nKey > 0 ){
131756 h = (h<<3) ^ h ^ *z++;
131757 nKey--;
131759 return (int)(h & 0x7fffffff);
131761 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
131762 if( n1!=n2 ) return 1;
131763 return strncmp((const char*)pKey1,(const char*)pKey2,n1);
131767 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
131769 static int fts3BinHash(const void *pKey, int nKey){
131770 int h = 0;
131771 const char *z = (const char *)pKey;
131772 while( nKey-- > 0 ){
131773 h = (h<<3) ^ h ^ *(z++);
131775 return h & 0x7fffffff;
131777 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
131778 if( n1!=n2 ) return 1;
131779 return memcmp(pKey1,pKey2,n1);
131783 ** Return a pointer to the appropriate hash function given the key class.
131785 ** The C syntax in this function definition may be unfamilar to some
131786 ** programmers, so we provide the following additional explanation:
131788 ** The name of the function is "ftsHashFunction". The function takes a
131789 ** single parameter "keyClass". The return value of ftsHashFunction()
131790 ** is a pointer to another function. Specifically, the return value
131791 ** of ftsHashFunction() is a pointer to a function that takes two parameters
131792 ** with types "const void*" and "int" and returns an "int".
131794 static int (*ftsHashFunction(int keyClass))(const void*,int){
131795 if( keyClass==FTS3_HASH_STRING ){
131796 return &fts3StrHash;
131797 }else{
131798 assert( keyClass==FTS3_HASH_BINARY );
131799 return &fts3BinHash;
131804 ** Return a pointer to the appropriate hash function given the key class.
131806 ** For help in interpreted the obscure C code in the function definition,
131807 ** see the header comment on the previous function.
131809 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
131810 if( keyClass==FTS3_HASH_STRING ){
131811 return &fts3StrCompare;
131812 }else{
131813 assert( keyClass==FTS3_HASH_BINARY );
131814 return &fts3BinCompare;
131818 /* Link an element into the hash table
131820 static void fts3HashInsertElement(
131821 Fts3Hash *pH, /* The complete hash table */
131822 struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
131823 Fts3HashElem *pNew /* The element to be inserted */
131825 Fts3HashElem *pHead; /* First element already in pEntry */
131826 pHead = pEntry->chain;
131827 if( pHead ){
131828 pNew->next = pHead;
131829 pNew->prev = pHead->prev;
131830 if( pHead->prev ){ pHead->prev->next = pNew; }
131831 else { pH->first = pNew; }
131832 pHead->prev = pNew;
131833 }else{
131834 pNew->next = pH->first;
131835 if( pH->first ){ pH->first->prev = pNew; }
131836 pNew->prev = 0;
131837 pH->first = pNew;
131839 pEntry->count++;
131840 pEntry->chain = pNew;
131844 /* Resize the hash table so that it cantains "new_size" buckets.
131845 ** "new_size" must be a power of 2. The hash table might fail
131846 ** to resize if sqliteMalloc() fails.
131848 ** Return non-zero if a memory allocation error occurs.
131850 static int fts3Rehash(Fts3Hash *pH, int new_size){
131851 struct _fts3ht *new_ht; /* The new hash table */
131852 Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
131853 int (*xHash)(const void*,int); /* The hash function */
131855 assert( (new_size & (new_size-1))==0 );
131856 new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
131857 if( new_ht==0 ) return 1;
131858 fts3HashFree(pH->ht);
131859 pH->ht = new_ht;
131860 pH->htsize = new_size;
131861 xHash = ftsHashFunction(pH->keyClass);
131862 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
131863 int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
131864 next_elem = elem->next;
131865 fts3HashInsertElement(pH, &new_ht[h], elem);
131867 return 0;
131870 /* This function (for internal use only) locates an element in an
131871 ** hash table that matches the given key. The hash for this key has
131872 ** already been computed and is passed as the 4th parameter.
131874 static Fts3HashElem *fts3FindElementByHash(
131875 const Fts3Hash *pH, /* The pH to be searched */
131876 const void *pKey, /* The key we are searching for */
131877 int nKey,
131878 int h /* The hash for this key. */
131880 Fts3HashElem *elem; /* Used to loop thru the element list */
131881 int count; /* Number of elements left to test */
131882 int (*xCompare)(const void*,int,const void*,int); /* comparison function */
131884 if( pH->ht ){
131885 struct _fts3ht *pEntry = &pH->ht[h];
131886 elem = pEntry->chain;
131887 count = pEntry->count;
131888 xCompare = ftsCompareFunction(pH->keyClass);
131889 while( count-- && elem ){
131890 if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
131891 return elem;
131893 elem = elem->next;
131896 return 0;
131899 /* Remove a single entry from the hash table given a pointer to that
131900 ** element and a hash on the element's key.
131902 static void fts3RemoveElementByHash(
131903 Fts3Hash *pH, /* The pH containing "elem" */
131904 Fts3HashElem* elem, /* The element to be removed from the pH */
131905 int h /* Hash value for the element */
131907 struct _fts3ht *pEntry;
131908 if( elem->prev ){
131909 elem->prev->next = elem->next;
131910 }else{
131911 pH->first = elem->next;
131913 if( elem->next ){
131914 elem->next->prev = elem->prev;
131916 pEntry = &pH->ht[h];
131917 if( pEntry->chain==elem ){
131918 pEntry->chain = elem->next;
131920 pEntry->count--;
131921 if( pEntry->count<=0 ){
131922 pEntry->chain = 0;
131924 if( pH->copyKey && elem->pKey ){
131925 fts3HashFree(elem->pKey);
131927 fts3HashFree( elem );
131928 pH->count--;
131929 if( pH->count<=0 ){
131930 assert( pH->first==0 );
131931 assert( pH->count==0 );
131932 fts3HashClear(pH);
131936 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
131937 const Fts3Hash *pH,
131938 const void *pKey,
131939 int nKey
131941 int h; /* A hash on key */
131942 int (*xHash)(const void*,int); /* The hash function */
131944 if( pH==0 || pH->ht==0 ) return 0;
131945 xHash = ftsHashFunction(pH->keyClass);
131946 assert( xHash!=0 );
131947 h = (*xHash)(pKey,nKey);
131948 assert( (pH->htsize & (pH->htsize-1))==0 );
131949 return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
131953 ** Attempt to locate an element of the hash table pH with a key
131954 ** that matches pKey,nKey. Return the data for this element if it is
131955 ** found, or NULL if there is no match.
131957 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
131958 Fts3HashElem *pElem; /* The element that matches key (if any) */
131960 pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
131961 return pElem ? pElem->data : 0;
131964 /* Insert an element into the hash table pH. The key is pKey,nKey
131965 ** and the data is "data".
131967 ** If no element exists with a matching key, then a new
131968 ** element is created. A copy of the key is made if the copyKey
131969 ** flag is set. NULL is returned.
131971 ** If another element already exists with the same key, then the
131972 ** new data replaces the old data and the old data is returned.
131973 ** The key is not copied in this instance. If a malloc fails, then
131974 ** the new data is returned and the hash table is unchanged.
131976 ** If the "data" parameter to this function is NULL, then the
131977 ** element corresponding to "key" is removed from the hash table.
131979 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
131980 Fts3Hash *pH, /* The hash table to insert into */
131981 const void *pKey, /* The key */
131982 int nKey, /* Number of bytes in the key */
131983 void *data /* The data */
131985 int hraw; /* Raw hash value of the key */
131986 int h; /* the hash of the key modulo hash table size */
131987 Fts3HashElem *elem; /* Used to loop thru the element list */
131988 Fts3HashElem *new_elem; /* New element added to the pH */
131989 int (*xHash)(const void*,int); /* The hash function */
131991 assert( pH!=0 );
131992 xHash = ftsHashFunction(pH->keyClass);
131993 assert( xHash!=0 );
131994 hraw = (*xHash)(pKey, nKey);
131995 assert( (pH->htsize & (pH->htsize-1))==0 );
131996 h = hraw & (pH->htsize-1);
131997 elem = fts3FindElementByHash(pH,pKey,nKey,h);
131998 if( elem ){
131999 void *old_data = elem->data;
132000 if( data==0 ){
132001 fts3RemoveElementByHash(pH,elem,h);
132002 }else{
132003 elem->data = data;
132005 return old_data;
132007 if( data==0 ) return 0;
132008 if( (pH->htsize==0 && fts3Rehash(pH,8))
132009 || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
132011 pH->count = 0;
132012 return data;
132014 assert( pH->htsize>0 );
132015 new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
132016 if( new_elem==0 ) return data;
132017 if( pH->copyKey && pKey!=0 ){
132018 new_elem->pKey = fts3HashMalloc( nKey );
132019 if( new_elem->pKey==0 ){
132020 fts3HashFree(new_elem);
132021 return data;
132023 memcpy((void*)new_elem->pKey, pKey, nKey);
132024 }else{
132025 new_elem->pKey = (void*)pKey;
132027 new_elem->nKey = nKey;
132028 pH->count++;
132029 assert( pH->htsize>0 );
132030 assert( (pH->htsize & (pH->htsize-1))==0 );
132031 h = hraw & (pH->htsize-1);
132032 fts3HashInsertElement(pH, &pH->ht[h], new_elem);
132033 new_elem->data = data;
132034 return 0;
132037 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
132039 /************** End of fts3_hash.c *******************************************/
132040 /************** Begin file fts3_porter.c *************************************/
132042 ** 2006 September 30
132044 ** The author disclaims copyright to this source code. In place of
132045 ** a legal notice, here is a blessing:
132047 ** May you do good and not evil.
132048 ** May you find forgiveness for yourself and forgive others.
132049 ** May you share freely, never taking more than you give.
132051 *************************************************************************
132052 ** Implementation of the full-text-search tokenizer that implements
132053 ** a Porter stemmer.
132057 ** The code in this file is only compiled if:
132059 ** * The FTS3 module is being built as an extension
132060 ** (in which case SQLITE_CORE is not defined), or
132062 ** * The FTS3 module is being built into the core of
132063 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
132065 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132067 /* #include <assert.h> */
132068 /* #include <stdlib.h> */
132069 /* #include <stdio.h> */
132070 /* #include <string.h> */
132074 ** Class derived from sqlite3_tokenizer
132076 typedef struct porter_tokenizer {
132077 sqlite3_tokenizer base; /* Base class */
132078 } porter_tokenizer;
132081 ** Class derived from sqlite3_tokenizer_cursor
132083 typedef struct porter_tokenizer_cursor {
132084 sqlite3_tokenizer_cursor base;
132085 const char *zInput; /* input we are tokenizing */
132086 int nInput; /* size of the input */
132087 int iOffset; /* current position in zInput */
132088 int iToken; /* index of next token to be returned */
132089 char *zToken; /* storage for current token */
132090 int nAllocated; /* space allocated to zToken buffer */
132091 } porter_tokenizer_cursor;
132095 ** Create a new tokenizer instance.
132097 static int porterCreate(
132098 int argc, const char * const *argv,
132099 sqlite3_tokenizer **ppTokenizer
132101 porter_tokenizer *t;
132103 UNUSED_PARAMETER(argc);
132104 UNUSED_PARAMETER(argv);
132106 t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
132107 if( t==NULL ) return SQLITE_NOMEM;
132108 memset(t, 0, sizeof(*t));
132109 *ppTokenizer = &t->base;
132110 return SQLITE_OK;
132114 ** Destroy a tokenizer
132116 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
132117 sqlite3_free(pTokenizer);
132118 return SQLITE_OK;
132122 ** Prepare to begin tokenizing a particular string. The input
132123 ** string to be tokenized is zInput[0..nInput-1]. A cursor
132124 ** used to incrementally tokenize this string is returned in
132125 ** *ppCursor.
132127 static int porterOpen(
132128 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
132129 const char *zInput, int nInput, /* String to be tokenized */
132130 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
132132 porter_tokenizer_cursor *c;
132134 UNUSED_PARAMETER(pTokenizer);
132136 c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
132137 if( c==NULL ) return SQLITE_NOMEM;
132139 c->zInput = zInput;
132140 if( zInput==0 ){
132141 c->nInput = 0;
132142 }else if( nInput<0 ){
132143 c->nInput = (int)strlen(zInput);
132144 }else{
132145 c->nInput = nInput;
132147 c->iOffset = 0; /* start tokenizing at the beginning */
132148 c->iToken = 0;
132149 c->zToken = NULL; /* no space allocated, yet. */
132150 c->nAllocated = 0;
132152 *ppCursor = &c->base;
132153 return SQLITE_OK;
132157 ** Close a tokenization cursor previously opened by a call to
132158 ** porterOpen() above.
132160 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
132161 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
132162 sqlite3_free(c->zToken);
132163 sqlite3_free(c);
132164 return SQLITE_OK;
132167 ** Vowel or consonant
132169 static const char cType[] = {
132170 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
132171 1, 1, 1, 2, 1
132175 ** isConsonant() and isVowel() determine if their first character in
132176 ** the string they point to is a consonant or a vowel, according
132177 ** to Porter ruls.
132179 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
132180 ** 'Y' is a consonant unless it follows another consonant,
132181 ** in which case it is a vowel.
132183 ** In these routine, the letters are in reverse order. So the 'y' rule
132184 ** is that 'y' is a consonant unless it is followed by another
132185 ** consonent.
132187 static int isVowel(const char*);
132188 static int isConsonant(const char *z){
132189 int j;
132190 char x = *z;
132191 if( x==0 ) return 0;
132192 assert( x>='a' && x<='z' );
132193 j = cType[x-'a'];
132194 if( j<2 ) return j;
132195 return z[1]==0 || isVowel(z + 1);
132197 static int isVowel(const char *z){
132198 int j;
132199 char x = *z;
132200 if( x==0 ) return 0;
132201 assert( x>='a' && x<='z' );
132202 j = cType[x-'a'];
132203 if( j<2 ) return 1-j;
132204 return isConsonant(z + 1);
132208 ** Let any sequence of one or more vowels be represented by V and let
132209 ** C be sequence of one or more consonants. Then every word can be
132210 ** represented as:
132212 ** [C] (VC){m} [V]
132214 ** In prose: A word is an optional consonant followed by zero or
132215 ** vowel-consonant pairs followed by an optional vowel. "m" is the
132216 ** number of vowel consonant pairs. This routine computes the value
132217 ** of m for the first i bytes of a word.
132219 ** Return true if the m-value for z is 1 or more. In other words,
132220 ** return true if z contains at least one vowel that is followed
132221 ** by a consonant.
132223 ** In this routine z[] is in reverse order. So we are really looking
132224 ** for an instance of of a consonant followed by a vowel.
132226 static int m_gt_0(const char *z){
132227 while( isVowel(z) ){ z++; }
132228 if( *z==0 ) return 0;
132229 while( isConsonant(z) ){ z++; }
132230 return *z!=0;
132233 /* Like mgt0 above except we are looking for a value of m which is
132234 ** exactly 1
132236 static int m_eq_1(const char *z){
132237 while( isVowel(z) ){ z++; }
132238 if( *z==0 ) return 0;
132239 while( isConsonant(z) ){ z++; }
132240 if( *z==0 ) return 0;
132241 while( isVowel(z) ){ z++; }
132242 if( *z==0 ) return 1;
132243 while( isConsonant(z) ){ z++; }
132244 return *z==0;
132247 /* Like mgt0 above except we are looking for a value of m>1 instead
132248 ** or m>0
132250 static int m_gt_1(const char *z){
132251 while( isVowel(z) ){ z++; }
132252 if( *z==0 ) return 0;
132253 while( isConsonant(z) ){ z++; }
132254 if( *z==0 ) return 0;
132255 while( isVowel(z) ){ z++; }
132256 if( *z==0 ) return 0;
132257 while( isConsonant(z) ){ z++; }
132258 return *z!=0;
132262 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
132264 static int hasVowel(const char *z){
132265 while( isConsonant(z) ){ z++; }
132266 return *z!=0;
132270 ** Return TRUE if the word ends in a double consonant.
132272 ** The text is reversed here. So we are really looking at
132273 ** the first two characters of z[].
132275 static int doubleConsonant(const char *z){
132276 return isConsonant(z) && z[0]==z[1];
132280 ** Return TRUE if the word ends with three letters which
132281 ** are consonant-vowel-consonent and where the final consonant
132282 ** is not 'w', 'x', or 'y'.
132284 ** The word is reversed here. So we are really checking the
132285 ** first three letters and the first one cannot be in [wxy].
132287 static int star_oh(const char *z){
132288 return
132289 isConsonant(z) &&
132290 z[0]!='w' && z[0]!='x' && z[0]!='y' &&
132291 isVowel(z+1) &&
132292 isConsonant(z+2);
132296 ** If the word ends with zFrom and xCond() is true for the stem
132297 ** of the word that preceeds the zFrom ending, then change the
132298 ** ending to zTo.
132300 ** The input word *pz and zFrom are both in reverse order. zTo
132301 ** is in normal order.
132303 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
132304 ** match. Not that TRUE is returned even if xCond() fails and
132305 ** no substitution occurs.
132307 static int stem(
132308 char **pz, /* The word being stemmed (Reversed) */
132309 const char *zFrom, /* If the ending matches this... (Reversed) */
132310 const char *zTo, /* ... change the ending to this (not reversed) */
132311 int (*xCond)(const char*) /* Condition that must be true */
132313 char *z = *pz;
132314 while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
132315 if( *zFrom!=0 ) return 0;
132316 if( xCond && !xCond(z) ) return 1;
132317 while( *zTo ){
132318 *(--z) = *(zTo++);
132320 *pz = z;
132321 return 1;
132325 ** This is the fallback stemmer used when the porter stemmer is
132326 ** inappropriate. The input word is copied into the output with
132327 ** US-ASCII case folding. If the input word is too long (more
132328 ** than 20 bytes if it contains no digits or more than 6 bytes if
132329 ** it contains digits) then word is truncated to 20 or 6 bytes
132330 ** by taking 10 or 3 bytes from the beginning and end.
132332 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
132333 int i, mx, j;
132334 int hasDigit = 0;
132335 for(i=0; i<nIn; i++){
132336 char c = zIn[i];
132337 if( c>='A' && c<='Z' ){
132338 zOut[i] = c - 'A' + 'a';
132339 }else{
132340 if( c>='0' && c<='9' ) hasDigit = 1;
132341 zOut[i] = c;
132344 mx = hasDigit ? 3 : 10;
132345 if( nIn>mx*2 ){
132346 for(j=mx, i=nIn-mx; i<nIn; i++, j++){
132347 zOut[j] = zOut[i];
132349 i = j;
132351 zOut[i] = 0;
132352 *pnOut = i;
132357 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
132358 ** zOut is at least big enough to hold nIn bytes. Write the actual
132359 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
132361 ** Any upper-case characters in the US-ASCII character set ([A-Z])
132362 ** are converted to lower case. Upper-case UTF characters are
132363 ** unchanged.
132365 ** Words that are longer than about 20 bytes are stemmed by retaining
132366 ** a few bytes from the beginning and the end of the word. If the
132367 ** word contains digits, 3 bytes are taken from the beginning and
132368 ** 3 bytes from the end. For long words without digits, 10 bytes
132369 ** are taken from each end. US-ASCII case folding still applies.
132371 ** If the input word contains not digits but does characters not
132372 ** in [a-zA-Z] then no stemming is attempted and this routine just
132373 ** copies the input into the input into the output with US-ASCII
132374 ** case folding.
132376 ** Stemming never increases the length of the word. So there is
132377 ** no chance of overflowing the zOut buffer.
132379 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
132380 int i, j;
132381 char zReverse[28];
132382 char *z, *z2;
132383 if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
132384 /* The word is too big or too small for the porter stemmer.
132385 ** Fallback to the copy stemmer */
132386 copy_stemmer(zIn, nIn, zOut, pnOut);
132387 return;
132389 for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
132390 char c = zIn[i];
132391 if( c>='A' && c<='Z' ){
132392 zReverse[j] = c + 'a' - 'A';
132393 }else if( c>='a' && c<='z' ){
132394 zReverse[j] = c;
132395 }else{
132396 /* The use of a character not in [a-zA-Z] means that we fallback
132397 ** to the copy stemmer */
132398 copy_stemmer(zIn, nIn, zOut, pnOut);
132399 return;
132402 memset(&zReverse[sizeof(zReverse)-5], 0, 5);
132403 z = &zReverse[j+1];
132406 /* Step 1a */
132407 if( z[0]=='s' ){
132409 !stem(&z, "sess", "ss", 0) &&
132410 !stem(&z, "sei", "i", 0) &&
132411 !stem(&z, "ss", "ss", 0)
132417 /* Step 1b */
132418 z2 = z;
132419 if( stem(&z, "dee", "ee", m_gt_0) ){
132420 /* Do nothing. The work was all in the test */
132421 }else if(
132422 (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
132423 && z!=z2
132425 if( stem(&z, "ta", "ate", 0) ||
132426 stem(&z, "lb", "ble", 0) ||
132427 stem(&z, "zi", "ize", 0) ){
132428 /* Do nothing. The work was all in the test */
132429 }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
132431 }else if( m_eq_1(z) && star_oh(z) ){
132432 *(--z) = 'e';
132436 /* Step 1c */
132437 if( z[0]=='y' && hasVowel(z+1) ){
132438 z[0] = 'i';
132441 /* Step 2 */
132442 switch( z[1] ){
132443 case 'a':
132444 if( !stem(&z, "lanoita", "ate", m_gt_0) ){
132445 stem(&z, "lanoit", "tion", m_gt_0);
132447 break;
132448 case 'c':
132449 if( !stem(&z, "icne", "ence", m_gt_0) ){
132450 stem(&z, "icna", "ance", m_gt_0);
132452 break;
132453 case 'e':
132454 stem(&z, "rezi", "ize", m_gt_0);
132455 break;
132456 case 'g':
132457 stem(&z, "igol", "log", m_gt_0);
132458 break;
132459 case 'l':
132460 if( !stem(&z, "ilb", "ble", m_gt_0)
132461 && !stem(&z, "illa", "al", m_gt_0)
132462 && !stem(&z, "iltne", "ent", m_gt_0)
132463 && !stem(&z, "ile", "e", m_gt_0)
132465 stem(&z, "ilsuo", "ous", m_gt_0);
132467 break;
132468 case 'o':
132469 if( !stem(&z, "noitazi", "ize", m_gt_0)
132470 && !stem(&z, "noita", "ate", m_gt_0)
132472 stem(&z, "rota", "ate", m_gt_0);
132474 break;
132475 case 's':
132476 if( !stem(&z, "msila", "al", m_gt_0)
132477 && !stem(&z, "ssenevi", "ive", m_gt_0)
132478 && !stem(&z, "ssenluf", "ful", m_gt_0)
132480 stem(&z, "ssensuo", "ous", m_gt_0);
132482 break;
132483 case 't':
132484 if( !stem(&z, "itila", "al", m_gt_0)
132485 && !stem(&z, "itivi", "ive", m_gt_0)
132487 stem(&z, "itilib", "ble", m_gt_0);
132489 break;
132492 /* Step 3 */
132493 switch( z[0] ){
132494 case 'e':
132495 if( !stem(&z, "etaci", "ic", m_gt_0)
132496 && !stem(&z, "evita", "", m_gt_0)
132498 stem(&z, "ezila", "al", m_gt_0);
132500 break;
132501 case 'i':
132502 stem(&z, "itici", "ic", m_gt_0);
132503 break;
132504 case 'l':
132505 if( !stem(&z, "laci", "ic", m_gt_0) ){
132506 stem(&z, "luf", "", m_gt_0);
132508 break;
132509 case 's':
132510 stem(&z, "ssen", "", m_gt_0);
132511 break;
132514 /* Step 4 */
132515 switch( z[1] ){
132516 case 'a':
132517 if( z[0]=='l' && m_gt_1(z+2) ){
132518 z += 2;
132520 break;
132521 case 'c':
132522 if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
132523 z += 4;
132525 break;
132526 case 'e':
132527 if( z[0]=='r' && m_gt_1(z+2) ){
132528 z += 2;
132530 break;
132531 case 'i':
132532 if( z[0]=='c' && m_gt_1(z+2) ){
132533 z += 2;
132535 break;
132536 case 'l':
132537 if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
132538 z += 4;
132540 break;
132541 case 'n':
132542 if( z[0]=='t' ){
132543 if( z[2]=='a' ){
132544 if( m_gt_1(z+3) ){
132545 z += 3;
132547 }else if( z[2]=='e' ){
132548 if( !stem(&z, "tneme", "", m_gt_1)
132549 && !stem(&z, "tnem", "", m_gt_1)
132551 stem(&z, "tne", "", m_gt_1);
132555 break;
132556 case 'o':
132557 if( z[0]=='u' ){
132558 if( m_gt_1(z+2) ){
132559 z += 2;
132561 }else if( z[3]=='s' || z[3]=='t' ){
132562 stem(&z, "noi", "", m_gt_1);
132564 break;
132565 case 's':
132566 if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
132567 z += 3;
132569 break;
132570 case 't':
132571 if( !stem(&z, "eta", "", m_gt_1) ){
132572 stem(&z, "iti", "", m_gt_1);
132574 break;
132575 case 'u':
132576 if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
132577 z += 3;
132579 break;
132580 case 'v':
132581 case 'z':
132582 if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
132583 z += 3;
132585 break;
132588 /* Step 5a */
132589 if( z[0]=='e' ){
132590 if( m_gt_1(z+1) ){
132592 }else if( m_eq_1(z+1) && !star_oh(z+1) ){
132597 /* Step 5b */
132598 if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
132602 /* z[] is now the stemmed word in reverse order. Flip it back
132603 ** around into forward order and return.
132605 *pnOut = i = (int)strlen(z);
132606 zOut[i] = 0;
132607 while( *z ){
132608 zOut[--i] = *(z++);
132613 ** Characters that can be part of a token. We assume any character
132614 ** whose value is greater than 0x80 (any UTF character) can be
132615 ** part of a token. In other words, delimiters all must have
132616 ** values of 0x7f or lower.
132618 static const char porterIdChar[] = {
132619 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
132620 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
132621 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
132622 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
132623 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
132624 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
132626 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
132629 ** Extract the next token from a tokenization cursor. The cursor must
132630 ** have been opened by a prior call to porterOpen().
132632 static int porterNext(
132633 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
132634 const char **pzToken, /* OUT: *pzToken is the token text */
132635 int *pnBytes, /* OUT: Number of bytes in token */
132636 int *piStartOffset, /* OUT: Starting offset of token */
132637 int *piEndOffset, /* OUT: Ending offset of token */
132638 int *piPosition /* OUT: Position integer of token */
132640 porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
132641 const char *z = c->zInput;
132643 while( c->iOffset<c->nInput ){
132644 int iStartOffset, ch;
132646 /* Scan past delimiter characters */
132647 while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
132648 c->iOffset++;
132651 /* Count non-delimiter characters. */
132652 iStartOffset = c->iOffset;
132653 while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
132654 c->iOffset++;
132657 if( c->iOffset>iStartOffset ){
132658 int n = c->iOffset-iStartOffset;
132659 if( n>c->nAllocated ){
132660 char *pNew;
132661 c->nAllocated = n+20;
132662 pNew = sqlite3_realloc(c->zToken, c->nAllocated);
132663 if( !pNew ) return SQLITE_NOMEM;
132664 c->zToken = pNew;
132666 porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
132667 *pzToken = c->zToken;
132668 *piStartOffset = iStartOffset;
132669 *piEndOffset = c->iOffset;
132670 *piPosition = c->iToken++;
132671 return SQLITE_OK;
132674 return SQLITE_DONE;
132678 ** The set of routines that implement the porter-stemmer tokenizer
132680 static const sqlite3_tokenizer_module porterTokenizerModule = {
132682 porterCreate,
132683 porterDestroy,
132684 porterOpen,
132685 porterClose,
132686 porterNext,
132691 ** Allocate a new porter tokenizer. Return a pointer to the new
132692 ** tokenizer in *ppModule
132694 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
132695 sqlite3_tokenizer_module const**ppModule
132697 *ppModule = &porterTokenizerModule;
132700 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
132702 /************** End of fts3_porter.c *****************************************/
132703 /************** Begin file fts3_tokenizer.c **********************************/
132705 ** 2007 June 22
132707 ** The author disclaims copyright to this source code. In place of
132708 ** a legal notice, here is a blessing:
132710 ** May you do good and not evil.
132711 ** May you find forgiveness for yourself and forgive others.
132712 ** May you share freely, never taking more than you give.
132714 ******************************************************************************
132716 ** This is part of an SQLite module implementing full-text search.
132717 ** This particular file implements the generic tokenizer interface.
132721 ** The code in this file is only compiled if:
132723 ** * The FTS3 module is being built as an extension
132724 ** (in which case SQLITE_CORE is not defined), or
132726 ** * The FTS3 module is being built into the core of
132727 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
132729 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132731 /* #include <assert.h> */
132732 /* #include <string.h> */
132735 ** Implementation of the SQL scalar function for accessing the underlying
132736 ** hash table. This function may be called as follows:
132738 ** SELECT <function-name>(<key-name>);
132739 ** SELECT <function-name>(<key-name>, <pointer>);
132741 ** where <function-name> is the name passed as the second argument
132742 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
132744 ** If the <pointer> argument is specified, it must be a blob value
132745 ** containing a pointer to be stored as the hash data corresponding
132746 ** to the string <key-name>. If <pointer> is not specified, then
132747 ** the string <key-name> must already exist in the has table. Otherwise,
132748 ** an error is returned.
132750 ** Whether or not the <pointer> argument is specified, the value returned
132751 ** is a blob containing the pointer stored as the hash data corresponding
132752 ** to string <key-name> (after the hash-table is updated, if applicable).
132754 static void scalarFunc(
132755 sqlite3_context *context,
132756 int argc,
132757 sqlite3_value **argv
132759 Fts3Hash *pHash;
132760 void *pPtr = 0;
132761 const unsigned char *zName;
132762 int nName;
132764 assert( argc==1 || argc==2 );
132766 pHash = (Fts3Hash *)sqlite3_user_data(context);
132768 zName = sqlite3_value_text(argv[0]);
132769 nName = sqlite3_value_bytes(argv[0])+1;
132771 if( argc==2 ){
132772 void *pOld;
132773 int n = sqlite3_value_bytes(argv[1]);
132774 if( n!=sizeof(pPtr) ){
132775 sqlite3_result_error(context, "argument type mismatch", -1);
132776 return;
132778 pPtr = *(void **)sqlite3_value_blob(argv[1]);
132779 pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
132780 if( pOld==pPtr ){
132781 sqlite3_result_error(context, "out of memory", -1);
132782 return;
132784 }else{
132785 pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
132786 if( !pPtr ){
132787 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
132788 sqlite3_result_error(context, zErr, -1);
132789 sqlite3_free(zErr);
132790 return;
132794 sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
132797 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
132798 static const char isFtsIdChar[] = {
132799 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
132800 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
132801 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
132802 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
132803 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
132804 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
132805 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
132806 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
132808 return (c&0x80 || isFtsIdChar[(int)(c)]);
132811 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
132812 const char *z1;
132813 const char *z2 = 0;
132815 /* Find the start of the next token. */
132816 z1 = zStr;
132817 while( z2==0 ){
132818 char c = *z1;
132819 switch( c ){
132820 case '\0': return 0; /* No more tokens here */
132821 case '\'':
132822 case '"':
132823 case '`': {
132824 z2 = z1;
132825 while( *++z2 && (*z2!=c || *++z2==c) );
132826 break;
132828 case '[':
132829 z2 = &z1[1];
132830 while( *z2 && z2[0]!=']' ) z2++;
132831 if( *z2 ) z2++;
132832 break;
132834 default:
132835 if( sqlite3Fts3IsIdChar(*z1) ){
132836 z2 = &z1[1];
132837 while( sqlite3Fts3IsIdChar(*z2) ) z2++;
132838 }else{
132839 z1++;
132844 *pn = (int)(z2-z1);
132845 return z1;
132848 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
132849 Fts3Hash *pHash, /* Tokenizer hash table */
132850 const char *zArg, /* Tokenizer name */
132851 sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
132852 char **pzErr /* OUT: Set to malloced error message */
132854 int rc;
132855 char *z = (char *)zArg;
132856 int n = 0;
132857 char *zCopy;
132858 char *zEnd; /* Pointer to nul-term of zCopy */
132859 sqlite3_tokenizer_module *m;
132861 zCopy = sqlite3_mprintf("%s", zArg);
132862 if( !zCopy ) return SQLITE_NOMEM;
132863 zEnd = &zCopy[strlen(zCopy)];
132865 z = (char *)sqlite3Fts3NextToken(zCopy, &n);
132866 z[n] = '\0';
132867 sqlite3Fts3Dequote(z);
132869 m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
132870 if( !m ){
132871 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
132872 rc = SQLITE_ERROR;
132873 }else{
132874 char const **aArg = 0;
132875 int iArg = 0;
132876 z = &z[n+1];
132877 while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
132878 int nNew = sizeof(char *)*(iArg+1);
132879 char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
132880 if( !aNew ){
132881 sqlite3_free(zCopy);
132882 sqlite3_free((void *)aArg);
132883 return SQLITE_NOMEM;
132885 aArg = aNew;
132886 aArg[iArg++] = z;
132887 z[n] = '\0';
132888 sqlite3Fts3Dequote(z);
132889 z = &z[n+1];
132891 rc = m->xCreate(iArg, aArg, ppTok);
132892 assert( rc!=SQLITE_OK || *ppTok );
132893 if( rc!=SQLITE_OK ){
132894 *pzErr = sqlite3_mprintf("unknown tokenizer");
132895 }else{
132896 (*ppTok)->pModule = m;
132898 sqlite3_free((void *)aArg);
132901 sqlite3_free(zCopy);
132902 return rc;
132906 #ifdef SQLITE_TEST
132908 #include <tcl.h>
132909 /* #include <string.h> */
132912 ** Implementation of a special SQL scalar function for testing tokenizers
132913 ** designed to be used in concert with the Tcl testing framework. This
132914 ** function must be called with two or more arguments:
132916 ** SELECT <function-name>(<key-name>, ..., <input-string>);
132918 ** where <function-name> is the name passed as the second argument
132919 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
132920 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
132922 ** The return value is a string that may be interpreted as a Tcl
132923 ** list. For each token in the <input-string>, three elements are
132924 ** added to the returned list. The first is the token position, the
132925 ** second is the token text (folded, stemmed, etc.) and the third is the
132926 ** substring of <input-string> associated with the token. For example,
132927 ** using the built-in "simple" tokenizer:
132929 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
132931 ** will return the string:
132933 ** "{0 i I 1 dont don't 2 see see 3 how how}"
132936 static void testFunc(
132937 sqlite3_context *context,
132938 int argc,
132939 sqlite3_value **argv
132941 Fts3Hash *pHash;
132942 sqlite3_tokenizer_module *p;
132943 sqlite3_tokenizer *pTokenizer = 0;
132944 sqlite3_tokenizer_cursor *pCsr = 0;
132946 const char *zErr = 0;
132948 const char *zName;
132949 int nName;
132950 const char *zInput;
132951 int nInput;
132953 const char *azArg[64];
132955 const char *zToken;
132956 int nToken = 0;
132957 int iStart = 0;
132958 int iEnd = 0;
132959 int iPos = 0;
132960 int i;
132962 Tcl_Obj *pRet;
132964 if( argc<2 ){
132965 sqlite3_result_error(context, "insufficient arguments", -1);
132966 return;
132969 nName = sqlite3_value_bytes(argv[0]);
132970 zName = (const char *)sqlite3_value_text(argv[0]);
132971 nInput = sqlite3_value_bytes(argv[argc-1]);
132972 zInput = (const char *)sqlite3_value_text(argv[argc-1]);
132974 pHash = (Fts3Hash *)sqlite3_user_data(context);
132975 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
132977 if( !p ){
132978 char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
132979 sqlite3_result_error(context, zErr, -1);
132980 sqlite3_free(zErr);
132981 return;
132984 pRet = Tcl_NewObj();
132985 Tcl_IncrRefCount(pRet);
132987 for(i=1; i<argc-1; i++){
132988 azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
132991 if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
132992 zErr = "error in xCreate()";
132993 goto finish;
132995 pTokenizer->pModule = p;
132996 if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
132997 zErr = "error in xOpen()";
132998 goto finish;
133001 while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
133002 Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
133003 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
133004 zToken = &zInput[iStart];
133005 nToken = iEnd-iStart;
133006 Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
133009 if( SQLITE_OK!=p->xClose(pCsr) ){
133010 zErr = "error in xClose()";
133011 goto finish;
133013 if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
133014 zErr = "error in xDestroy()";
133015 goto finish;
133018 finish:
133019 if( zErr ){
133020 sqlite3_result_error(context, zErr, -1);
133021 }else{
133022 sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
133024 Tcl_DecrRefCount(pRet);
133027 static
133028 int registerTokenizer(
133029 sqlite3 *db,
133030 char *zName,
133031 const sqlite3_tokenizer_module *p
133033 int rc;
133034 sqlite3_stmt *pStmt;
133035 const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
133037 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
133038 if( rc!=SQLITE_OK ){
133039 return rc;
133042 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
133043 sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
133044 sqlite3_step(pStmt);
133046 return sqlite3_finalize(pStmt);
133049 static
133050 int queryTokenizer(
133051 sqlite3 *db,
133052 char *zName,
133053 const sqlite3_tokenizer_module **pp
133055 int rc;
133056 sqlite3_stmt *pStmt;
133057 const char zSql[] = "SELECT fts3_tokenizer(?)";
133059 *pp = 0;
133060 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
133061 if( rc!=SQLITE_OK ){
133062 return rc;
133065 sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
133066 if( SQLITE_ROW==sqlite3_step(pStmt) ){
133067 if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
133068 memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
133072 return sqlite3_finalize(pStmt);
133075 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
133078 ** Implementation of the scalar function fts3_tokenizer_internal_test().
133079 ** This function is used for testing only, it is not included in the
133080 ** build unless SQLITE_TEST is defined.
133082 ** The purpose of this is to test that the fts3_tokenizer() function
133083 ** can be used as designed by the C-code in the queryTokenizer and
133084 ** registerTokenizer() functions above. These two functions are repeated
133085 ** in the README.tokenizer file as an example, so it is important to
133086 ** test them.
133088 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
133089 ** function with no arguments. An assert() will fail if a problem is
133090 ** detected. i.e.:
133092 ** SELECT fts3_tokenizer_internal_test();
133095 static void intTestFunc(
133096 sqlite3_context *context,
133097 int argc,
133098 sqlite3_value **argv
133100 int rc;
133101 const sqlite3_tokenizer_module *p1;
133102 const sqlite3_tokenizer_module *p2;
133103 sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
133105 UNUSED_PARAMETER(argc);
133106 UNUSED_PARAMETER(argv);
133108 /* Test the query function */
133109 sqlite3Fts3SimpleTokenizerModule(&p1);
133110 rc = queryTokenizer(db, "simple", &p2);
133111 assert( rc==SQLITE_OK );
133112 assert( p1==p2 );
133113 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
133114 assert( rc==SQLITE_ERROR );
133115 assert( p2==0 );
133116 assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
133118 /* Test the storage function */
133119 rc = registerTokenizer(db, "nosuchtokenizer", p1);
133120 assert( rc==SQLITE_OK );
133121 rc = queryTokenizer(db, "nosuchtokenizer", &p2);
133122 assert( rc==SQLITE_OK );
133123 assert( p2==p1 );
133125 sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
133128 #endif
133131 ** Set up SQL objects in database db used to access the contents of
133132 ** the hash table pointed to by argument pHash. The hash table must
133133 ** been initialized to use string keys, and to take a private copy
133134 ** of the key when a value is inserted. i.e. by a call similar to:
133136 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
133138 ** This function adds a scalar function (see header comment above
133139 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
133140 ** defined at compilation time, a temporary virtual table (see header
133141 ** comment above struct HashTableVtab) to the database schema. Both
133142 ** provide read/write access to the contents of *pHash.
133144 ** The third argument to this function, zName, is used as the name
133145 ** of both the scalar and, if created, the virtual table.
133147 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
133148 sqlite3 *db,
133149 Fts3Hash *pHash,
133150 const char *zName
133152 int rc = SQLITE_OK;
133153 void *p = (void *)pHash;
133154 const int any = SQLITE_ANY;
133156 #ifdef SQLITE_TEST
133157 char *zTest = 0;
133158 char *zTest2 = 0;
133159 void *pdb = (void *)db;
133160 zTest = sqlite3_mprintf("%s_test", zName);
133161 zTest2 = sqlite3_mprintf("%s_internal_test", zName);
133162 if( !zTest || !zTest2 ){
133163 rc = SQLITE_NOMEM;
133165 #endif
133167 if( SQLITE_OK==rc ){
133168 rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
133170 if( SQLITE_OK==rc ){
133171 rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
133173 #ifdef SQLITE_TEST
133174 if( SQLITE_OK==rc ){
133175 rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
133177 if( SQLITE_OK==rc ){
133178 rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
133180 #endif
133182 #ifdef SQLITE_TEST
133183 sqlite3_free(zTest);
133184 sqlite3_free(zTest2);
133185 #endif
133187 return rc;
133190 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133192 /************** End of fts3_tokenizer.c **************************************/
133193 /************** Begin file fts3_tokenizer1.c *********************************/
133195 ** 2006 Oct 10
133197 ** The author disclaims copyright to this source code. In place of
133198 ** a legal notice, here is a blessing:
133200 ** May you do good and not evil.
133201 ** May you find forgiveness for yourself and forgive others.
133202 ** May you share freely, never taking more than you give.
133204 ******************************************************************************
133206 ** Implementation of the "simple" full-text-search tokenizer.
133210 ** The code in this file is only compiled if:
133212 ** * The FTS3 module is being built as an extension
133213 ** (in which case SQLITE_CORE is not defined), or
133215 ** * The FTS3 module is being built into the core of
133216 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
133218 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133220 /* #include <assert.h> */
133221 /* #include <stdlib.h> */
133222 /* #include <stdio.h> */
133223 /* #include <string.h> */
133226 typedef struct simple_tokenizer {
133227 sqlite3_tokenizer base;
133228 char delim[128]; /* flag ASCII delimiters */
133229 } simple_tokenizer;
133231 typedef struct simple_tokenizer_cursor {
133232 sqlite3_tokenizer_cursor base;
133233 const char *pInput; /* input we are tokenizing */
133234 int nBytes; /* size of the input */
133235 int iOffset; /* current position in pInput */
133236 int iToken; /* index of next token to be returned */
133237 char *pToken; /* storage for current token */
133238 int nTokenAllocated; /* space allocated to zToken buffer */
133239 } simple_tokenizer_cursor;
133242 static int simpleDelim(simple_tokenizer *t, unsigned char c){
133243 return c<0x80 && t->delim[c];
133245 static int fts3_isalnum(int x){
133246 return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
133250 ** Create a new tokenizer instance.
133252 static int simpleCreate(
133253 int argc, const char * const *argv,
133254 sqlite3_tokenizer **ppTokenizer
133256 simple_tokenizer *t;
133258 t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
133259 if( t==NULL ) return SQLITE_NOMEM;
133260 memset(t, 0, sizeof(*t));
133262 /* TODO(shess) Delimiters need to remain the same from run to run,
133263 ** else we need to reindex. One solution would be a meta-table to
133264 ** track such information in the database, then we'd only want this
133265 ** information on the initial create.
133267 if( argc>1 ){
133268 int i, n = (int)strlen(argv[1]);
133269 for(i=0; i<n; i++){
133270 unsigned char ch = argv[1][i];
133271 /* We explicitly don't support UTF-8 delimiters for now. */
133272 if( ch>=0x80 ){
133273 sqlite3_free(t);
133274 return SQLITE_ERROR;
133276 t->delim[ch] = 1;
133278 } else {
133279 /* Mark non-alphanumeric ASCII characters as delimiters */
133280 int i;
133281 for(i=1; i<0x80; i++){
133282 t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
133286 *ppTokenizer = &t->base;
133287 return SQLITE_OK;
133291 ** Destroy a tokenizer
133293 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
133294 sqlite3_free(pTokenizer);
133295 return SQLITE_OK;
133299 ** Prepare to begin tokenizing a particular string. The input
133300 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
133301 ** used to incrementally tokenize this string is returned in
133302 ** *ppCursor.
133304 static int simpleOpen(
133305 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
133306 const char *pInput, int nBytes, /* String to be tokenized */
133307 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
133309 simple_tokenizer_cursor *c;
133311 UNUSED_PARAMETER(pTokenizer);
133313 c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
133314 if( c==NULL ) return SQLITE_NOMEM;
133316 c->pInput = pInput;
133317 if( pInput==0 ){
133318 c->nBytes = 0;
133319 }else if( nBytes<0 ){
133320 c->nBytes = (int)strlen(pInput);
133321 }else{
133322 c->nBytes = nBytes;
133324 c->iOffset = 0; /* start tokenizing at the beginning */
133325 c->iToken = 0;
133326 c->pToken = NULL; /* no space allocated, yet. */
133327 c->nTokenAllocated = 0;
133329 *ppCursor = &c->base;
133330 return SQLITE_OK;
133334 ** Close a tokenization cursor previously opened by a call to
133335 ** simpleOpen() above.
133337 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
133338 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
133339 sqlite3_free(c->pToken);
133340 sqlite3_free(c);
133341 return SQLITE_OK;
133345 ** Extract the next token from a tokenization cursor. The cursor must
133346 ** have been opened by a prior call to simpleOpen().
133348 static int simpleNext(
133349 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
133350 const char **ppToken, /* OUT: *ppToken is the token text */
133351 int *pnBytes, /* OUT: Number of bytes in token */
133352 int *piStartOffset, /* OUT: Starting offset of token */
133353 int *piEndOffset, /* OUT: Ending offset of token */
133354 int *piPosition /* OUT: Position integer of token */
133356 simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
133357 simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
133358 unsigned char *p = (unsigned char *)c->pInput;
133360 while( c->iOffset<c->nBytes ){
133361 int iStartOffset;
133363 /* Scan past delimiter characters */
133364 while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
133365 c->iOffset++;
133368 /* Count non-delimiter characters. */
133369 iStartOffset = c->iOffset;
133370 while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
133371 c->iOffset++;
133374 if( c->iOffset>iStartOffset ){
133375 int i, n = c->iOffset-iStartOffset;
133376 if( n>c->nTokenAllocated ){
133377 char *pNew;
133378 c->nTokenAllocated = n+20;
133379 pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
133380 if( !pNew ) return SQLITE_NOMEM;
133381 c->pToken = pNew;
133383 for(i=0; i<n; i++){
133384 /* TODO(shess) This needs expansion to handle UTF-8
133385 ** case-insensitivity.
133387 unsigned char ch = p[iStartOffset+i];
133388 c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
133390 *ppToken = c->pToken;
133391 *pnBytes = n;
133392 *piStartOffset = iStartOffset;
133393 *piEndOffset = c->iOffset;
133394 *piPosition = c->iToken++;
133396 return SQLITE_OK;
133399 return SQLITE_DONE;
133403 ** The set of routines that implement the simple tokenizer
133405 static const sqlite3_tokenizer_module simpleTokenizerModule = {
133407 simpleCreate,
133408 simpleDestroy,
133409 simpleOpen,
133410 simpleClose,
133411 simpleNext,
133416 ** Allocate a new simple tokenizer. Return a pointer to the new
133417 ** tokenizer in *ppModule
133419 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
133420 sqlite3_tokenizer_module const**ppModule
133422 *ppModule = &simpleTokenizerModule;
133425 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133427 /************** End of fts3_tokenizer1.c *************************************/
133428 /************** Begin file fts3_tokenize_vtab.c ******************************/
133430 ** 2013 Apr 22
133432 ** The author disclaims copyright to this source code. In place of
133433 ** a legal notice, here is a blessing:
133435 ** May you do good and not evil.
133436 ** May you find forgiveness for yourself and forgive others.
133437 ** May you share freely, never taking more than you give.
133439 ******************************************************************************
133441 ** This file contains code for the "fts3tokenize" virtual table module.
133442 ** An fts3tokenize virtual table is created as follows:
133444 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
133445 ** <tokenizer-name>, <arg-1>, ...
133446 ** );
133448 ** The table created has the following schema:
133450 ** CREATE TABLE <tbl>(input, token, start, end, position)
133452 ** When queried, the query must include a WHERE clause of type:
133454 ** input = <string>
133456 ** The virtual table module tokenizes this <string>, using the FTS3
133457 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
133458 ** statement and returns one row for each token in the result. With
133459 ** fields set as follows:
133461 ** input: Always set to a copy of <string>
133462 ** token: A token from the input.
133463 ** start: Byte offset of the token within the input <string>.
133464 ** end: Byte offset of the byte immediately following the end of the
133465 ** token within the input string.
133466 ** pos: Token offset of token within input.
133469 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133471 /* #include <string.h> */
133472 /* #include <assert.h> */
133474 typedef struct Fts3tokTable Fts3tokTable;
133475 typedef struct Fts3tokCursor Fts3tokCursor;
133478 ** Virtual table structure.
133480 struct Fts3tokTable {
133481 sqlite3_vtab base; /* Base class used by SQLite core */
133482 const sqlite3_tokenizer_module *pMod;
133483 sqlite3_tokenizer *pTok;
133487 ** Virtual table cursor structure.
133489 struct Fts3tokCursor {
133490 sqlite3_vtab_cursor base; /* Base class used by SQLite core */
133491 char *zInput; /* Input string */
133492 sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
133493 int iRowid; /* Current 'rowid' value */
133494 const char *zToken; /* Current 'token' value */
133495 int nToken; /* Size of zToken in bytes */
133496 int iStart; /* Current 'start' value */
133497 int iEnd; /* Current 'end' value */
133498 int iPos; /* Current 'pos' value */
133502 ** Query FTS for the tokenizer implementation named zName.
133504 static int fts3tokQueryTokenizer(
133505 Fts3Hash *pHash,
133506 const char *zName,
133507 const sqlite3_tokenizer_module **pp,
133508 char **pzErr
133510 sqlite3_tokenizer_module *p;
133511 int nName = (int)strlen(zName);
133513 p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
133514 if( !p ){
133515 *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
133516 return SQLITE_ERROR;
133519 *pp = p;
133520 return SQLITE_OK;
133524 ** The second argument, argv[], is an array of pointers to nul-terminated
133525 ** strings. This function makes a copy of the array and strings into a
133526 ** single block of memory. It then dequotes any of the strings that appear
133527 ** to be quoted.
133529 ** If successful, output parameter *pazDequote is set to point at the
133530 ** array of dequoted strings and SQLITE_OK is returned. The caller is
133531 ** responsible for eventually calling sqlite3_free() to free the array
133532 ** in this case. Or, if an error occurs, an SQLite error code is returned.
133533 ** The final value of *pazDequote is undefined in this case.
133535 static int fts3tokDequoteArray(
133536 int argc, /* Number of elements in argv[] */
133537 const char * const *argv, /* Input array */
133538 char ***pazDequote /* Output array */
133540 int rc = SQLITE_OK; /* Return code */
133541 if( argc==0 ){
133542 *pazDequote = 0;
133543 }else{
133544 int i;
133545 int nByte = 0;
133546 char **azDequote;
133548 for(i=0; i<argc; i++){
133549 nByte += (int)(strlen(argv[i]) + 1);
133552 *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
133553 if( azDequote==0 ){
133554 rc = SQLITE_NOMEM;
133555 }else{
133556 char *pSpace = (char *)&azDequote[argc];
133557 for(i=0; i<argc; i++){
133558 int n = (int)strlen(argv[i]);
133559 azDequote[i] = pSpace;
133560 memcpy(pSpace, argv[i], n+1);
133561 sqlite3Fts3Dequote(pSpace);
133562 pSpace += (n+1);
133567 return rc;
133571 ** Schema of the tokenizer table.
133573 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
133576 ** This function does all the work for both the xConnect and xCreate methods.
133577 ** These tables have no persistent representation of their own, so xConnect
133578 ** and xCreate are identical operations.
133580 ** argv[0]: module name
133581 ** argv[1]: database name
133582 ** argv[2]: table name
133583 ** argv[3]: first argument (tokenizer name)
133585 static int fts3tokConnectMethod(
133586 sqlite3 *db, /* Database connection */
133587 void *pHash, /* Hash table of tokenizers */
133588 int argc, /* Number of elements in argv array */
133589 const char * const *argv, /* xCreate/xConnect argument array */
133590 sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
133591 char **pzErr /* OUT: sqlite3_malloc'd error message */
133593 Fts3tokTable *pTab;
133594 const sqlite3_tokenizer_module *pMod = 0;
133595 sqlite3_tokenizer *pTok = 0;
133596 int rc;
133597 char **azDequote = 0;
133598 int nDequote;
133600 rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
133601 if( rc!=SQLITE_OK ) return rc;
133603 nDequote = argc-3;
133604 rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
133606 if( rc==SQLITE_OK ){
133607 const char *zModule;
133608 if( nDequote<1 ){
133609 zModule = "simple";
133610 }else{
133611 zModule = azDequote[0];
133613 rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
133616 assert( (rc==SQLITE_OK)==(pMod!=0) );
133617 if( rc==SQLITE_OK ){
133618 const char * const *azArg = (const char * const *)&azDequote[1];
133619 rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
133622 if( rc==SQLITE_OK ){
133623 pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
133624 if( pTab==0 ){
133625 rc = SQLITE_NOMEM;
133629 if( rc==SQLITE_OK ){
133630 memset(pTab, 0, sizeof(Fts3tokTable));
133631 pTab->pMod = pMod;
133632 pTab->pTok = pTok;
133633 *ppVtab = &pTab->base;
133634 }else{
133635 if( pTok ){
133636 pMod->xDestroy(pTok);
133640 sqlite3_free(azDequote);
133641 return rc;
133645 ** This function does the work for both the xDisconnect and xDestroy methods.
133646 ** These tables have no persistent representation of their own, so xDisconnect
133647 ** and xDestroy are identical operations.
133649 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
133650 Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
133652 pTab->pMod->xDestroy(pTab->pTok);
133653 sqlite3_free(pTab);
133654 return SQLITE_OK;
133658 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
133660 static int fts3tokBestIndexMethod(
133661 sqlite3_vtab *pVTab,
133662 sqlite3_index_info *pInfo
133664 int i;
133665 UNUSED_PARAMETER(pVTab);
133667 for(i=0; i<pInfo->nConstraint; i++){
133668 if( pInfo->aConstraint[i].usable
133669 && pInfo->aConstraint[i].iColumn==0
133670 && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
133672 pInfo->idxNum = 1;
133673 pInfo->aConstraintUsage[i].argvIndex = 1;
133674 pInfo->aConstraintUsage[i].omit = 1;
133675 pInfo->estimatedCost = 1;
133676 return SQLITE_OK;
133680 pInfo->idxNum = 0;
133681 assert( pInfo->estimatedCost>1000000.0 );
133683 return SQLITE_OK;
133687 ** xOpen - Open a cursor.
133689 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
133690 Fts3tokCursor *pCsr;
133691 UNUSED_PARAMETER(pVTab);
133693 pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
133694 if( pCsr==0 ){
133695 return SQLITE_NOMEM;
133697 memset(pCsr, 0, sizeof(Fts3tokCursor));
133699 *ppCsr = (sqlite3_vtab_cursor *)pCsr;
133700 return SQLITE_OK;
133704 ** Reset the tokenizer cursor passed as the only argument. As if it had
133705 ** just been returned by fts3tokOpenMethod().
133707 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
133708 if( pCsr->pCsr ){
133709 Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
133710 pTab->pMod->xClose(pCsr->pCsr);
133711 pCsr->pCsr = 0;
133713 sqlite3_free(pCsr->zInput);
133714 pCsr->zInput = 0;
133715 pCsr->zToken = 0;
133716 pCsr->nToken = 0;
133717 pCsr->iStart = 0;
133718 pCsr->iEnd = 0;
133719 pCsr->iPos = 0;
133720 pCsr->iRowid = 0;
133724 ** xClose - Close a cursor.
133726 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
133727 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
133729 fts3tokResetCursor(pCsr);
133730 sqlite3_free(pCsr);
133731 return SQLITE_OK;
133735 ** xNext - Advance the cursor to the next row, if any.
133737 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
133738 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
133739 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
133740 int rc; /* Return code */
133742 pCsr->iRowid++;
133743 rc = pTab->pMod->xNext(pCsr->pCsr,
133744 &pCsr->zToken, &pCsr->nToken,
133745 &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
133748 if( rc!=SQLITE_OK ){
133749 fts3tokResetCursor(pCsr);
133750 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
133753 return rc;
133757 ** xFilter - Initialize a cursor to point at the start of its data.
133759 static int fts3tokFilterMethod(
133760 sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
133761 int idxNum, /* Strategy index */
133762 const char *idxStr, /* Unused */
133763 int nVal, /* Number of elements in apVal */
133764 sqlite3_value **apVal /* Arguments for the indexing scheme */
133766 int rc = SQLITE_ERROR;
133767 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
133768 Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
133769 UNUSED_PARAMETER(idxStr);
133770 UNUSED_PARAMETER(nVal);
133772 fts3tokResetCursor(pCsr);
133773 if( idxNum==1 ){
133774 const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
133775 int nByte = sqlite3_value_bytes(apVal[0]);
133776 pCsr->zInput = sqlite3_malloc(nByte+1);
133777 if( pCsr->zInput==0 ){
133778 rc = SQLITE_NOMEM;
133779 }else{
133780 memcpy(pCsr->zInput, zByte, nByte);
133781 pCsr->zInput[nByte] = 0;
133782 rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
133783 if( rc==SQLITE_OK ){
133784 pCsr->pCsr->pTokenizer = pTab->pTok;
133789 if( rc!=SQLITE_OK ) return rc;
133790 return fts3tokNextMethod(pCursor);
133794 ** xEof - Return true if the cursor is at EOF, or false otherwise.
133796 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
133797 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
133798 return (pCsr->zToken==0);
133802 ** xColumn - Return a column value.
133804 static int fts3tokColumnMethod(
133805 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
133806 sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
133807 int iCol /* Index of column to read value from */
133809 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
133811 /* CREATE TABLE x(input, token, start, end, position) */
133812 switch( iCol ){
133813 case 0:
133814 sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
133815 break;
133816 case 1:
133817 sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
133818 break;
133819 case 2:
133820 sqlite3_result_int(pCtx, pCsr->iStart);
133821 break;
133822 case 3:
133823 sqlite3_result_int(pCtx, pCsr->iEnd);
133824 break;
133825 default:
133826 assert( iCol==4 );
133827 sqlite3_result_int(pCtx, pCsr->iPos);
133828 break;
133830 return SQLITE_OK;
133834 ** xRowid - Return the current rowid for the cursor.
133836 static int fts3tokRowidMethod(
133837 sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
133838 sqlite_int64 *pRowid /* OUT: Rowid value */
133840 Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
133841 *pRowid = (sqlite3_int64)pCsr->iRowid;
133842 return SQLITE_OK;
133846 ** Register the fts3tok module with database connection db. Return SQLITE_OK
133847 ** if successful or an error code if sqlite3_create_module() fails.
133849 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
133850 static const sqlite3_module fts3tok_module = {
133851 0, /* iVersion */
133852 fts3tokConnectMethod, /* xCreate */
133853 fts3tokConnectMethod, /* xConnect */
133854 fts3tokBestIndexMethod, /* xBestIndex */
133855 fts3tokDisconnectMethod, /* xDisconnect */
133856 fts3tokDisconnectMethod, /* xDestroy */
133857 fts3tokOpenMethod, /* xOpen */
133858 fts3tokCloseMethod, /* xClose */
133859 fts3tokFilterMethod, /* xFilter */
133860 fts3tokNextMethod, /* xNext */
133861 fts3tokEofMethod, /* xEof */
133862 fts3tokColumnMethod, /* xColumn */
133863 fts3tokRowidMethod, /* xRowid */
133864 0, /* xUpdate */
133865 0, /* xBegin */
133866 0, /* xSync */
133867 0, /* xCommit */
133868 0, /* xRollback */
133869 0, /* xFindFunction */
133870 0, /* xRename */
133871 0, /* xSavepoint */
133872 0, /* xRelease */
133873 0 /* xRollbackTo */
133875 int rc; /* Return code */
133877 rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
133878 return rc;
133881 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
133883 /************** End of fts3_tokenize_vtab.c **********************************/
133884 /************** Begin file fts3_write.c **************************************/
133886 ** 2009 Oct 23
133888 ** The author disclaims copyright to this source code. In place of
133889 ** a legal notice, here is a blessing:
133891 ** May you do good and not evil.
133892 ** May you find forgiveness for yourself and forgive others.
133893 ** May you share freely, never taking more than you give.
133895 ******************************************************************************
133897 ** This file is part of the SQLite FTS3 extension module. Specifically,
133898 ** this file contains code to insert, update and delete rows from FTS3
133899 ** tables. It also contains code to merge FTS3 b-tree segments. Some
133900 ** of the sub-routines used to merge segments are also used by the query
133901 ** code in fts3.c.
133904 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133906 /* #include <string.h> */
133907 /* #include <assert.h> */
133908 /* #include <stdlib.h> */
133911 #define FTS_MAX_APPENDABLE_HEIGHT 16
133914 ** When full-text index nodes are loaded from disk, the buffer that they
133915 ** are loaded into has the following number of bytes of padding at the end
133916 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
133917 ** of 920 bytes is allocated for it.
133919 ** This means that if we have a pointer into a buffer containing node data,
133920 ** it is always safe to read up to two varints from it without risking an
133921 ** overread, even if the node data is corrupted.
133923 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
133926 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
133927 ** memory incrementally instead of all at once. This can be a big performance
133928 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
133929 ** method before retrieving all query results (as may happen, for example,
133930 ** if a query has a LIMIT clause).
133932 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
133933 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
133934 ** The code is written so that the hard lower-limit for each of these values
133935 ** is 1. Clearly such small values would be inefficient, but can be useful
133936 ** for testing purposes.
133938 ** If this module is built with SQLITE_TEST defined, these constants may
133939 ** be overridden at runtime for testing purposes. File fts3_test.c contains
133940 ** a Tcl interface to read and write the values.
133942 #ifdef SQLITE_TEST
133943 int test_fts3_node_chunksize = (4*1024);
133944 int test_fts3_node_chunk_threshold = (4*1024)*4;
133945 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
133946 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
133947 #else
133948 # define FTS3_NODE_CHUNKSIZE (4*1024)
133949 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
133950 #endif
133953 ** The two values that may be meaningfully bound to the :1 parameter in
133954 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
133956 #define FTS_STAT_DOCTOTAL 0
133957 #define FTS_STAT_INCRMERGEHINT 1
133958 #define FTS_STAT_AUTOINCRMERGE 2
133961 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
133962 ** and incremental merge operation that takes place. This is used for
133963 ** debugging FTS only, it should not usually be turned on in production
133964 ** systems.
133966 #ifdef FTS3_LOG_MERGES
133967 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
133968 sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
133970 #else
133971 #define fts3LogMerge(x, y)
133972 #endif
133975 typedef struct PendingList PendingList;
133976 typedef struct SegmentNode SegmentNode;
133977 typedef struct SegmentWriter SegmentWriter;
133980 ** An instance of the following data structure is used to build doclists
133981 ** incrementally. See function fts3PendingListAppend() for details.
133983 struct PendingList {
133984 int nData;
133985 char *aData;
133986 int nSpace;
133987 sqlite3_int64 iLastDocid;
133988 sqlite3_int64 iLastCol;
133989 sqlite3_int64 iLastPos;
133994 ** Each cursor has a (possibly empty) linked list of the following objects.
133996 struct Fts3DeferredToken {
133997 Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
133998 int iCol; /* Column token must occur in */
133999 Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
134000 PendingList *pList; /* Doclist is assembled here */
134004 ** An instance of this structure is used to iterate through the terms on
134005 ** a contiguous set of segment b-tree leaf nodes. Although the details of
134006 ** this structure are only manipulated by code in this file, opaque handles
134007 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
134008 ** terms when querying the full-text index. See functions:
134010 ** sqlite3Fts3SegReaderNew()
134011 ** sqlite3Fts3SegReaderFree()
134012 ** sqlite3Fts3SegReaderIterate()
134014 ** Methods used to manipulate Fts3SegReader structures:
134016 ** fts3SegReaderNext()
134017 ** fts3SegReaderFirstDocid()
134018 ** fts3SegReaderNextDocid()
134020 struct Fts3SegReader {
134021 int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
134022 u8 bLookup; /* True for a lookup only */
134023 u8 rootOnly; /* True for a root-only reader */
134025 sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
134026 sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
134027 sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
134028 sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
134030 char *aNode; /* Pointer to node data (or NULL) */
134031 int nNode; /* Size of buffer at aNode (or 0) */
134032 int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
134033 sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
134035 Fts3HashElem **ppNextElem;
134037 /* Variables set by fts3SegReaderNext(). These may be read directly
134038 ** by the caller. They are valid from the time SegmentReaderNew() returns
134039 ** until SegmentReaderNext() returns something other than SQLITE_OK
134040 ** (i.e. SQLITE_DONE).
134042 int nTerm; /* Number of bytes in current term */
134043 char *zTerm; /* Pointer to current term */
134044 int nTermAlloc; /* Allocated size of zTerm buffer */
134045 char *aDoclist; /* Pointer to doclist of current entry */
134046 int nDoclist; /* Size of doclist in current entry */
134048 /* The following variables are used by fts3SegReaderNextDocid() to iterate
134049 ** through the current doclist (aDoclist/nDoclist).
134051 char *pOffsetList;
134052 int nOffsetList; /* For descending pending seg-readers only */
134053 sqlite3_int64 iDocid;
134056 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
134057 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
134060 ** An instance of this structure is used to create a segment b-tree in the
134061 ** database. The internal details of this type are only accessed by the
134062 ** following functions:
134064 ** fts3SegWriterAdd()
134065 ** fts3SegWriterFlush()
134066 ** fts3SegWriterFree()
134068 struct SegmentWriter {
134069 SegmentNode *pTree; /* Pointer to interior tree structure */
134070 sqlite3_int64 iFirst; /* First slot in %_segments written */
134071 sqlite3_int64 iFree; /* Next free slot in %_segments */
134072 char *zTerm; /* Pointer to previous term buffer */
134073 int nTerm; /* Number of bytes in zTerm */
134074 int nMalloc; /* Size of malloc'd buffer at zMalloc */
134075 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
134076 int nSize; /* Size of allocation at aData */
134077 int nData; /* Bytes of data in aData */
134078 char *aData; /* Pointer to block from malloc() */
134082 ** Type SegmentNode is used by the following three functions to create
134083 ** the interior part of the segment b+-tree structures (everything except
134084 ** the leaf nodes). These functions and type are only ever used by code
134085 ** within the fts3SegWriterXXX() family of functions described above.
134087 ** fts3NodeAddTerm()
134088 ** fts3NodeWrite()
134089 ** fts3NodeFree()
134091 ** When a b+tree is written to the database (either as a result of a merge
134092 ** or the pending-terms table being flushed), leaves are written into the
134093 ** database file as soon as they are completely populated. The interior of
134094 ** the tree is assembled in memory and written out only once all leaves have
134095 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
134096 ** very large, meaning that the interior of the tree consumes relatively
134097 ** little memory.
134099 struct SegmentNode {
134100 SegmentNode *pParent; /* Parent node (or NULL for root node) */
134101 SegmentNode *pRight; /* Pointer to right-sibling */
134102 SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
134103 int nEntry; /* Number of terms written to node so far */
134104 char *zTerm; /* Pointer to previous term buffer */
134105 int nTerm; /* Number of bytes in zTerm */
134106 int nMalloc; /* Size of malloc'd buffer at zMalloc */
134107 char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
134108 int nData; /* Bytes of valid data so far */
134109 char *aData; /* Node data */
134113 ** Valid values for the second argument to fts3SqlStmt().
134115 #define SQL_DELETE_CONTENT 0
134116 #define SQL_IS_EMPTY 1
134117 #define SQL_DELETE_ALL_CONTENT 2
134118 #define SQL_DELETE_ALL_SEGMENTS 3
134119 #define SQL_DELETE_ALL_SEGDIR 4
134120 #define SQL_DELETE_ALL_DOCSIZE 5
134121 #define SQL_DELETE_ALL_STAT 6
134122 #define SQL_SELECT_CONTENT_BY_ROWID 7
134123 #define SQL_NEXT_SEGMENT_INDEX 8
134124 #define SQL_INSERT_SEGMENTS 9
134125 #define SQL_NEXT_SEGMENTS_ID 10
134126 #define SQL_INSERT_SEGDIR 11
134127 #define SQL_SELECT_LEVEL 12
134128 #define SQL_SELECT_LEVEL_RANGE 13
134129 #define SQL_SELECT_LEVEL_COUNT 14
134130 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
134131 #define SQL_DELETE_SEGDIR_LEVEL 16
134132 #define SQL_DELETE_SEGMENTS_RANGE 17
134133 #define SQL_CONTENT_INSERT 18
134134 #define SQL_DELETE_DOCSIZE 19
134135 #define SQL_REPLACE_DOCSIZE 20
134136 #define SQL_SELECT_DOCSIZE 21
134137 #define SQL_SELECT_STAT 22
134138 #define SQL_REPLACE_STAT 23
134140 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
134141 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
134142 #define SQL_DELETE_SEGDIR_RANGE 26
134143 #define SQL_SELECT_ALL_LANGID 27
134144 #define SQL_FIND_MERGE_LEVEL 28
134145 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
134146 #define SQL_DELETE_SEGDIR_ENTRY 30
134147 #define SQL_SHIFT_SEGDIR_ENTRY 31
134148 #define SQL_SELECT_SEGDIR 32
134149 #define SQL_CHOMP_SEGDIR 33
134150 #define SQL_SEGMENT_IS_APPENDABLE 34
134151 #define SQL_SELECT_INDEXES 35
134152 #define SQL_SELECT_MXLEVEL 36
134155 ** This function is used to obtain an SQLite prepared statement handle
134156 ** for the statement identified by the second argument. If successful,
134157 ** *pp is set to the requested statement handle and SQLITE_OK returned.
134158 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
134160 ** If argument apVal is not NULL, then it must point to an array with
134161 ** at least as many entries as the requested statement has bound
134162 ** parameters. The values are bound to the statements parameters before
134163 ** returning.
134165 static int fts3SqlStmt(
134166 Fts3Table *p, /* Virtual table handle */
134167 int eStmt, /* One of the SQL_XXX constants above */
134168 sqlite3_stmt **pp, /* OUT: Statement handle */
134169 sqlite3_value **apVal /* Values to bind to statement */
134171 const char *azSql[] = {
134172 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
134173 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
134174 /* 2 */ "DELETE FROM %Q.'%q_content'",
134175 /* 3 */ "DELETE FROM %Q.'%q_segments'",
134176 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
134177 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
134178 /* 6 */ "DELETE FROM %Q.'%q_stat'",
134179 /* 7 */ "SELECT %s WHERE rowid=?",
134180 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
134181 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
134182 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
134183 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
134185 /* Return segments in order from oldest to newest.*/
134186 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
134187 "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
134188 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
134189 "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
134190 "ORDER BY level DESC, idx ASC",
134192 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
134193 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
134195 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
134196 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
134197 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
134198 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
134199 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
134200 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
134201 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
134202 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
134203 /* 24 */ "",
134204 /* 25 */ "",
134206 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
134207 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
134209 /* This statement is used to determine which level to read the input from
134210 ** when performing an incremental merge. It returns the absolute level number
134211 ** of the oldest level in the db that contains at least ? segments. Or,
134212 ** if no level in the FTS index contains more than ? segments, the statement
134213 ** returns zero rows. */
134214 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
134215 " ORDER BY (level %% 1024) ASC LIMIT 1",
134217 /* Estimate the upper limit on the number of leaf nodes in a new segment
134218 ** created by merging the oldest :2 segments from absolute level :1. See
134219 ** function sqlite3Fts3Incrmerge() for details. */
134220 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
134221 " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
134223 /* SQL_DELETE_SEGDIR_ENTRY
134224 ** Delete the %_segdir entry on absolute level :1 with index :2. */
134225 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
134227 /* SQL_SHIFT_SEGDIR_ENTRY
134228 ** Modify the idx value for the segment with idx=:3 on absolute level :2
134229 ** to :1. */
134230 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
134232 /* SQL_SELECT_SEGDIR
134233 ** Read a single entry from the %_segdir table. The entry from absolute
134234 ** level :1 with index value :2. */
134235 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
134236 "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
134238 /* SQL_CHOMP_SEGDIR
134239 ** Update the start_block (:1) and root (:2) fields of the %_segdir
134240 ** entry located on absolute level :3 with index :4. */
134241 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
134242 "WHERE level = ? AND idx = ?",
134244 /* SQL_SEGMENT_IS_APPENDABLE
134245 ** Return a single row if the segment with end_block=? is appendable. Or
134246 ** no rows otherwise. */
134247 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
134249 /* SQL_SELECT_INDEXES
134250 ** Return the list of valid segment indexes for absolute level ? */
134251 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
134253 /* SQL_SELECT_MXLEVEL
134254 ** Return the largest relative level in the FTS index or indexes. */
134255 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
134257 int rc = SQLITE_OK;
134258 sqlite3_stmt *pStmt;
134260 assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
134261 assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
134263 pStmt = p->aStmt[eStmt];
134264 if( !pStmt ){
134265 char *zSql;
134266 if( eStmt==SQL_CONTENT_INSERT ){
134267 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
134268 }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
134269 zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
134270 }else{
134271 zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
134273 if( !zSql ){
134274 rc = SQLITE_NOMEM;
134275 }else{
134276 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
134277 sqlite3_free(zSql);
134278 assert( rc==SQLITE_OK || pStmt==0 );
134279 p->aStmt[eStmt] = pStmt;
134282 if( apVal ){
134283 int i;
134284 int nParam = sqlite3_bind_parameter_count(pStmt);
134285 for(i=0; rc==SQLITE_OK && i<nParam; i++){
134286 rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
134289 *pp = pStmt;
134290 return rc;
134294 static int fts3SelectDocsize(
134295 Fts3Table *pTab, /* FTS3 table handle */
134296 sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
134297 sqlite3_stmt **ppStmt /* OUT: Statement handle */
134299 sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
134300 int rc; /* Return code */
134302 rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
134303 if( rc==SQLITE_OK ){
134304 sqlite3_bind_int64(pStmt, 1, iDocid);
134305 rc = sqlite3_step(pStmt);
134306 if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
134307 rc = sqlite3_reset(pStmt);
134308 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
134309 pStmt = 0;
134310 }else{
134311 rc = SQLITE_OK;
134315 *ppStmt = pStmt;
134316 return rc;
134319 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
134320 Fts3Table *pTab, /* Fts3 table handle */
134321 sqlite3_stmt **ppStmt /* OUT: Statement handle */
134323 sqlite3_stmt *pStmt = 0;
134324 int rc;
134325 rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
134326 if( rc==SQLITE_OK ){
134327 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
134328 if( sqlite3_step(pStmt)!=SQLITE_ROW
134329 || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
134331 rc = sqlite3_reset(pStmt);
134332 if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
134333 pStmt = 0;
134336 *ppStmt = pStmt;
134337 return rc;
134340 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
134341 Fts3Table *pTab, /* Fts3 table handle */
134342 sqlite3_int64 iDocid, /* Docid to read size data for */
134343 sqlite3_stmt **ppStmt /* OUT: Statement handle */
134345 return fts3SelectDocsize(pTab, iDocid, ppStmt);
134349 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
134350 ** array apVal[] to the SQL statement identified by eStmt, the statement
134351 ** is executed.
134353 ** Returns SQLITE_OK if the statement is successfully executed, or an
134354 ** SQLite error code otherwise.
134356 static void fts3SqlExec(
134357 int *pRC, /* Result code */
134358 Fts3Table *p, /* The FTS3 table */
134359 int eStmt, /* Index of statement to evaluate */
134360 sqlite3_value **apVal /* Parameters to bind */
134362 sqlite3_stmt *pStmt;
134363 int rc;
134364 if( *pRC ) return;
134365 rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
134366 if( rc==SQLITE_OK ){
134367 sqlite3_step(pStmt);
134368 rc = sqlite3_reset(pStmt);
134370 *pRC = rc;
134375 ** This function ensures that the caller has obtained an exclusive
134376 ** shared-cache table-lock on the %_segdir table. This is required before
134377 ** writing data to the fts3 table. If this lock is not acquired first, then
134378 ** the caller may end up attempting to take this lock as part of committing
134379 ** a transaction, causing SQLite to return SQLITE_LOCKED or
134380 ** LOCKED_SHAREDCACHEto a COMMIT command.
134382 ** It is best to avoid this because if FTS3 returns any error when
134383 ** committing a transaction, the whole transaction will be rolled back.
134384 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
134385 ** It can still happen if the user locks the underlying tables directly
134386 ** instead of accessing them via FTS.
134388 static int fts3Writelock(Fts3Table *p){
134389 int rc = SQLITE_OK;
134391 if( p->nPendingData==0 ){
134392 sqlite3_stmt *pStmt;
134393 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
134394 if( rc==SQLITE_OK ){
134395 sqlite3_bind_null(pStmt, 1);
134396 sqlite3_step(pStmt);
134397 rc = sqlite3_reset(pStmt);
134401 return rc;
134405 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
134406 ** Within each language id, a separate index is maintained to store the
134407 ** document terms, and each configured prefix size (configured the FTS
134408 ** "prefix=" option). And each index consists of multiple levels ("relative
134409 ** levels").
134411 ** All three of these values (the language id, the specific index and the
134412 ** level within the index) are encoded in 64-bit integer values stored
134413 ** in the %_segdir table on disk. This function is used to convert three
134414 ** separate component values into the single 64-bit integer value that
134415 ** can be used to query the %_segdir table.
134417 ** Specifically, each language-id/index combination is allocated 1024
134418 ** 64-bit integer level values ("absolute levels"). The main terms index
134419 ** for language-id 0 is allocate values 0-1023. The first prefix index
134420 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
134421 ** Language 1 indexes are allocated immediately following language 0.
134423 ** So, for a system with nPrefix prefix indexes configured, the block of
134424 ** absolute levels that corresponds to language-id iLangid and index
134425 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
134427 static sqlite3_int64 getAbsoluteLevel(
134428 Fts3Table *p, /* FTS3 table handle */
134429 int iLangid, /* Language id */
134430 int iIndex, /* Index in p->aIndex[] */
134431 int iLevel /* Level of segments */
134433 sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
134434 assert( iLangid>=0 );
134435 assert( p->nIndex>0 );
134436 assert( iIndex>=0 && iIndex<p->nIndex );
134438 iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
134439 return iBase + iLevel;
134443 ** Set *ppStmt to a statement handle that may be used to iterate through
134444 ** all rows in the %_segdir table, from oldest to newest. If successful,
134445 ** return SQLITE_OK. If an error occurs while preparing the statement,
134446 ** return an SQLite error code.
134448 ** There is only ever one instance of this SQL statement compiled for
134449 ** each FTS3 table.
134451 ** The statement returns the following columns from the %_segdir table:
134453 ** 0: idx
134454 ** 1: start_block
134455 ** 2: leaves_end_block
134456 ** 3: end_block
134457 ** 4: root
134459 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
134460 Fts3Table *p, /* FTS3 table */
134461 int iLangid, /* Language being queried */
134462 int iIndex, /* Index for p->aIndex[] */
134463 int iLevel, /* Level to select (relative level) */
134464 sqlite3_stmt **ppStmt /* OUT: Compiled statement */
134466 int rc;
134467 sqlite3_stmt *pStmt = 0;
134469 assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
134470 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
134471 assert( iIndex>=0 && iIndex<p->nIndex );
134473 if( iLevel<0 ){
134474 /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
134475 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
134476 if( rc==SQLITE_OK ){
134477 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
134478 sqlite3_bind_int64(pStmt, 2,
134479 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
134482 }else{
134483 /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
134484 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
134485 if( rc==SQLITE_OK ){
134486 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
134489 *ppStmt = pStmt;
134490 return rc;
134495 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
134496 ** if successful, or an SQLite error code otherwise.
134498 ** This function also serves to allocate the PendingList structure itself.
134499 ** For example, to create a new PendingList structure containing two
134500 ** varints:
134502 ** PendingList *p = 0;
134503 ** fts3PendingListAppendVarint(&p, 1);
134504 ** fts3PendingListAppendVarint(&p, 2);
134506 static int fts3PendingListAppendVarint(
134507 PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
134508 sqlite3_int64 i /* Value to append to data */
134510 PendingList *p = *pp;
134512 /* Allocate or grow the PendingList as required. */
134513 if( !p ){
134514 p = sqlite3_malloc(sizeof(*p) + 100);
134515 if( !p ){
134516 return SQLITE_NOMEM;
134518 p->nSpace = 100;
134519 p->aData = (char *)&p[1];
134520 p->nData = 0;
134522 else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
134523 int nNew = p->nSpace * 2;
134524 p = sqlite3_realloc(p, sizeof(*p) + nNew);
134525 if( !p ){
134526 sqlite3_free(*pp);
134527 *pp = 0;
134528 return SQLITE_NOMEM;
134530 p->nSpace = nNew;
134531 p->aData = (char *)&p[1];
134534 /* Append the new serialized varint to the end of the list. */
134535 p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
134536 p->aData[p->nData] = '\0';
134537 *pp = p;
134538 return SQLITE_OK;
134542 ** Add a docid/column/position entry to a PendingList structure. Non-zero
134543 ** is returned if the structure is sqlite3_realloced as part of adding
134544 ** the entry. Otherwise, zero.
134546 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
134547 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
134548 ** it is set to SQLITE_OK.
134550 static int fts3PendingListAppend(
134551 PendingList **pp, /* IN/OUT: PendingList structure */
134552 sqlite3_int64 iDocid, /* Docid for entry to add */
134553 sqlite3_int64 iCol, /* Column for entry to add */
134554 sqlite3_int64 iPos, /* Position of term for entry to add */
134555 int *pRc /* OUT: Return code */
134557 PendingList *p = *pp;
134558 int rc = SQLITE_OK;
134560 assert( !p || p->iLastDocid<=iDocid );
134562 if( !p || p->iLastDocid!=iDocid ){
134563 sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
134564 if( p ){
134565 assert( p->nData<p->nSpace );
134566 assert( p->aData[p->nData]==0 );
134567 p->nData++;
134569 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
134570 goto pendinglistappend_out;
134572 p->iLastCol = -1;
134573 p->iLastPos = 0;
134574 p->iLastDocid = iDocid;
134576 if( iCol>0 && p->iLastCol!=iCol ){
134577 if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
134578 || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
134580 goto pendinglistappend_out;
134582 p->iLastCol = iCol;
134583 p->iLastPos = 0;
134585 if( iCol>=0 ){
134586 assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
134587 rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
134588 if( rc==SQLITE_OK ){
134589 p->iLastPos = iPos;
134593 pendinglistappend_out:
134594 *pRc = rc;
134595 if( p!=*pp ){
134596 *pp = p;
134597 return 1;
134599 return 0;
134603 ** Free a PendingList object allocated by fts3PendingListAppend().
134605 static void fts3PendingListDelete(PendingList *pList){
134606 sqlite3_free(pList);
134610 ** Add an entry to one of the pending-terms hash tables.
134612 static int fts3PendingTermsAddOne(
134613 Fts3Table *p,
134614 int iCol,
134615 int iPos,
134616 Fts3Hash *pHash, /* Pending terms hash table to add entry to */
134617 const char *zToken,
134618 int nToken
134620 PendingList *pList;
134621 int rc = SQLITE_OK;
134623 pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
134624 if( pList ){
134625 p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
134627 if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
134628 if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
134629 /* Malloc failed while inserting the new entry. This can only
134630 ** happen if there was no previous entry for this token.
134632 assert( 0==fts3HashFind(pHash, zToken, nToken) );
134633 sqlite3_free(pList);
134634 rc = SQLITE_NOMEM;
134637 if( rc==SQLITE_OK ){
134638 p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
134640 return rc;
134644 ** Tokenize the nul-terminated string zText and add all tokens to the
134645 ** pending-terms hash-table. The docid used is that currently stored in
134646 ** p->iPrevDocid, and the column is specified by argument iCol.
134648 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
134650 static int fts3PendingTermsAdd(
134651 Fts3Table *p, /* Table into which text will be inserted */
134652 int iLangid, /* Language id to use */
134653 const char *zText, /* Text of document to be inserted */
134654 int iCol, /* Column into which text is being inserted */
134655 u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
134657 int rc;
134658 int iStart = 0;
134659 int iEnd = 0;
134660 int iPos = 0;
134661 int nWord = 0;
134663 char const *zToken;
134664 int nToken = 0;
134666 sqlite3_tokenizer *pTokenizer = p->pTokenizer;
134667 sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
134668 sqlite3_tokenizer_cursor *pCsr;
134669 int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
134670 const char**,int*,int*,int*,int*);
134672 assert( pTokenizer && pModule );
134674 /* If the user has inserted a NULL value, this function may be called with
134675 ** zText==0. In this case, add zero token entries to the hash table and
134676 ** return early. */
134677 if( zText==0 ){
134678 *pnWord = 0;
134679 return SQLITE_OK;
134682 rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
134683 if( rc!=SQLITE_OK ){
134684 return rc;
134687 xNext = pModule->xNext;
134688 while( SQLITE_OK==rc
134689 && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
134691 int i;
134692 if( iPos>=nWord ) nWord = iPos+1;
134694 /* Positions cannot be negative; we use -1 as a terminator internally.
134695 ** Tokens must have a non-zero length.
134697 if( iPos<0 || !zToken || nToken<=0 ){
134698 rc = SQLITE_ERROR;
134699 break;
134702 /* Add the term to the terms index */
134703 rc = fts3PendingTermsAddOne(
134704 p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
134707 /* Add the term to each of the prefix indexes that it is not too
134708 ** short for. */
134709 for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
134710 struct Fts3Index *pIndex = &p->aIndex[i];
134711 if( nToken<pIndex->nPrefix ) continue;
134712 rc = fts3PendingTermsAddOne(
134713 p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
134718 pModule->xClose(pCsr);
134719 *pnWord += nWord;
134720 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
134724 ** Calling this function indicates that subsequent calls to
134725 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
134726 ** contents of the document with docid iDocid.
134728 static int fts3PendingTermsDocid(
134729 Fts3Table *p, /* Full-text table handle */
134730 int iLangid, /* Language id of row being written */
134731 sqlite_int64 iDocid /* Docid of row being written */
134733 assert( iLangid>=0 );
134735 /* TODO(shess) Explore whether partially flushing the buffer on
134736 ** forced-flush would provide better performance. I suspect that if
134737 ** we ordered the doclists by size and flushed the largest until the
134738 ** buffer was half empty, that would let the less frequent terms
134739 ** generate longer doclists.
134741 if( iDocid<=p->iPrevDocid
134742 || p->iPrevLangid!=iLangid
134743 || p->nPendingData>p->nMaxPendingData
134745 int rc = sqlite3Fts3PendingTermsFlush(p);
134746 if( rc!=SQLITE_OK ) return rc;
134748 p->iPrevDocid = iDocid;
134749 p->iPrevLangid = iLangid;
134750 return SQLITE_OK;
134754 ** Discard the contents of the pending-terms hash tables.
134756 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
134757 int i;
134758 for(i=0; i<p->nIndex; i++){
134759 Fts3HashElem *pElem;
134760 Fts3Hash *pHash = &p->aIndex[i].hPending;
134761 for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
134762 PendingList *pList = (PendingList *)fts3HashData(pElem);
134763 fts3PendingListDelete(pList);
134765 fts3HashClear(pHash);
134767 p->nPendingData = 0;
134771 ** This function is called by the xUpdate() method as part of an INSERT
134772 ** operation. It adds entries for each term in the new record to the
134773 ** pendingTerms hash table.
134775 ** Argument apVal is the same as the similarly named argument passed to
134776 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
134778 static int fts3InsertTerms(
134779 Fts3Table *p,
134780 int iLangid,
134781 sqlite3_value **apVal,
134782 u32 *aSz
134784 int i; /* Iterator variable */
134785 for(i=2; i<p->nColumn+2; i++){
134786 int iCol = i-2;
134787 if( p->abNotindexed[iCol]==0 ){
134788 const char *zText = (const char *)sqlite3_value_text(apVal[i]);
134789 int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
134790 if( rc!=SQLITE_OK ){
134791 return rc;
134793 aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
134796 return SQLITE_OK;
134800 ** This function is called by the xUpdate() method for an INSERT operation.
134801 ** The apVal parameter is passed a copy of the apVal argument passed by
134802 ** SQLite to the xUpdate() method. i.e:
134804 ** apVal[0] Not used for INSERT.
134805 ** apVal[1] rowid
134806 ** apVal[2] Left-most user-defined column
134807 ** ...
134808 ** apVal[p->nColumn+1] Right-most user-defined column
134809 ** apVal[p->nColumn+2] Hidden column with same name as table
134810 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
134811 ** apVal[p->nColumn+4] Hidden languageid column
134813 static int fts3InsertData(
134814 Fts3Table *p, /* Full-text table */
134815 sqlite3_value **apVal, /* Array of values to insert */
134816 sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
134818 int rc; /* Return code */
134819 sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
134821 if( p->zContentTbl ){
134822 sqlite3_value *pRowid = apVal[p->nColumn+3];
134823 if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
134824 pRowid = apVal[1];
134826 if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
134827 return SQLITE_CONSTRAINT;
134829 *piDocid = sqlite3_value_int64(pRowid);
134830 return SQLITE_OK;
134833 /* Locate the statement handle used to insert data into the %_content
134834 ** table. The SQL for this statement is:
134836 ** INSERT INTO %_content VALUES(?, ?, ?, ...)
134838 ** The statement features N '?' variables, where N is the number of user
134839 ** defined columns in the FTS3 table, plus one for the docid field.
134841 rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
134842 if( rc==SQLITE_OK && p->zLanguageid ){
134843 rc = sqlite3_bind_int(
134844 pContentInsert, p->nColumn+2,
134845 sqlite3_value_int(apVal[p->nColumn+4])
134848 if( rc!=SQLITE_OK ) return rc;
134850 /* There is a quirk here. The users INSERT statement may have specified
134851 ** a value for the "rowid" field, for the "docid" field, or for both.
134852 ** Which is a problem, since "rowid" and "docid" are aliases for the
134853 ** same value. For example:
134855 ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
134857 ** In FTS3, this is an error. It is an error to specify non-NULL values
134858 ** for both docid and some other rowid alias.
134860 if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
134861 if( SQLITE_NULL==sqlite3_value_type(apVal[0])
134862 && SQLITE_NULL!=sqlite3_value_type(apVal[1])
134864 /* A rowid/docid conflict. */
134865 return SQLITE_ERROR;
134867 rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
134868 if( rc!=SQLITE_OK ) return rc;
134871 /* Execute the statement to insert the record. Set *piDocid to the
134872 ** new docid value.
134874 sqlite3_step(pContentInsert);
134875 rc = sqlite3_reset(pContentInsert);
134877 *piDocid = sqlite3_last_insert_rowid(p->db);
134878 return rc;
134884 ** Remove all data from the FTS3 table. Clear the hash table containing
134885 ** pending terms.
134887 static int fts3DeleteAll(Fts3Table *p, int bContent){
134888 int rc = SQLITE_OK; /* Return code */
134890 /* Discard the contents of the pending-terms hash table. */
134891 sqlite3Fts3PendingTermsClear(p);
134893 /* Delete everything from the shadow tables. Except, leave %_content as
134894 ** is if bContent is false. */
134895 assert( p->zContentTbl==0 || bContent==0 );
134896 if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
134897 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
134898 fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
134899 if( p->bHasDocsize ){
134900 fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
134902 if( p->bHasStat ){
134903 fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
134905 return rc;
134911 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
134912 int iLangid = 0;
134913 if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
134914 return iLangid;
134918 ** The first element in the apVal[] array is assumed to contain the docid
134919 ** (an integer) of a row about to be deleted. Remove all terms from the
134920 ** full-text index.
134922 static void fts3DeleteTerms(
134923 int *pRC, /* Result code */
134924 Fts3Table *p, /* The FTS table to delete from */
134925 sqlite3_value *pRowid, /* The docid to be deleted */
134926 u32 *aSz, /* Sizes of deleted document written here */
134927 int *pbFound /* OUT: Set to true if row really does exist */
134929 int rc;
134930 sqlite3_stmt *pSelect;
134932 assert( *pbFound==0 );
134933 if( *pRC ) return;
134934 rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
134935 if( rc==SQLITE_OK ){
134936 if( SQLITE_ROW==sqlite3_step(pSelect) ){
134937 int i;
134938 int iLangid = langidFromSelect(p, pSelect);
134939 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
134940 for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
134941 int iCol = i-1;
134942 if( p->abNotindexed[iCol]==0 ){
134943 const char *zText = (const char *)sqlite3_column_text(pSelect, i);
134944 rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
134945 aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
134948 if( rc!=SQLITE_OK ){
134949 sqlite3_reset(pSelect);
134950 *pRC = rc;
134951 return;
134953 *pbFound = 1;
134955 rc = sqlite3_reset(pSelect);
134956 }else{
134957 sqlite3_reset(pSelect);
134959 *pRC = rc;
134963 ** Forward declaration to account for the circular dependency between
134964 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
134966 static int fts3SegmentMerge(Fts3Table *, int, int, int);
134969 ** This function allocates a new level iLevel index in the segdir table.
134970 ** Usually, indexes are allocated within a level sequentially starting
134971 ** with 0, so the allocated index is one greater than the value returned
134972 ** by:
134974 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
134976 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
134977 ** level, they are merged into a single level (iLevel+1) segment and the
134978 ** allocated index is 0.
134980 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
134981 ** returned. Otherwise, an SQLite error code is returned.
134983 static int fts3AllocateSegdirIdx(
134984 Fts3Table *p,
134985 int iLangid, /* Language id */
134986 int iIndex, /* Index for p->aIndex */
134987 int iLevel,
134988 int *piIdx
134990 int rc; /* Return Code */
134991 sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
134992 int iNext = 0; /* Result of query pNextIdx */
134994 assert( iLangid>=0 );
134995 assert( p->nIndex>=1 );
134997 /* Set variable iNext to the next available segdir index at level iLevel. */
134998 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
134999 if( rc==SQLITE_OK ){
135000 sqlite3_bind_int64(
135001 pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
135003 if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
135004 iNext = sqlite3_column_int(pNextIdx, 0);
135006 rc = sqlite3_reset(pNextIdx);
135009 if( rc==SQLITE_OK ){
135010 /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
135011 ** full, merge all segments in level iLevel into a single iLevel+1
135012 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
135013 ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
135015 if( iNext>=FTS3_MERGE_COUNT ){
135016 fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
135017 rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
135018 *piIdx = 0;
135019 }else{
135020 *piIdx = iNext;
135024 return rc;
135028 ** The %_segments table is declared as follows:
135030 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
135032 ** This function reads data from a single row of the %_segments table. The
135033 ** specific row is identified by the iBlockid parameter. If paBlob is not
135034 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
135035 ** with the contents of the blob stored in the "block" column of the
135036 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
135037 ** to the size of the blob in bytes before returning.
135039 ** If an error occurs, or the table does not contain the specified row,
135040 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
135041 ** paBlob is non-NULL, then it is the responsibility of the caller to
135042 ** eventually free the returned buffer.
135044 ** This function may leave an open sqlite3_blob* handle in the
135045 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
135046 ** to this function. The handle may be closed by calling the
135047 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
135048 ** performance improvement, but the blob handle should always be closed
135049 ** before control is returned to the user (to prevent a lock being held
135050 ** on the database file for longer than necessary). Thus, any virtual table
135051 ** method (xFilter etc.) that may directly or indirectly call this function
135052 ** must call sqlite3Fts3SegmentsClose() before returning.
135054 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
135055 Fts3Table *p, /* FTS3 table handle */
135056 sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
135057 char **paBlob, /* OUT: Blob data in malloc'd buffer */
135058 int *pnBlob, /* OUT: Size of blob data */
135059 int *pnLoad /* OUT: Bytes actually loaded */
135061 int rc; /* Return code */
135063 /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
135064 assert( pnBlob );
135066 if( p->pSegments ){
135067 rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
135068 }else{
135069 if( 0==p->zSegmentsTbl ){
135070 p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
135071 if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
135073 rc = sqlite3_blob_open(
135074 p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
135078 if( rc==SQLITE_OK ){
135079 int nByte = sqlite3_blob_bytes(p->pSegments);
135080 *pnBlob = nByte;
135081 if( paBlob ){
135082 char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
135083 if( !aByte ){
135084 rc = SQLITE_NOMEM;
135085 }else{
135086 if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
135087 nByte = FTS3_NODE_CHUNKSIZE;
135088 *pnLoad = nByte;
135090 rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
135091 memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
135092 if( rc!=SQLITE_OK ){
135093 sqlite3_free(aByte);
135094 aByte = 0;
135097 *paBlob = aByte;
135101 return rc;
135105 ** Close the blob handle at p->pSegments, if it is open. See comments above
135106 ** the sqlite3Fts3ReadBlock() function for details.
135108 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
135109 sqlite3_blob_close(p->pSegments);
135110 p->pSegments = 0;
135113 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
135114 int nRead; /* Number of bytes to read */
135115 int rc; /* Return code */
135117 nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
135118 rc = sqlite3_blob_read(
135119 pReader->pBlob,
135120 &pReader->aNode[pReader->nPopulate],
135121 nRead,
135122 pReader->nPopulate
135125 if( rc==SQLITE_OK ){
135126 pReader->nPopulate += nRead;
135127 memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
135128 if( pReader->nPopulate==pReader->nNode ){
135129 sqlite3_blob_close(pReader->pBlob);
135130 pReader->pBlob = 0;
135131 pReader->nPopulate = 0;
135134 return rc;
135137 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
135138 int rc = SQLITE_OK;
135139 assert( !pReader->pBlob
135140 || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
135142 while( pReader->pBlob && rc==SQLITE_OK
135143 && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
135145 rc = fts3SegReaderIncrRead(pReader);
135147 return rc;
135151 ** Set an Fts3SegReader cursor to point at EOF.
135153 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
135154 if( !fts3SegReaderIsRootOnly(pSeg) ){
135155 sqlite3_free(pSeg->aNode);
135156 sqlite3_blob_close(pSeg->pBlob);
135157 pSeg->pBlob = 0;
135159 pSeg->aNode = 0;
135163 ** Move the iterator passed as the first argument to the next term in the
135164 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
135165 ** SQLITE_DONE. Otherwise, an SQLite error code.
135167 static int fts3SegReaderNext(
135168 Fts3Table *p,
135169 Fts3SegReader *pReader,
135170 int bIncr
135172 int rc; /* Return code of various sub-routines */
135173 char *pNext; /* Cursor variable */
135174 int nPrefix; /* Number of bytes in term prefix */
135175 int nSuffix; /* Number of bytes in term suffix */
135177 if( !pReader->aDoclist ){
135178 pNext = pReader->aNode;
135179 }else{
135180 pNext = &pReader->aDoclist[pReader->nDoclist];
135183 if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
135185 if( fts3SegReaderIsPending(pReader) ){
135186 Fts3HashElem *pElem = *(pReader->ppNextElem);
135187 if( pElem==0 ){
135188 pReader->aNode = 0;
135189 }else{
135190 PendingList *pList = (PendingList *)fts3HashData(pElem);
135191 pReader->zTerm = (char *)fts3HashKey(pElem);
135192 pReader->nTerm = fts3HashKeysize(pElem);
135193 pReader->nNode = pReader->nDoclist = pList->nData + 1;
135194 pReader->aNode = pReader->aDoclist = pList->aData;
135195 pReader->ppNextElem++;
135196 assert( pReader->aNode );
135198 return SQLITE_OK;
135201 fts3SegReaderSetEof(pReader);
135203 /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
135204 ** blocks have already been traversed. */
135205 assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
135206 if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
135207 return SQLITE_OK;
135210 rc = sqlite3Fts3ReadBlock(
135211 p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
135212 (bIncr ? &pReader->nPopulate : 0)
135214 if( rc!=SQLITE_OK ) return rc;
135215 assert( pReader->pBlob==0 );
135216 if( bIncr && pReader->nPopulate<pReader->nNode ){
135217 pReader->pBlob = p->pSegments;
135218 p->pSegments = 0;
135220 pNext = pReader->aNode;
135223 assert( !fts3SegReaderIsPending(pReader) );
135225 rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
135226 if( rc!=SQLITE_OK ) return rc;
135228 /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
135229 ** safe (no risk of overread) even if the node data is corrupted. */
135230 pNext += fts3GetVarint32(pNext, &nPrefix);
135231 pNext += fts3GetVarint32(pNext, &nSuffix);
135232 if( nPrefix<0 || nSuffix<=0
135233 || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
135235 return FTS_CORRUPT_VTAB;
135238 if( nPrefix+nSuffix>pReader->nTermAlloc ){
135239 int nNew = (nPrefix+nSuffix)*2;
135240 char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
135241 if( !zNew ){
135242 return SQLITE_NOMEM;
135244 pReader->zTerm = zNew;
135245 pReader->nTermAlloc = nNew;
135248 rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
135249 if( rc!=SQLITE_OK ) return rc;
135251 memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
135252 pReader->nTerm = nPrefix+nSuffix;
135253 pNext += nSuffix;
135254 pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
135255 pReader->aDoclist = pNext;
135256 pReader->pOffsetList = 0;
135258 /* Check that the doclist does not appear to extend past the end of the
135259 ** b-tree node. And that the final byte of the doclist is 0x00. If either
135260 ** of these statements is untrue, then the data structure is corrupt.
135262 if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
135263 || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
135265 return FTS_CORRUPT_VTAB;
135267 return SQLITE_OK;
135271 ** Set the SegReader to point to the first docid in the doclist associated
135272 ** with the current term.
135274 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
135275 int rc = SQLITE_OK;
135276 assert( pReader->aDoclist );
135277 assert( !pReader->pOffsetList );
135278 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
135279 u8 bEof = 0;
135280 pReader->iDocid = 0;
135281 pReader->nOffsetList = 0;
135282 sqlite3Fts3DoclistPrev(0,
135283 pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
135284 &pReader->iDocid, &pReader->nOffsetList, &bEof
135286 }else{
135287 rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
135288 if( rc==SQLITE_OK ){
135289 int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
135290 pReader->pOffsetList = &pReader->aDoclist[n];
135293 return rc;
135297 ** Advance the SegReader to point to the next docid in the doclist
135298 ** associated with the current term.
135300 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
135301 ** *ppOffsetList is set to point to the first column-offset list
135302 ** in the doclist entry (i.e. immediately past the docid varint).
135303 ** *pnOffsetList is set to the length of the set of column-offset
135304 ** lists, not including the nul-terminator byte. For example:
135306 static int fts3SegReaderNextDocid(
135307 Fts3Table *pTab,
135308 Fts3SegReader *pReader, /* Reader to advance to next docid */
135309 char **ppOffsetList, /* OUT: Pointer to current position-list */
135310 int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
135312 int rc = SQLITE_OK;
135313 char *p = pReader->pOffsetList;
135314 char c = 0;
135316 assert( p );
135318 if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
135319 /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
135320 ** Pending-terms doclists are always built up in ascending order, so
135321 ** we have to iterate through them backwards here. */
135322 u8 bEof = 0;
135323 if( ppOffsetList ){
135324 *ppOffsetList = pReader->pOffsetList;
135325 *pnOffsetList = pReader->nOffsetList - 1;
135327 sqlite3Fts3DoclistPrev(0,
135328 pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
135329 &pReader->nOffsetList, &bEof
135331 if( bEof ){
135332 pReader->pOffsetList = 0;
135333 }else{
135334 pReader->pOffsetList = p;
135336 }else{
135337 char *pEnd = &pReader->aDoclist[pReader->nDoclist];
135339 /* Pointer p currently points at the first byte of an offset list. The
135340 ** following block advances it to point one byte past the end of
135341 ** the same offset list. */
135342 while( 1 ){
135344 /* The following line of code (and the "p++" below the while() loop) is
135345 ** normally all that is required to move pointer p to the desired
135346 ** position. The exception is if this node is being loaded from disk
135347 ** incrementally and pointer "p" now points to the first byte past
135348 ** the populated part of pReader->aNode[].
135350 while( *p | c ) c = *p++ & 0x80;
135351 assert( *p==0 );
135353 if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
135354 rc = fts3SegReaderIncrRead(pReader);
135355 if( rc!=SQLITE_OK ) return rc;
135359 /* If required, populate the output variables with a pointer to and the
135360 ** size of the previous offset-list.
135362 if( ppOffsetList ){
135363 *ppOffsetList = pReader->pOffsetList;
135364 *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
135367 /* List may have been edited in place by fts3EvalNearTrim() */
135368 while( p<pEnd && *p==0 ) p++;
135370 /* If there are no more entries in the doclist, set pOffsetList to
135371 ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
135372 ** Fts3SegReader.pOffsetList to point to the next offset list before
135373 ** returning.
135375 if( p>=pEnd ){
135376 pReader->pOffsetList = 0;
135377 }else{
135378 rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
135379 if( rc==SQLITE_OK ){
135380 sqlite3_int64 iDelta;
135381 pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
135382 if( pTab->bDescIdx ){
135383 pReader->iDocid -= iDelta;
135384 }else{
135385 pReader->iDocid += iDelta;
135391 return SQLITE_OK;
135395 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
135396 Fts3Cursor *pCsr,
135397 Fts3MultiSegReader *pMsr,
135398 int *pnOvfl
135400 Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
135401 int nOvfl = 0;
135402 int ii;
135403 int rc = SQLITE_OK;
135404 int pgsz = p->nPgsz;
135406 assert( p->bFts4 );
135407 assert( pgsz>0 );
135409 for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
135410 Fts3SegReader *pReader = pMsr->apSegment[ii];
135411 if( !fts3SegReaderIsPending(pReader)
135412 && !fts3SegReaderIsRootOnly(pReader)
135414 sqlite3_int64 jj;
135415 for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
135416 int nBlob;
135417 rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
135418 if( rc!=SQLITE_OK ) break;
135419 if( (nBlob+35)>pgsz ){
135420 nOvfl += (nBlob + 34)/pgsz;
135425 *pnOvfl = nOvfl;
135426 return rc;
135430 ** Free all allocations associated with the iterator passed as the
135431 ** second argument.
135433 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
135434 if( pReader && !fts3SegReaderIsPending(pReader) ){
135435 sqlite3_free(pReader->zTerm);
135436 if( !fts3SegReaderIsRootOnly(pReader) ){
135437 sqlite3_free(pReader->aNode);
135438 sqlite3_blob_close(pReader->pBlob);
135441 sqlite3_free(pReader);
135445 ** Allocate a new SegReader object.
135447 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
135448 int iAge, /* Segment "age". */
135449 int bLookup, /* True for a lookup only */
135450 sqlite3_int64 iStartLeaf, /* First leaf to traverse */
135451 sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
135452 sqlite3_int64 iEndBlock, /* Final block of segment */
135453 const char *zRoot, /* Buffer containing root node */
135454 int nRoot, /* Size of buffer containing root node */
135455 Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
135457 Fts3SegReader *pReader; /* Newly allocated SegReader object */
135458 int nExtra = 0; /* Bytes to allocate segment root node */
135460 assert( iStartLeaf<=iEndLeaf );
135461 if( iStartLeaf==0 ){
135462 nExtra = nRoot + FTS3_NODE_PADDING;
135465 pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
135466 if( !pReader ){
135467 return SQLITE_NOMEM;
135469 memset(pReader, 0, sizeof(Fts3SegReader));
135470 pReader->iIdx = iAge;
135471 pReader->bLookup = bLookup!=0;
135472 pReader->iStartBlock = iStartLeaf;
135473 pReader->iLeafEndBlock = iEndLeaf;
135474 pReader->iEndBlock = iEndBlock;
135476 if( nExtra ){
135477 /* The entire segment is stored in the root node. */
135478 pReader->aNode = (char *)&pReader[1];
135479 pReader->rootOnly = 1;
135480 pReader->nNode = nRoot;
135481 memcpy(pReader->aNode, zRoot, nRoot);
135482 memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
135483 }else{
135484 pReader->iCurrentBlock = iStartLeaf-1;
135486 *ppReader = pReader;
135487 return SQLITE_OK;
135491 ** This is a comparison function used as a qsort() callback when sorting
135492 ** an array of pending terms by term. This occurs as part of flushing
135493 ** the contents of the pending-terms hash table to the database.
135495 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
135496 char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
135497 char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
135498 int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
135499 int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
135501 int n = (n1<n2 ? n1 : n2);
135502 int c = memcmp(z1, z2, n);
135503 if( c==0 ){
135504 c = n1 - n2;
135506 return c;
135510 ** This function is used to allocate an Fts3SegReader that iterates through
135511 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
135513 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
135514 ** through each term in the pending-terms table. Or, if isPrefixIter is
135515 ** non-zero, it iterates through each term and its prefixes. For example, if
135516 ** the pending terms hash table contains the terms "sqlite", "mysql" and
135517 ** "firebird", then the iterator visits the following 'terms' (in the order
135518 ** shown):
135520 ** f fi fir fire fireb firebi firebir firebird
135521 ** m my mys mysq mysql
135522 ** s sq sql sqli sqlit sqlite
135524 ** Whereas if isPrefixIter is zero, the terms visited are:
135526 ** firebird mysql sqlite
135528 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
135529 Fts3Table *p, /* Virtual table handle */
135530 int iIndex, /* Index for p->aIndex */
135531 const char *zTerm, /* Term to search for */
135532 int nTerm, /* Size of buffer zTerm */
135533 int bPrefix, /* True for a prefix iterator */
135534 Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
135536 Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
135537 Fts3HashElem *pE; /* Iterator variable */
135538 Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
135539 int nElem = 0; /* Size of array at aElem */
135540 int rc = SQLITE_OK; /* Return Code */
135541 Fts3Hash *pHash;
135543 pHash = &p->aIndex[iIndex].hPending;
135544 if( bPrefix ){
135545 int nAlloc = 0; /* Size of allocated array at aElem */
135547 for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
135548 char *zKey = (char *)fts3HashKey(pE);
135549 int nKey = fts3HashKeysize(pE);
135550 if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
135551 if( nElem==nAlloc ){
135552 Fts3HashElem **aElem2;
135553 nAlloc += 16;
135554 aElem2 = (Fts3HashElem **)sqlite3_realloc(
135555 aElem, nAlloc*sizeof(Fts3HashElem *)
135557 if( !aElem2 ){
135558 rc = SQLITE_NOMEM;
135559 nElem = 0;
135560 break;
135562 aElem = aElem2;
135565 aElem[nElem++] = pE;
135569 /* If more than one term matches the prefix, sort the Fts3HashElem
135570 ** objects in term order using qsort(). This uses the same comparison
135571 ** callback as is used when flushing terms to disk.
135573 if( nElem>1 ){
135574 qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
135577 }else{
135578 /* The query is a simple term lookup that matches at most one term in
135579 ** the index. All that is required is a straight hash-lookup.
135581 ** Because the stack address of pE may be accessed via the aElem pointer
135582 ** below, the "Fts3HashElem *pE" must be declared so that it is valid
135583 ** within this entire function, not just this "else{...}" block.
135585 pE = fts3HashFindElem(pHash, zTerm, nTerm);
135586 if( pE ){
135587 aElem = &pE;
135588 nElem = 1;
135592 if( nElem>0 ){
135593 int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
135594 pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
135595 if( !pReader ){
135596 rc = SQLITE_NOMEM;
135597 }else{
135598 memset(pReader, 0, nByte);
135599 pReader->iIdx = 0x7FFFFFFF;
135600 pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
135601 memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
135605 if( bPrefix ){
135606 sqlite3_free(aElem);
135608 *ppReader = pReader;
135609 return rc;
135613 ** Compare the entries pointed to by two Fts3SegReader structures.
135614 ** Comparison is as follows:
135616 ** 1) EOF is greater than not EOF.
135618 ** 2) The current terms (if any) are compared using memcmp(). If one
135619 ** term is a prefix of another, the longer term is considered the
135620 ** larger.
135622 ** 3) By segment age. An older segment is considered larger.
135624 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
135625 int rc;
135626 if( pLhs->aNode && pRhs->aNode ){
135627 int rc2 = pLhs->nTerm - pRhs->nTerm;
135628 if( rc2<0 ){
135629 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
135630 }else{
135631 rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
135633 if( rc==0 ){
135634 rc = rc2;
135636 }else{
135637 rc = (pLhs->aNode==0) - (pRhs->aNode==0);
135639 if( rc==0 ){
135640 rc = pRhs->iIdx - pLhs->iIdx;
135642 assert( rc!=0 );
135643 return rc;
135647 ** A different comparison function for SegReader structures. In this
135648 ** version, it is assumed that each SegReader points to an entry in
135649 ** a doclist for identical terms. Comparison is made as follows:
135651 ** 1) EOF (end of doclist in this case) is greater than not EOF.
135653 ** 2) By current docid.
135655 ** 3) By segment age. An older segment is considered larger.
135657 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
135658 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
135659 if( rc==0 ){
135660 if( pLhs->iDocid==pRhs->iDocid ){
135661 rc = pRhs->iIdx - pLhs->iIdx;
135662 }else{
135663 rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
135666 assert( pLhs->aNode && pRhs->aNode );
135667 return rc;
135669 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
135670 int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
135671 if( rc==0 ){
135672 if( pLhs->iDocid==pRhs->iDocid ){
135673 rc = pRhs->iIdx - pLhs->iIdx;
135674 }else{
135675 rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
135678 assert( pLhs->aNode && pRhs->aNode );
135679 return rc;
135683 ** Compare the term that the Fts3SegReader object passed as the first argument
135684 ** points to with the term specified by arguments zTerm and nTerm.
135686 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
135687 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
135688 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
135690 static int fts3SegReaderTermCmp(
135691 Fts3SegReader *pSeg, /* Segment reader object */
135692 const char *zTerm, /* Term to compare to */
135693 int nTerm /* Size of term zTerm in bytes */
135695 int res = 0;
135696 if( pSeg->aNode ){
135697 if( pSeg->nTerm>nTerm ){
135698 res = memcmp(pSeg->zTerm, zTerm, nTerm);
135699 }else{
135700 res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
135702 if( res==0 ){
135703 res = pSeg->nTerm-nTerm;
135706 return res;
135710 ** Argument apSegment is an array of nSegment elements. It is known that
135711 ** the final (nSegment-nSuspect) members are already in sorted order
135712 ** (according to the comparison function provided). This function shuffles
135713 ** the array around until all entries are in sorted order.
135715 static void fts3SegReaderSort(
135716 Fts3SegReader **apSegment, /* Array to sort entries of */
135717 int nSegment, /* Size of apSegment array */
135718 int nSuspect, /* Unsorted entry count */
135719 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
135721 int i; /* Iterator variable */
135723 assert( nSuspect<=nSegment );
135725 if( nSuspect==nSegment ) nSuspect--;
135726 for(i=nSuspect-1; i>=0; i--){
135727 int j;
135728 for(j=i; j<(nSegment-1); j++){
135729 Fts3SegReader *pTmp;
135730 if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
135731 pTmp = apSegment[j+1];
135732 apSegment[j+1] = apSegment[j];
135733 apSegment[j] = pTmp;
135737 #ifndef NDEBUG
135738 /* Check that the list really is sorted now. */
135739 for(i=0; i<(nSuspect-1); i++){
135740 assert( xCmp(apSegment[i], apSegment[i+1])<0 );
135742 #endif
135746 ** Insert a record into the %_segments table.
135748 static int fts3WriteSegment(
135749 Fts3Table *p, /* Virtual table handle */
135750 sqlite3_int64 iBlock, /* Block id for new block */
135751 char *z, /* Pointer to buffer containing block data */
135752 int n /* Size of buffer z in bytes */
135754 sqlite3_stmt *pStmt;
135755 int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
135756 if( rc==SQLITE_OK ){
135757 sqlite3_bind_int64(pStmt, 1, iBlock);
135758 sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
135759 sqlite3_step(pStmt);
135760 rc = sqlite3_reset(pStmt);
135762 return rc;
135766 ** Find the largest relative level number in the table. If successful, set
135767 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
135768 ** set *pnMax to zero and return an SQLite error code.
135770 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
135771 int rc;
135772 int mxLevel = 0;
135773 sqlite3_stmt *pStmt = 0;
135775 rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
135776 if( rc==SQLITE_OK ){
135777 if( SQLITE_ROW==sqlite3_step(pStmt) ){
135778 mxLevel = sqlite3_column_int(pStmt, 0);
135780 rc = sqlite3_reset(pStmt);
135782 *pnMax = mxLevel;
135783 return rc;
135787 ** Insert a record into the %_segdir table.
135789 static int fts3WriteSegdir(
135790 Fts3Table *p, /* Virtual table handle */
135791 sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
135792 int iIdx, /* Value for "idx" field */
135793 sqlite3_int64 iStartBlock, /* Value for "start_block" field */
135794 sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
135795 sqlite3_int64 iEndBlock, /* Value for "end_block" field */
135796 char *zRoot, /* Blob value for "root" field */
135797 int nRoot /* Number of bytes in buffer zRoot */
135799 sqlite3_stmt *pStmt;
135800 int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
135801 if( rc==SQLITE_OK ){
135802 sqlite3_bind_int64(pStmt, 1, iLevel);
135803 sqlite3_bind_int(pStmt, 2, iIdx);
135804 sqlite3_bind_int64(pStmt, 3, iStartBlock);
135805 sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
135806 sqlite3_bind_int64(pStmt, 5, iEndBlock);
135807 sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
135808 sqlite3_step(pStmt);
135809 rc = sqlite3_reset(pStmt);
135811 return rc;
135815 ** Return the size of the common prefix (if any) shared by zPrev and
135816 ** zNext, in bytes. For example,
135818 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
135819 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
135820 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
135822 static int fts3PrefixCompress(
135823 const char *zPrev, /* Buffer containing previous term */
135824 int nPrev, /* Size of buffer zPrev in bytes */
135825 const char *zNext, /* Buffer containing next term */
135826 int nNext /* Size of buffer zNext in bytes */
135828 int n;
135829 UNUSED_PARAMETER(nNext);
135830 for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
135831 return n;
135835 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
135836 ** (according to memcmp) than the previous term.
135838 static int fts3NodeAddTerm(
135839 Fts3Table *p, /* Virtual table handle */
135840 SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
135841 int isCopyTerm, /* True if zTerm/nTerm is transient */
135842 const char *zTerm, /* Pointer to buffer containing term */
135843 int nTerm /* Size of term in bytes */
135845 SegmentNode *pTree = *ppTree;
135846 int rc;
135847 SegmentNode *pNew;
135849 /* First try to append the term to the current node. Return early if
135850 ** this is possible.
135852 if( pTree ){
135853 int nData = pTree->nData; /* Current size of node in bytes */
135854 int nReq = nData; /* Required space after adding zTerm */
135855 int nPrefix; /* Number of bytes of prefix compression */
135856 int nSuffix; /* Suffix length */
135858 nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
135859 nSuffix = nTerm-nPrefix;
135861 nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
135862 if( nReq<=p->nNodeSize || !pTree->zTerm ){
135864 if( nReq>p->nNodeSize ){
135865 /* An unusual case: this is the first term to be added to the node
135866 ** and the static node buffer (p->nNodeSize bytes) is not large
135867 ** enough. Use a separately malloced buffer instead This wastes
135868 ** p->nNodeSize bytes, but since this scenario only comes about when
135869 ** the database contain two terms that share a prefix of almost 2KB,
135870 ** this is not expected to be a serious problem.
135872 assert( pTree->aData==(char *)&pTree[1] );
135873 pTree->aData = (char *)sqlite3_malloc(nReq);
135874 if( !pTree->aData ){
135875 return SQLITE_NOMEM;
135879 if( pTree->zTerm ){
135880 /* There is no prefix-length field for first term in a node */
135881 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
135884 nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
135885 memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
135886 pTree->nData = nData + nSuffix;
135887 pTree->nEntry++;
135889 if( isCopyTerm ){
135890 if( pTree->nMalloc<nTerm ){
135891 char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
135892 if( !zNew ){
135893 return SQLITE_NOMEM;
135895 pTree->nMalloc = nTerm*2;
135896 pTree->zMalloc = zNew;
135898 pTree->zTerm = pTree->zMalloc;
135899 memcpy(pTree->zTerm, zTerm, nTerm);
135900 pTree->nTerm = nTerm;
135901 }else{
135902 pTree->zTerm = (char *)zTerm;
135903 pTree->nTerm = nTerm;
135905 return SQLITE_OK;
135909 /* If control flows to here, it was not possible to append zTerm to the
135910 ** current node. Create a new node (a right-sibling of the current node).
135911 ** If this is the first node in the tree, the term is added to it.
135913 ** Otherwise, the term is not added to the new node, it is left empty for
135914 ** now. Instead, the term is inserted into the parent of pTree. If pTree
135915 ** has no parent, one is created here.
135917 pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
135918 if( !pNew ){
135919 return SQLITE_NOMEM;
135921 memset(pNew, 0, sizeof(SegmentNode));
135922 pNew->nData = 1 + FTS3_VARINT_MAX;
135923 pNew->aData = (char *)&pNew[1];
135925 if( pTree ){
135926 SegmentNode *pParent = pTree->pParent;
135927 rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
135928 if( pTree->pParent==0 ){
135929 pTree->pParent = pParent;
135931 pTree->pRight = pNew;
135932 pNew->pLeftmost = pTree->pLeftmost;
135933 pNew->pParent = pParent;
135934 pNew->zMalloc = pTree->zMalloc;
135935 pNew->nMalloc = pTree->nMalloc;
135936 pTree->zMalloc = 0;
135937 }else{
135938 pNew->pLeftmost = pNew;
135939 rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
135942 *ppTree = pNew;
135943 return rc;
135947 ** Helper function for fts3NodeWrite().
135949 static int fts3TreeFinishNode(
135950 SegmentNode *pTree,
135951 int iHeight,
135952 sqlite3_int64 iLeftChild
135954 int nStart;
135955 assert( iHeight>=1 && iHeight<128 );
135956 nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
135957 pTree->aData[nStart] = (char)iHeight;
135958 sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
135959 return nStart;
135963 ** Write the buffer for the segment node pTree and all of its peers to the
135964 ** database. Then call this function recursively to write the parent of
135965 ** pTree and its peers to the database.
135967 ** Except, if pTree is a root node, do not write it to the database. Instead,
135968 ** set output variables *paRoot and *pnRoot to contain the root node.
135970 ** If successful, SQLITE_OK is returned and output variable *piLast is
135971 ** set to the largest blockid written to the database (or zero if no
135972 ** blocks were written to the db). Otherwise, an SQLite error code is
135973 ** returned.
135975 static int fts3NodeWrite(
135976 Fts3Table *p, /* Virtual table handle */
135977 SegmentNode *pTree, /* SegmentNode handle */
135978 int iHeight, /* Height of this node in tree */
135979 sqlite3_int64 iLeaf, /* Block id of first leaf node */
135980 sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
135981 sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
135982 char **paRoot, /* OUT: Data for root node */
135983 int *pnRoot /* OUT: Size of root node in bytes */
135985 int rc = SQLITE_OK;
135987 if( !pTree->pParent ){
135988 /* Root node of the tree. */
135989 int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
135990 *piLast = iFree-1;
135991 *pnRoot = pTree->nData - nStart;
135992 *paRoot = &pTree->aData[nStart];
135993 }else{
135994 SegmentNode *pIter;
135995 sqlite3_int64 iNextFree = iFree;
135996 sqlite3_int64 iNextLeaf = iLeaf;
135997 for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
135998 int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
135999 int nWrite = pIter->nData - nStart;
136001 rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
136002 iNextFree++;
136003 iNextLeaf += (pIter->nEntry+1);
136005 if( rc==SQLITE_OK ){
136006 assert( iNextLeaf==iFree );
136007 rc = fts3NodeWrite(
136008 p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
136013 return rc;
136017 ** Free all memory allocations associated with the tree pTree.
136019 static void fts3NodeFree(SegmentNode *pTree){
136020 if( pTree ){
136021 SegmentNode *p = pTree->pLeftmost;
136022 fts3NodeFree(p->pParent);
136023 while( p ){
136024 SegmentNode *pRight = p->pRight;
136025 if( p->aData!=(char *)&p[1] ){
136026 sqlite3_free(p->aData);
136028 assert( pRight==0 || p->zMalloc==0 );
136029 sqlite3_free(p->zMalloc);
136030 sqlite3_free(p);
136031 p = pRight;
136037 ** Add a term to the segment being constructed by the SegmentWriter object
136038 ** *ppWriter. When adding the first term to a segment, *ppWriter should
136039 ** be passed NULL. This function will allocate a new SegmentWriter object
136040 ** and return it via the input/output variable *ppWriter in this case.
136042 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
136044 static int fts3SegWriterAdd(
136045 Fts3Table *p, /* Virtual table handle */
136046 SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
136047 int isCopyTerm, /* True if buffer zTerm must be copied */
136048 const char *zTerm, /* Pointer to buffer containing term */
136049 int nTerm, /* Size of term in bytes */
136050 const char *aDoclist, /* Pointer to buffer containing doclist */
136051 int nDoclist /* Size of doclist in bytes */
136053 int nPrefix; /* Size of term prefix in bytes */
136054 int nSuffix; /* Size of term suffix in bytes */
136055 int nReq; /* Number of bytes required on leaf page */
136056 int nData;
136057 SegmentWriter *pWriter = *ppWriter;
136059 if( !pWriter ){
136060 int rc;
136061 sqlite3_stmt *pStmt;
136063 /* Allocate the SegmentWriter structure */
136064 pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
136065 if( !pWriter ) return SQLITE_NOMEM;
136066 memset(pWriter, 0, sizeof(SegmentWriter));
136067 *ppWriter = pWriter;
136069 /* Allocate a buffer in which to accumulate data */
136070 pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
136071 if( !pWriter->aData ) return SQLITE_NOMEM;
136072 pWriter->nSize = p->nNodeSize;
136074 /* Find the next free blockid in the %_segments table */
136075 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
136076 if( rc!=SQLITE_OK ) return rc;
136077 if( SQLITE_ROW==sqlite3_step(pStmt) ){
136078 pWriter->iFree = sqlite3_column_int64(pStmt, 0);
136079 pWriter->iFirst = pWriter->iFree;
136081 rc = sqlite3_reset(pStmt);
136082 if( rc!=SQLITE_OK ) return rc;
136084 nData = pWriter->nData;
136086 nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
136087 nSuffix = nTerm-nPrefix;
136089 /* Figure out how many bytes are required by this new entry */
136090 nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
136091 sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
136092 nSuffix + /* Term suffix */
136093 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
136094 nDoclist; /* Doclist data */
136096 if( nData>0 && nData+nReq>p->nNodeSize ){
136097 int rc;
136099 /* The current leaf node is full. Write it out to the database. */
136100 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
136101 if( rc!=SQLITE_OK ) return rc;
136102 p->nLeafAdd++;
136104 /* Add the current term to the interior node tree. The term added to
136105 ** the interior tree must:
136107 ** a) be greater than the largest term on the leaf node just written
136108 ** to the database (still available in pWriter->zTerm), and
136110 ** b) be less than or equal to the term about to be added to the new
136111 ** leaf node (zTerm/nTerm).
136113 ** In other words, it must be the prefix of zTerm 1 byte longer than
136114 ** the common prefix (if any) of zTerm and pWriter->zTerm.
136116 assert( nPrefix<nTerm );
136117 rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
136118 if( rc!=SQLITE_OK ) return rc;
136120 nData = 0;
136121 pWriter->nTerm = 0;
136123 nPrefix = 0;
136124 nSuffix = nTerm;
136125 nReq = 1 + /* varint containing prefix size */
136126 sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
136127 nTerm + /* Term suffix */
136128 sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
136129 nDoclist; /* Doclist data */
136132 /* If the buffer currently allocated is too small for this entry, realloc
136133 ** the buffer to make it large enough.
136135 if( nReq>pWriter->nSize ){
136136 char *aNew = sqlite3_realloc(pWriter->aData, nReq);
136137 if( !aNew ) return SQLITE_NOMEM;
136138 pWriter->aData = aNew;
136139 pWriter->nSize = nReq;
136141 assert( nData+nReq<=pWriter->nSize );
136143 /* Append the prefix-compressed term and doclist to the buffer. */
136144 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
136145 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
136146 memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
136147 nData += nSuffix;
136148 nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
136149 memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
136150 pWriter->nData = nData + nDoclist;
136152 /* Save the current term so that it can be used to prefix-compress the next.
136153 ** If the isCopyTerm parameter is true, then the buffer pointed to by
136154 ** zTerm is transient, so take a copy of the term data. Otherwise, just
136155 ** store a copy of the pointer.
136157 if( isCopyTerm ){
136158 if( nTerm>pWriter->nMalloc ){
136159 char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
136160 if( !zNew ){
136161 return SQLITE_NOMEM;
136163 pWriter->nMalloc = nTerm*2;
136164 pWriter->zMalloc = zNew;
136165 pWriter->zTerm = zNew;
136167 assert( pWriter->zTerm==pWriter->zMalloc );
136168 memcpy(pWriter->zTerm, zTerm, nTerm);
136169 }else{
136170 pWriter->zTerm = (char *)zTerm;
136172 pWriter->nTerm = nTerm;
136174 return SQLITE_OK;
136178 ** Flush all data associated with the SegmentWriter object pWriter to the
136179 ** database. This function must be called after all terms have been added
136180 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
136181 ** returned. Otherwise, an SQLite error code.
136183 static int fts3SegWriterFlush(
136184 Fts3Table *p, /* Virtual table handle */
136185 SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
136186 sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
136187 int iIdx /* Value for 'idx' column of %_segdir */
136189 int rc; /* Return code */
136190 if( pWriter->pTree ){
136191 sqlite3_int64 iLast = 0; /* Largest block id written to database */
136192 sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
136193 char *zRoot = NULL; /* Pointer to buffer containing root node */
136194 int nRoot = 0; /* Size of buffer zRoot */
136196 iLastLeaf = pWriter->iFree;
136197 rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
136198 if( rc==SQLITE_OK ){
136199 rc = fts3NodeWrite(p, pWriter->pTree, 1,
136200 pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
136202 if( rc==SQLITE_OK ){
136203 rc = fts3WriteSegdir(
136204 p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
136206 }else{
136207 /* The entire tree fits on the root node. Write it to the segdir table. */
136208 rc = fts3WriteSegdir(
136209 p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
136211 p->nLeafAdd++;
136212 return rc;
136216 ** Release all memory held by the SegmentWriter object passed as the
136217 ** first argument.
136219 static void fts3SegWriterFree(SegmentWriter *pWriter){
136220 if( pWriter ){
136221 sqlite3_free(pWriter->aData);
136222 sqlite3_free(pWriter->zMalloc);
136223 fts3NodeFree(pWriter->pTree);
136224 sqlite3_free(pWriter);
136229 ** The first value in the apVal[] array is assumed to contain an integer.
136230 ** This function tests if there exist any documents with docid values that
136231 ** are different from that integer. i.e. if deleting the document with docid
136232 ** pRowid would mean the FTS3 table were empty.
136234 ** If successful, *pisEmpty is set to true if the table is empty except for
136235 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
136236 ** error occurs, an SQLite error code is returned.
136238 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
136239 sqlite3_stmt *pStmt;
136240 int rc;
136241 if( p->zContentTbl ){
136242 /* If using the content=xxx option, assume the table is never empty */
136243 *pisEmpty = 0;
136244 rc = SQLITE_OK;
136245 }else{
136246 rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
136247 if( rc==SQLITE_OK ){
136248 if( SQLITE_ROW==sqlite3_step(pStmt) ){
136249 *pisEmpty = sqlite3_column_int(pStmt, 0);
136251 rc = sqlite3_reset(pStmt);
136254 return rc;
136258 ** Set *pnMax to the largest segment level in the database for the index
136259 ** iIndex.
136261 ** Segment levels are stored in the 'level' column of the %_segdir table.
136263 ** Return SQLITE_OK if successful, or an SQLite error code if not.
136265 static int fts3SegmentMaxLevel(
136266 Fts3Table *p,
136267 int iLangid,
136268 int iIndex,
136269 sqlite3_int64 *pnMax
136271 sqlite3_stmt *pStmt;
136272 int rc;
136273 assert( iIndex>=0 && iIndex<p->nIndex );
136275 /* Set pStmt to the compiled version of:
136277 ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
136279 ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
136281 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
136282 if( rc!=SQLITE_OK ) return rc;
136283 sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
136284 sqlite3_bind_int64(pStmt, 2,
136285 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
136287 if( SQLITE_ROW==sqlite3_step(pStmt) ){
136288 *pnMax = sqlite3_column_int64(pStmt, 0);
136290 return sqlite3_reset(pStmt);
136294 ** Delete all entries in the %_segments table associated with the segment
136295 ** opened with seg-reader pSeg. This function does not affect the contents
136296 ** of the %_segdir table.
136298 static int fts3DeleteSegment(
136299 Fts3Table *p, /* FTS table handle */
136300 Fts3SegReader *pSeg /* Segment to delete */
136302 int rc = SQLITE_OK; /* Return code */
136303 if( pSeg->iStartBlock ){
136304 sqlite3_stmt *pDelete; /* SQL statement to delete rows */
136305 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
136306 if( rc==SQLITE_OK ){
136307 sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
136308 sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
136309 sqlite3_step(pDelete);
136310 rc = sqlite3_reset(pDelete);
136313 return rc;
136317 ** This function is used after merging multiple segments into a single large
136318 ** segment to delete the old, now redundant, segment b-trees. Specifically,
136319 ** it:
136321 ** 1) Deletes all %_segments entries for the segments associated with
136322 ** each of the SegReader objects in the array passed as the third
136323 ** argument, and
136325 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
136326 ** entries regardless of level if (iLevel<0).
136328 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
136330 static int fts3DeleteSegdir(
136331 Fts3Table *p, /* Virtual table handle */
136332 int iLangid, /* Language id */
136333 int iIndex, /* Index for p->aIndex */
136334 int iLevel, /* Level of %_segdir entries to delete */
136335 Fts3SegReader **apSegment, /* Array of SegReader objects */
136336 int nReader /* Size of array apSegment */
136338 int rc = SQLITE_OK; /* Return Code */
136339 int i; /* Iterator variable */
136340 sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
136342 for(i=0; rc==SQLITE_OK && i<nReader; i++){
136343 rc = fts3DeleteSegment(p, apSegment[i]);
136345 if( rc!=SQLITE_OK ){
136346 return rc;
136349 assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
136350 if( iLevel==FTS3_SEGCURSOR_ALL ){
136351 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
136352 if( rc==SQLITE_OK ){
136353 sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
136354 sqlite3_bind_int64(pDelete, 2,
136355 getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
136358 }else{
136359 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
136360 if( rc==SQLITE_OK ){
136361 sqlite3_bind_int64(
136362 pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
136367 if( rc==SQLITE_OK ){
136368 sqlite3_step(pDelete);
136369 rc = sqlite3_reset(pDelete);
136372 return rc;
136376 ** When this function is called, buffer *ppList (size *pnList bytes) contains
136377 ** a position list that may (or may not) feature multiple columns. This
136378 ** function adjusts the pointer *ppList and the length *pnList so that they
136379 ** identify the subset of the position list that corresponds to column iCol.
136381 ** If there are no entries in the input position list for column iCol, then
136382 ** *pnList is set to zero before returning.
136384 ** If parameter bZero is non-zero, then any part of the input list following
136385 ** the end of the output list is zeroed before returning.
136387 static void fts3ColumnFilter(
136388 int iCol, /* Column to filter on */
136389 int bZero, /* Zero out anything following *ppList */
136390 char **ppList, /* IN/OUT: Pointer to position list */
136391 int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
136393 char *pList = *ppList;
136394 int nList = *pnList;
136395 char *pEnd = &pList[nList];
136396 int iCurrent = 0;
136397 char *p = pList;
136399 assert( iCol>=0 );
136400 while( 1 ){
136401 char c = 0;
136402 while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
136404 if( iCol==iCurrent ){
136405 nList = (int)(p - pList);
136406 break;
136409 nList -= (int)(p - pList);
136410 pList = p;
136411 if( nList==0 ){
136412 break;
136414 p = &pList[1];
136415 p += fts3GetVarint32(p, &iCurrent);
136418 if( bZero && &pList[nList]!=pEnd ){
136419 memset(&pList[nList], 0, pEnd - &pList[nList]);
136421 *ppList = pList;
136422 *pnList = nList;
136426 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
136427 ** existing data). Grow the buffer if required.
136429 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
136430 ** trying to resize the buffer, return SQLITE_NOMEM.
136432 static int fts3MsrBufferData(
136433 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
136434 char *pList,
136435 int nList
136437 if( nList>pMsr->nBuffer ){
136438 char *pNew;
136439 pMsr->nBuffer = nList*2;
136440 pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
136441 if( !pNew ) return SQLITE_NOMEM;
136442 pMsr->aBuffer = pNew;
136445 memcpy(pMsr->aBuffer, pList, nList);
136446 return SQLITE_OK;
136449 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
136450 Fts3Table *p, /* Virtual table handle */
136451 Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
136452 sqlite3_int64 *piDocid, /* OUT: Docid value */
136453 char **paPoslist, /* OUT: Pointer to position list */
136454 int *pnPoslist /* OUT: Size of position list in bytes */
136456 int nMerge = pMsr->nAdvance;
136457 Fts3SegReader **apSegment = pMsr->apSegment;
136458 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
136459 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
136462 if( nMerge==0 ){
136463 *paPoslist = 0;
136464 return SQLITE_OK;
136467 while( 1 ){
136468 Fts3SegReader *pSeg;
136469 pSeg = pMsr->apSegment[0];
136471 if( pSeg->pOffsetList==0 ){
136472 *paPoslist = 0;
136473 break;
136474 }else{
136475 int rc;
136476 char *pList;
136477 int nList;
136478 int j;
136479 sqlite3_int64 iDocid = apSegment[0]->iDocid;
136481 rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
136482 j = 1;
136483 while( rc==SQLITE_OK
136484 && j<nMerge
136485 && apSegment[j]->pOffsetList
136486 && apSegment[j]->iDocid==iDocid
136488 rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
136491 if( rc!=SQLITE_OK ) return rc;
136492 fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
136494 if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
136495 rc = fts3MsrBufferData(pMsr, pList, nList+1);
136496 if( rc!=SQLITE_OK ) return rc;
136497 assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
136498 pList = pMsr->aBuffer;
136501 if( pMsr->iColFilter>=0 ){
136502 fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
136505 if( nList>0 ){
136506 *paPoslist = pList;
136507 *piDocid = iDocid;
136508 *pnPoslist = nList;
136509 break;
136514 return SQLITE_OK;
136517 static int fts3SegReaderStart(
136518 Fts3Table *p, /* Virtual table handle */
136519 Fts3MultiSegReader *pCsr, /* Cursor object */
136520 const char *zTerm, /* Term searched for (or NULL) */
136521 int nTerm /* Length of zTerm in bytes */
136523 int i;
136524 int nSeg = pCsr->nSegment;
136526 /* If the Fts3SegFilter defines a specific term (or term prefix) to search
136527 ** for, then advance each segment iterator until it points to a term of
136528 ** equal or greater value than the specified term. This prevents many
136529 ** unnecessary merge/sort operations for the case where single segment
136530 ** b-tree leaf nodes contain more than one term.
136532 for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
136533 int res = 0;
136534 Fts3SegReader *pSeg = pCsr->apSegment[i];
136536 int rc = fts3SegReaderNext(p, pSeg, 0);
136537 if( rc!=SQLITE_OK ) return rc;
136538 }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
136540 if( pSeg->bLookup && res!=0 ){
136541 fts3SegReaderSetEof(pSeg);
136544 fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
136546 return SQLITE_OK;
136549 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
136550 Fts3Table *p, /* Virtual table handle */
136551 Fts3MultiSegReader *pCsr, /* Cursor object */
136552 Fts3SegFilter *pFilter /* Restrictions on range of iteration */
136554 pCsr->pFilter = pFilter;
136555 return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
136558 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
136559 Fts3Table *p, /* Virtual table handle */
136560 Fts3MultiSegReader *pCsr, /* Cursor object */
136561 int iCol, /* Column to match on. */
136562 const char *zTerm, /* Term to iterate through a doclist for */
136563 int nTerm /* Number of bytes in zTerm */
136565 int i;
136566 int rc;
136567 int nSegment = pCsr->nSegment;
136568 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
136569 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
136572 assert( pCsr->pFilter==0 );
136573 assert( zTerm && nTerm>0 );
136575 /* Advance each segment iterator until it points to the term zTerm/nTerm. */
136576 rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
136577 if( rc!=SQLITE_OK ) return rc;
136579 /* Determine how many of the segments actually point to zTerm/nTerm. */
136580 for(i=0; i<nSegment; i++){
136581 Fts3SegReader *pSeg = pCsr->apSegment[i];
136582 if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
136583 break;
136586 pCsr->nAdvance = i;
136588 /* Advance each of the segments to point to the first docid. */
136589 for(i=0; i<pCsr->nAdvance; i++){
136590 rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
136591 if( rc!=SQLITE_OK ) return rc;
136593 fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
136595 assert( iCol<0 || iCol<p->nColumn );
136596 pCsr->iColFilter = iCol;
136598 return SQLITE_OK;
136602 ** This function is called on a MultiSegReader that has been started using
136603 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
136604 ** have been made. Calling this function puts the MultiSegReader in such
136605 ** a state that if the next two calls are:
136607 ** sqlite3Fts3SegReaderStart()
136608 ** sqlite3Fts3SegReaderStep()
136610 ** then the entire doclist for the term is available in
136611 ** MultiSegReader.aDoclist/nDoclist.
136613 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
136614 int i; /* Used to iterate through segment-readers */
136616 assert( pCsr->zTerm==0 );
136617 assert( pCsr->nTerm==0 );
136618 assert( pCsr->aDoclist==0 );
136619 assert( pCsr->nDoclist==0 );
136621 pCsr->nAdvance = 0;
136622 pCsr->bRestart = 1;
136623 for(i=0; i<pCsr->nSegment; i++){
136624 pCsr->apSegment[i]->pOffsetList = 0;
136625 pCsr->apSegment[i]->nOffsetList = 0;
136626 pCsr->apSegment[i]->iDocid = 0;
136629 return SQLITE_OK;
136633 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
136634 Fts3Table *p, /* Virtual table handle */
136635 Fts3MultiSegReader *pCsr /* Cursor object */
136637 int rc = SQLITE_OK;
136639 int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
136640 int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
136641 int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
136642 int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
136643 int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
136644 int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
136646 Fts3SegReader **apSegment = pCsr->apSegment;
136647 int nSegment = pCsr->nSegment;
136648 Fts3SegFilter *pFilter = pCsr->pFilter;
136649 int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
136650 p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
136653 if( pCsr->nSegment==0 ) return SQLITE_OK;
136656 int nMerge;
136657 int i;
136659 /* Advance the first pCsr->nAdvance entries in the apSegment[] array
136660 ** forward. Then sort the list in order of current term again.
136662 for(i=0; i<pCsr->nAdvance; i++){
136663 Fts3SegReader *pSeg = apSegment[i];
136664 if( pSeg->bLookup ){
136665 fts3SegReaderSetEof(pSeg);
136666 }else{
136667 rc = fts3SegReaderNext(p, pSeg, 0);
136669 if( rc!=SQLITE_OK ) return rc;
136671 fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
136672 pCsr->nAdvance = 0;
136674 /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
136675 assert( rc==SQLITE_OK );
136676 if( apSegment[0]->aNode==0 ) break;
136678 pCsr->nTerm = apSegment[0]->nTerm;
136679 pCsr->zTerm = apSegment[0]->zTerm;
136681 /* If this is a prefix-search, and if the term that apSegment[0] points
136682 ** to does not share a suffix with pFilter->zTerm/nTerm, then all
136683 ** required callbacks have been made. In this case exit early.
136685 ** Similarly, if this is a search for an exact match, and the first term
136686 ** of segment apSegment[0] is not a match, exit early.
136688 if( pFilter->zTerm && !isScan ){
136689 if( pCsr->nTerm<pFilter->nTerm
136690 || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
136691 || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
136693 break;
136697 nMerge = 1;
136698 while( nMerge<nSegment
136699 && apSegment[nMerge]->aNode
136700 && apSegment[nMerge]->nTerm==pCsr->nTerm
136701 && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
136703 nMerge++;
136706 assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
136707 if( nMerge==1
136708 && !isIgnoreEmpty
136709 && !isFirst
136710 && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
136712 pCsr->nDoclist = apSegment[0]->nDoclist;
136713 if( fts3SegReaderIsPending(apSegment[0]) ){
136714 rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
136715 pCsr->aDoclist = pCsr->aBuffer;
136716 }else{
136717 pCsr->aDoclist = apSegment[0]->aDoclist;
136719 if( rc==SQLITE_OK ) rc = SQLITE_ROW;
136720 }else{
136721 int nDoclist = 0; /* Size of doclist */
136722 sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
136724 /* The current term of the first nMerge entries in the array
136725 ** of Fts3SegReader objects is the same. The doclists must be merged
136726 ** and a single term returned with the merged doclist.
136728 for(i=0; i<nMerge; i++){
136729 fts3SegReaderFirstDocid(p, apSegment[i]);
136731 fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
136732 while( apSegment[0]->pOffsetList ){
136733 int j; /* Number of segments that share a docid */
136734 char *pList = 0;
136735 int nList = 0;
136736 int nByte;
136737 sqlite3_int64 iDocid = apSegment[0]->iDocid;
136738 fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
136739 j = 1;
136740 while( j<nMerge
136741 && apSegment[j]->pOffsetList
136742 && apSegment[j]->iDocid==iDocid
136744 fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
136748 if( isColFilter ){
136749 fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
136752 if( !isIgnoreEmpty || nList>0 ){
136754 /* Calculate the 'docid' delta value to write into the merged
136755 ** doclist. */
136756 sqlite3_int64 iDelta;
136757 if( p->bDescIdx && nDoclist>0 ){
136758 iDelta = iPrev - iDocid;
136759 }else{
136760 iDelta = iDocid - iPrev;
136762 assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
136763 assert( nDoclist>0 || iDelta==iDocid );
136765 nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
136766 if( nDoclist+nByte>pCsr->nBuffer ){
136767 char *aNew;
136768 pCsr->nBuffer = (nDoclist+nByte)*2;
136769 aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
136770 if( !aNew ){
136771 return SQLITE_NOMEM;
136773 pCsr->aBuffer = aNew;
136776 if( isFirst ){
136777 char *a = &pCsr->aBuffer[nDoclist];
136778 int nWrite;
136780 nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
136781 if( nWrite ){
136782 iPrev = iDocid;
136783 nDoclist += nWrite;
136785 }else{
136786 nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
136787 iPrev = iDocid;
136788 if( isRequirePos ){
136789 memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
136790 nDoclist += nList;
136791 pCsr->aBuffer[nDoclist++] = '\0';
136796 fts3SegReaderSort(apSegment, nMerge, j, xCmp);
136798 if( nDoclist>0 ){
136799 pCsr->aDoclist = pCsr->aBuffer;
136800 pCsr->nDoclist = nDoclist;
136801 rc = SQLITE_ROW;
136804 pCsr->nAdvance = nMerge;
136805 }while( rc==SQLITE_OK );
136807 return rc;
136811 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
136812 Fts3MultiSegReader *pCsr /* Cursor object */
136814 if( pCsr ){
136815 int i;
136816 for(i=0; i<pCsr->nSegment; i++){
136817 sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
136819 sqlite3_free(pCsr->apSegment);
136820 sqlite3_free(pCsr->aBuffer);
136822 pCsr->nSegment = 0;
136823 pCsr->apSegment = 0;
136824 pCsr->aBuffer = 0;
136829 ** Merge all level iLevel segments in the database into a single
136830 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
136831 ** single segment with a level equal to the numerically largest level
136832 ** currently present in the database.
136834 ** If this function is called with iLevel<0, but there is only one
136835 ** segment in the database, SQLITE_DONE is returned immediately.
136836 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
136837 ** an SQLite error code is returned.
136839 static int fts3SegmentMerge(
136840 Fts3Table *p,
136841 int iLangid, /* Language id to merge */
136842 int iIndex, /* Index in p->aIndex[] to merge */
136843 int iLevel /* Level to merge */
136845 int rc; /* Return code */
136846 int iIdx = 0; /* Index of new segment */
136847 sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
136848 SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
136849 Fts3SegFilter filter; /* Segment term filter condition */
136850 Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
136851 int bIgnoreEmpty = 0; /* True to ignore empty segments */
136853 assert( iLevel==FTS3_SEGCURSOR_ALL
136854 || iLevel==FTS3_SEGCURSOR_PENDING
136855 || iLevel>=0
136857 assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
136858 assert( iIndex>=0 && iIndex<p->nIndex );
136860 rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
136861 if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
136863 if( iLevel==FTS3_SEGCURSOR_ALL ){
136864 /* This call is to merge all segments in the database to a single
136865 ** segment. The level of the new segment is equal to the numerically
136866 ** greatest segment level currently present in the database for this
136867 ** index. The idx of the new segment is always 0. */
136868 if( csr.nSegment==1 ){
136869 rc = SQLITE_DONE;
136870 goto finished;
136872 rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
136873 bIgnoreEmpty = 1;
136875 }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
136876 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
136877 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
136878 }else{
136879 /* This call is to merge all segments at level iLevel. find the next
136880 ** available segment index at level iLevel+1. The call to
136881 ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
136882 ** a single iLevel+2 segment if necessary. */
136883 rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
136884 iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
136886 if( rc!=SQLITE_OK ) goto finished;
136887 assert( csr.nSegment>0 );
136888 assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
136889 assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
136891 memset(&filter, 0, sizeof(Fts3SegFilter));
136892 filter.flags = FTS3_SEGMENT_REQUIRE_POS;
136893 filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
136895 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
136896 while( SQLITE_OK==rc ){
136897 rc = sqlite3Fts3SegReaderStep(p, &csr);
136898 if( rc!=SQLITE_ROW ) break;
136899 rc = fts3SegWriterAdd(p, &pWriter, 1,
136900 csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
136902 if( rc!=SQLITE_OK ) goto finished;
136903 assert( pWriter );
136905 if( iLevel!=FTS3_SEGCURSOR_PENDING ){
136906 rc = fts3DeleteSegdir(
136907 p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
136909 if( rc!=SQLITE_OK ) goto finished;
136911 rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
136913 finished:
136914 fts3SegWriterFree(pWriter);
136915 sqlite3Fts3SegReaderFinish(&csr);
136916 return rc;
136921 ** Flush the contents of pendingTerms to level 0 segments.
136923 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
136924 int rc = SQLITE_OK;
136925 int i;
136927 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
136928 rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
136929 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
136931 sqlite3Fts3PendingTermsClear(p);
136933 /* Determine the auto-incr-merge setting if unknown. If enabled,
136934 ** estimate the number of leaf blocks of content to be written
136936 if( rc==SQLITE_OK && p->bHasStat
136937 && p->bAutoincrmerge==0xff && p->nLeafAdd>0
136939 sqlite3_stmt *pStmt = 0;
136940 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
136941 if( rc==SQLITE_OK ){
136942 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
136943 rc = sqlite3_step(pStmt);
136944 p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
136945 rc = sqlite3_reset(pStmt);
136948 return rc;
136952 ** Encode N integers as varints into a blob.
136954 static void fts3EncodeIntArray(
136955 int N, /* The number of integers to encode */
136956 u32 *a, /* The integer values */
136957 char *zBuf, /* Write the BLOB here */
136958 int *pNBuf /* Write number of bytes if zBuf[] used here */
136960 int i, j;
136961 for(i=j=0; i<N; i++){
136962 j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
136964 *pNBuf = j;
136968 ** Decode a blob of varints into N integers
136970 static void fts3DecodeIntArray(
136971 int N, /* The number of integers to decode */
136972 u32 *a, /* Write the integer values */
136973 const char *zBuf, /* The BLOB containing the varints */
136974 int nBuf /* size of the BLOB */
136976 int i, j;
136977 UNUSED_PARAMETER(nBuf);
136978 for(i=j=0; i<N; i++){
136979 sqlite3_int64 x;
136980 j += sqlite3Fts3GetVarint(&zBuf[j], &x);
136981 assert(j<=nBuf);
136982 a[i] = (u32)(x & 0xffffffff);
136987 ** Insert the sizes (in tokens) for each column of the document
136988 ** with docid equal to p->iPrevDocid. The sizes are encoded as
136989 ** a blob of varints.
136991 static void fts3InsertDocsize(
136992 int *pRC, /* Result code */
136993 Fts3Table *p, /* Table into which to insert */
136994 u32 *aSz /* Sizes of each column, in tokens */
136996 char *pBlob; /* The BLOB encoding of the document size */
136997 int nBlob; /* Number of bytes in the BLOB */
136998 sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
136999 int rc; /* Result code from subfunctions */
137001 if( *pRC ) return;
137002 pBlob = sqlite3_malloc( 10*p->nColumn );
137003 if( pBlob==0 ){
137004 *pRC = SQLITE_NOMEM;
137005 return;
137007 fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
137008 rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
137009 if( rc ){
137010 sqlite3_free(pBlob);
137011 *pRC = rc;
137012 return;
137014 sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
137015 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
137016 sqlite3_step(pStmt);
137017 *pRC = sqlite3_reset(pStmt);
137021 ** Record 0 of the %_stat table contains a blob consisting of N varints,
137022 ** where N is the number of user defined columns in the fts3 table plus
137023 ** two. If nCol is the number of user defined columns, then values of the
137024 ** varints are set as follows:
137026 ** Varint 0: Total number of rows in the table.
137028 ** Varint 1..nCol: For each column, the total number of tokens stored in
137029 ** the column for all rows of the table.
137031 ** Varint 1+nCol: The total size, in bytes, of all text values in all
137032 ** columns of all rows of the table.
137035 static void fts3UpdateDocTotals(
137036 int *pRC, /* The result code */
137037 Fts3Table *p, /* Table being updated */
137038 u32 *aSzIns, /* Size increases */
137039 u32 *aSzDel, /* Size decreases */
137040 int nChng /* Change in the number of documents */
137042 char *pBlob; /* Storage for BLOB written into %_stat */
137043 int nBlob; /* Size of BLOB written into %_stat */
137044 u32 *a; /* Array of integers that becomes the BLOB */
137045 sqlite3_stmt *pStmt; /* Statement for reading and writing */
137046 int i; /* Loop counter */
137047 int rc; /* Result code from subfunctions */
137049 const int nStat = p->nColumn+2;
137051 if( *pRC ) return;
137052 a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
137053 if( a==0 ){
137054 *pRC = SQLITE_NOMEM;
137055 return;
137057 pBlob = (char*)&a[nStat];
137058 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
137059 if( rc ){
137060 sqlite3_free(a);
137061 *pRC = rc;
137062 return;
137064 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
137065 if( sqlite3_step(pStmt)==SQLITE_ROW ){
137066 fts3DecodeIntArray(nStat, a,
137067 sqlite3_column_blob(pStmt, 0),
137068 sqlite3_column_bytes(pStmt, 0));
137069 }else{
137070 memset(a, 0, sizeof(u32)*(nStat) );
137072 rc = sqlite3_reset(pStmt);
137073 if( rc!=SQLITE_OK ){
137074 sqlite3_free(a);
137075 *pRC = rc;
137076 return;
137078 if( nChng<0 && a[0]<(u32)(-nChng) ){
137079 a[0] = 0;
137080 }else{
137081 a[0] += nChng;
137083 for(i=0; i<p->nColumn+1; i++){
137084 u32 x = a[i+1];
137085 if( x+aSzIns[i] < aSzDel[i] ){
137086 x = 0;
137087 }else{
137088 x = x + aSzIns[i] - aSzDel[i];
137090 a[i+1] = x;
137092 fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
137093 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
137094 if( rc ){
137095 sqlite3_free(a);
137096 *pRC = rc;
137097 return;
137099 sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
137100 sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
137101 sqlite3_step(pStmt);
137102 *pRC = sqlite3_reset(pStmt);
137103 sqlite3_free(a);
137107 ** Merge the entire database so that there is one segment for each
137108 ** iIndex/iLangid combination.
137110 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
137111 int bSeenDone = 0;
137112 int rc;
137113 sqlite3_stmt *pAllLangid = 0;
137115 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
137116 if( rc==SQLITE_OK ){
137117 int rc2;
137118 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
137119 while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
137120 int i;
137121 int iLangid = sqlite3_column_int(pAllLangid, 0);
137122 for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
137123 rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
137124 if( rc==SQLITE_DONE ){
137125 bSeenDone = 1;
137126 rc = SQLITE_OK;
137130 rc2 = sqlite3_reset(pAllLangid);
137131 if( rc==SQLITE_OK ) rc = rc2;
137134 sqlite3Fts3SegmentsClose(p);
137135 sqlite3Fts3PendingTermsClear(p);
137137 return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
137141 ** This function is called when the user executes the following statement:
137143 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
137145 ** The entire FTS index is discarded and rebuilt. If the table is one
137146 ** created using the content=xxx option, then the new index is based on
137147 ** the current contents of the xxx table. Otherwise, it is rebuilt based
137148 ** on the contents of the %_content table.
137150 static int fts3DoRebuild(Fts3Table *p){
137151 int rc; /* Return Code */
137153 rc = fts3DeleteAll(p, 0);
137154 if( rc==SQLITE_OK ){
137155 u32 *aSz = 0;
137156 u32 *aSzIns = 0;
137157 u32 *aSzDel = 0;
137158 sqlite3_stmt *pStmt = 0;
137159 int nEntry = 0;
137161 /* Compose and prepare an SQL statement to loop through the content table */
137162 char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
137163 if( !zSql ){
137164 rc = SQLITE_NOMEM;
137165 }else{
137166 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
137167 sqlite3_free(zSql);
137170 if( rc==SQLITE_OK ){
137171 int nByte = sizeof(u32) * (p->nColumn+1)*3;
137172 aSz = (u32 *)sqlite3_malloc(nByte);
137173 if( aSz==0 ){
137174 rc = SQLITE_NOMEM;
137175 }else{
137176 memset(aSz, 0, nByte);
137177 aSzIns = &aSz[p->nColumn+1];
137178 aSzDel = &aSzIns[p->nColumn+1];
137182 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
137183 int iCol;
137184 int iLangid = langidFromSelect(p, pStmt);
137185 rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
137186 memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
137187 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
137188 if( p->abNotindexed[iCol]==0 ){
137189 const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
137190 rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
137191 aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
137194 if( p->bHasDocsize ){
137195 fts3InsertDocsize(&rc, p, aSz);
137197 if( rc!=SQLITE_OK ){
137198 sqlite3_finalize(pStmt);
137199 pStmt = 0;
137200 }else{
137201 nEntry++;
137202 for(iCol=0; iCol<=p->nColumn; iCol++){
137203 aSzIns[iCol] += aSz[iCol];
137207 if( p->bFts4 ){
137208 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
137210 sqlite3_free(aSz);
137212 if( pStmt ){
137213 int rc2 = sqlite3_finalize(pStmt);
137214 if( rc==SQLITE_OK ){
137215 rc = rc2;
137220 return rc;
137225 ** This function opens a cursor used to read the input data for an
137226 ** incremental merge operation. Specifically, it opens a cursor to scan
137227 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
137228 ** level iAbsLevel.
137230 static int fts3IncrmergeCsr(
137231 Fts3Table *p, /* FTS3 table handle */
137232 sqlite3_int64 iAbsLevel, /* Absolute level to open */
137233 int nSeg, /* Number of segments to merge */
137234 Fts3MultiSegReader *pCsr /* Cursor object to populate */
137236 int rc; /* Return Code */
137237 sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
137238 int nByte; /* Bytes allocated at pCsr->apSegment[] */
137240 /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
137241 memset(pCsr, 0, sizeof(*pCsr));
137242 nByte = sizeof(Fts3SegReader *) * nSeg;
137243 pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
137245 if( pCsr->apSegment==0 ){
137246 rc = SQLITE_NOMEM;
137247 }else{
137248 memset(pCsr->apSegment, 0, nByte);
137249 rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
137251 if( rc==SQLITE_OK ){
137252 int i;
137253 int rc2;
137254 sqlite3_bind_int64(pStmt, 1, iAbsLevel);
137255 assert( pCsr->nSegment==0 );
137256 for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
137257 rc = sqlite3Fts3SegReaderNew(i, 0,
137258 sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
137259 sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
137260 sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
137261 sqlite3_column_blob(pStmt, 4), /* segdir.root */
137262 sqlite3_column_bytes(pStmt, 4), /* segdir.root */
137263 &pCsr->apSegment[i]
137265 pCsr->nSegment++;
137267 rc2 = sqlite3_reset(pStmt);
137268 if( rc==SQLITE_OK ) rc = rc2;
137271 return rc;
137274 typedef struct IncrmergeWriter IncrmergeWriter;
137275 typedef struct NodeWriter NodeWriter;
137276 typedef struct Blob Blob;
137277 typedef struct NodeReader NodeReader;
137280 ** An instance of the following structure is used as a dynamic buffer
137281 ** to build up nodes or other blobs of data in.
137283 ** The function blobGrowBuffer() is used to extend the allocation.
137285 struct Blob {
137286 char *a; /* Pointer to allocation */
137287 int n; /* Number of valid bytes of data in a[] */
137288 int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
137292 ** This structure is used to build up buffers containing segment b-tree
137293 ** nodes (blocks).
137295 struct NodeWriter {
137296 sqlite3_int64 iBlock; /* Current block id */
137297 Blob key; /* Last key written to the current block */
137298 Blob block; /* Current block image */
137302 ** An object of this type contains the state required to create or append
137303 ** to an appendable b-tree segment.
137305 struct IncrmergeWriter {
137306 int nLeafEst; /* Space allocated for leaf blocks */
137307 int nWork; /* Number of leaf pages flushed */
137308 sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
137309 int iIdx; /* Index of *output* segment in iAbsLevel+1 */
137310 sqlite3_int64 iStart; /* Block number of first allocated block */
137311 sqlite3_int64 iEnd; /* Block number of last allocated block */
137312 NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
137316 ** An object of the following type is used to read data from a single
137317 ** FTS segment node. See the following functions:
137319 ** nodeReaderInit()
137320 ** nodeReaderNext()
137321 ** nodeReaderRelease()
137323 struct NodeReader {
137324 const char *aNode;
137325 int nNode;
137326 int iOff; /* Current offset within aNode[] */
137328 /* Output variables. Containing the current node entry. */
137329 sqlite3_int64 iChild; /* Pointer to child node */
137330 Blob term; /* Current term */
137331 const char *aDoclist; /* Pointer to doclist */
137332 int nDoclist; /* Size of doclist in bytes */
137336 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137337 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
137338 ** bytes in size, extend (realloc) it to be so.
137340 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
137341 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
137342 ** to reflect the new size of the pBlob->a[] buffer.
137344 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
137345 if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
137346 int nAlloc = nMin;
137347 char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
137348 if( a ){
137349 pBlob->nAlloc = nAlloc;
137350 pBlob->a = a;
137351 }else{
137352 *pRc = SQLITE_NOMEM;
137358 ** Attempt to advance the node-reader object passed as the first argument to
137359 ** the next entry on the node.
137361 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
137362 ** Otherwise return SQLITE_OK. If there is no next entry on the node
137363 ** (e.g. because the current entry is the last) set NodeReader->aNode to
137364 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
137365 ** variables for the new entry.
137367 static int nodeReaderNext(NodeReader *p){
137368 int bFirst = (p->term.n==0); /* True for first term on the node */
137369 int nPrefix = 0; /* Bytes to copy from previous term */
137370 int nSuffix = 0; /* Bytes to append to the prefix */
137371 int rc = SQLITE_OK; /* Return code */
137373 assert( p->aNode );
137374 if( p->iChild && bFirst==0 ) p->iChild++;
137375 if( p->iOff>=p->nNode ){
137376 /* EOF */
137377 p->aNode = 0;
137378 }else{
137379 if( bFirst==0 ){
137380 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
137382 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
137384 blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
137385 if( rc==SQLITE_OK ){
137386 memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
137387 p->term.n = nPrefix+nSuffix;
137388 p->iOff += nSuffix;
137389 if( p->iChild==0 ){
137390 p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
137391 p->aDoclist = &p->aNode[p->iOff];
137392 p->iOff += p->nDoclist;
137397 assert( p->iOff<=p->nNode );
137399 return rc;
137403 ** Release all dynamic resources held by node-reader object *p.
137405 static void nodeReaderRelease(NodeReader *p){
137406 sqlite3_free(p->term.a);
137410 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
137412 ** If successful, SQLITE_OK is returned and the NodeReader object set to
137413 ** point to the first entry on the node (if any). Otherwise, an SQLite
137414 ** error code is returned.
137416 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
137417 memset(p, 0, sizeof(NodeReader));
137418 p->aNode = aNode;
137419 p->nNode = nNode;
137421 /* Figure out if this is a leaf or an internal node. */
137422 if( p->aNode[0] ){
137423 /* An internal node. */
137424 p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
137425 }else{
137426 p->iOff = 1;
137429 return nodeReaderNext(p);
137433 ** This function is called while writing an FTS segment each time a leaf o
137434 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
137435 ** to be greater than the largest key on the node just written, but smaller
137436 ** than or equal to the first key that will be written to the next leaf
137437 ** node.
137439 ** The block id of the leaf node just written to disk may be found in
137440 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
137442 static int fts3IncrmergePush(
137443 Fts3Table *p, /* Fts3 table handle */
137444 IncrmergeWriter *pWriter, /* Writer object */
137445 const char *zTerm, /* Term to write to internal node */
137446 int nTerm /* Bytes at zTerm */
137448 sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
137449 int iLayer;
137451 assert( nTerm>0 );
137452 for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
137453 sqlite3_int64 iNextPtr = 0;
137454 NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
137455 int rc = SQLITE_OK;
137456 int nPrefix;
137457 int nSuffix;
137458 int nSpace;
137460 /* Figure out how much space the key will consume if it is written to
137461 ** the current node of layer iLayer. Due to the prefix compression,
137462 ** the space required changes depending on which node the key is to
137463 ** be added to. */
137464 nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
137465 nSuffix = nTerm - nPrefix;
137466 nSpace = sqlite3Fts3VarintLen(nPrefix);
137467 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
137469 if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
137470 /* If the current node of layer iLayer contains zero keys, or if adding
137471 ** the key to it will not cause it to grow to larger than nNodeSize
137472 ** bytes in size, write the key here. */
137474 Blob *pBlk = &pNode->block;
137475 if( pBlk->n==0 ){
137476 blobGrowBuffer(pBlk, p->nNodeSize, &rc);
137477 if( rc==SQLITE_OK ){
137478 pBlk->a[0] = (char)iLayer;
137479 pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
137482 blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
137483 blobGrowBuffer(&pNode->key, nTerm, &rc);
137485 if( rc==SQLITE_OK ){
137486 if( pNode->key.n ){
137487 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
137489 pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
137490 memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
137491 pBlk->n += nSuffix;
137493 memcpy(pNode->key.a, zTerm, nTerm);
137494 pNode->key.n = nTerm;
137496 }else{
137497 /* Otherwise, flush the current node of layer iLayer to disk.
137498 ** Then allocate a new, empty sibling node. The key will be written
137499 ** into the parent of this node. */
137500 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
137502 assert( pNode->block.nAlloc>=p->nNodeSize );
137503 pNode->block.a[0] = (char)iLayer;
137504 pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
137506 iNextPtr = pNode->iBlock;
137507 pNode->iBlock++;
137508 pNode->key.n = 0;
137511 if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
137512 iPtr = iNextPtr;
137515 assert( 0 );
137516 return 0;
137520 ** Append a term and (optionally) doclist to the FTS segment node currently
137521 ** stored in blob *pNode. The node need not contain any terms, but the
137522 ** header must be written before this function is called.
137524 ** A node header is a single 0x00 byte for a leaf node, or a height varint
137525 ** followed by the left-hand-child varint for an internal node.
137527 ** The term to be appended is passed via arguments zTerm/nTerm. For a
137528 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
137529 ** node, both aDoclist and nDoclist must be passed 0.
137531 ** If the size of the value in blob pPrev is zero, then this is the first
137532 ** term written to the node. Otherwise, pPrev contains a copy of the
137533 ** previous term. Before this function returns, it is updated to contain a
137534 ** copy of zTerm/nTerm.
137536 ** It is assumed that the buffer associated with pNode is already large
137537 ** enough to accommodate the new entry. The buffer associated with pPrev
137538 ** is extended by this function if requrired.
137540 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
137541 ** returned. Otherwise, SQLITE_OK.
137543 static int fts3AppendToNode(
137544 Blob *pNode, /* Current node image to append to */
137545 Blob *pPrev, /* Buffer containing previous term written */
137546 const char *zTerm, /* New term to write */
137547 int nTerm, /* Size of zTerm in bytes */
137548 const char *aDoclist, /* Doclist (or NULL) to write */
137549 int nDoclist /* Size of aDoclist in bytes */
137551 int rc = SQLITE_OK; /* Return code */
137552 int bFirst = (pPrev->n==0); /* True if this is the first term written */
137553 int nPrefix; /* Size of term prefix in bytes */
137554 int nSuffix; /* Size of term suffix in bytes */
137556 /* Node must have already been started. There must be a doclist for a
137557 ** leaf node, and there must not be a doclist for an internal node. */
137558 assert( pNode->n>0 );
137559 assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
137561 blobGrowBuffer(pPrev, nTerm, &rc);
137562 if( rc!=SQLITE_OK ) return rc;
137564 nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
137565 nSuffix = nTerm - nPrefix;
137566 memcpy(pPrev->a, zTerm, nTerm);
137567 pPrev->n = nTerm;
137569 if( bFirst==0 ){
137570 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
137572 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
137573 memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
137574 pNode->n += nSuffix;
137576 if( aDoclist ){
137577 pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
137578 memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
137579 pNode->n += nDoclist;
137582 assert( pNode->n<=pNode->nAlloc );
137584 return SQLITE_OK;
137588 ** Append the current term and doclist pointed to by cursor pCsr to the
137589 ** appendable b-tree segment opened for writing by pWriter.
137591 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
137593 static int fts3IncrmergeAppend(
137594 Fts3Table *p, /* Fts3 table handle */
137595 IncrmergeWriter *pWriter, /* Writer object */
137596 Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
137598 const char *zTerm = pCsr->zTerm;
137599 int nTerm = pCsr->nTerm;
137600 const char *aDoclist = pCsr->aDoclist;
137601 int nDoclist = pCsr->nDoclist;
137602 int rc = SQLITE_OK; /* Return code */
137603 int nSpace; /* Total space in bytes required on leaf */
137604 int nPrefix; /* Size of prefix shared with previous term */
137605 int nSuffix; /* Size of suffix (nTerm - nPrefix) */
137606 NodeWriter *pLeaf; /* Object used to write leaf nodes */
137608 pLeaf = &pWriter->aNodeWriter[0];
137609 nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
137610 nSuffix = nTerm - nPrefix;
137612 nSpace = sqlite3Fts3VarintLen(nPrefix);
137613 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
137614 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
137616 /* If the current block is not empty, and if adding this term/doclist
137617 ** to the current block would make it larger than Fts3Table.nNodeSize
137618 ** bytes, write this block out to the database. */
137619 if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
137620 rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
137621 pWriter->nWork++;
137623 /* Add the current term to the parent node. The term added to the
137624 ** parent must:
137626 ** a) be greater than the largest term on the leaf node just written
137627 ** to the database (still available in pLeaf->key), and
137629 ** b) be less than or equal to the term about to be added to the new
137630 ** leaf node (zTerm/nTerm).
137632 ** In other words, it must be the prefix of zTerm 1 byte longer than
137633 ** the common prefix (if any) of zTerm and pWriter->zTerm.
137635 if( rc==SQLITE_OK ){
137636 rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
137639 /* Advance to the next output block */
137640 pLeaf->iBlock++;
137641 pLeaf->key.n = 0;
137642 pLeaf->block.n = 0;
137644 nSuffix = nTerm;
137645 nSpace = 1;
137646 nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
137647 nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
137650 blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
137652 if( rc==SQLITE_OK ){
137653 if( pLeaf->block.n==0 ){
137654 pLeaf->block.n = 1;
137655 pLeaf->block.a[0] = '\0';
137657 rc = fts3AppendToNode(
137658 &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
137662 return rc;
137666 ** This function is called to release all dynamic resources held by the
137667 ** merge-writer object pWriter, and if no error has occurred, to flush
137668 ** all outstanding node buffers held by pWriter to disk.
137670 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
137671 ** is made to write any data to disk. Instead, this function serves only
137672 ** to release outstanding resources.
137674 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
137675 ** flushing buffers to disk, *pRc is set to an SQLite error code before
137676 ** returning.
137678 static void fts3IncrmergeRelease(
137679 Fts3Table *p, /* FTS3 table handle */
137680 IncrmergeWriter *pWriter, /* Merge-writer object */
137681 int *pRc /* IN/OUT: Error code */
137683 int i; /* Used to iterate through non-root layers */
137684 int iRoot; /* Index of root in pWriter->aNodeWriter */
137685 NodeWriter *pRoot; /* NodeWriter for root node */
137686 int rc = *pRc; /* Error code */
137688 /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
137689 ** root node. If the segment fits entirely on a single leaf node, iRoot
137690 ** will be set to 0. If the root node is the parent of the leaves, iRoot
137691 ** will be 1. And so on. */
137692 for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
137693 NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
137694 if( pNode->block.n>0 ) break;
137695 assert( *pRc || pNode->block.nAlloc==0 );
137696 assert( *pRc || pNode->key.nAlloc==0 );
137697 sqlite3_free(pNode->block.a);
137698 sqlite3_free(pNode->key.a);
137701 /* Empty output segment. This is a no-op. */
137702 if( iRoot<0 ) return;
137704 /* The entire output segment fits on a single node. Normally, this means
137705 ** the node would be stored as a blob in the "root" column of the %_segdir
137706 ** table. However, this is not permitted in this case. The problem is that
137707 ** space has already been reserved in the %_segments table, and so the
137708 ** start_block and end_block fields of the %_segdir table must be populated.
137709 ** And, by design or by accident, released versions of FTS cannot handle
137710 ** segments that fit entirely on the root node with start_block!=0.
137712 ** Instead, create a synthetic root node that contains nothing but a
137713 ** pointer to the single content node. So that the segment consists of a
137714 ** single leaf and a single interior (root) node.
137716 ** Todo: Better might be to defer allocating space in the %_segments
137717 ** table until we are sure it is needed.
137719 if( iRoot==0 ){
137720 Blob *pBlock = &pWriter->aNodeWriter[1].block;
137721 blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
137722 if( rc==SQLITE_OK ){
137723 pBlock->a[0] = 0x01;
137724 pBlock->n = 1 + sqlite3Fts3PutVarint(
137725 &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
137728 iRoot = 1;
137730 pRoot = &pWriter->aNodeWriter[iRoot];
137732 /* Flush all currently outstanding nodes to disk. */
137733 for(i=0; i<iRoot; i++){
137734 NodeWriter *pNode = &pWriter->aNodeWriter[i];
137735 if( pNode->block.n>0 && rc==SQLITE_OK ){
137736 rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
137738 sqlite3_free(pNode->block.a);
137739 sqlite3_free(pNode->key.a);
137742 /* Write the %_segdir record. */
137743 if( rc==SQLITE_OK ){
137744 rc = fts3WriteSegdir(p,
137745 pWriter->iAbsLevel+1, /* level */
137746 pWriter->iIdx, /* idx */
137747 pWriter->iStart, /* start_block */
137748 pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
137749 pWriter->iEnd, /* end_block */
137750 pRoot->block.a, pRoot->block.n /* root */
137753 sqlite3_free(pRoot->block.a);
137754 sqlite3_free(pRoot->key.a);
137756 *pRc = rc;
137760 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
137761 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
137762 ** the other, it is considered to be smaller than the other.
137764 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
137765 ** if it is greater.
137767 static int fts3TermCmp(
137768 const char *zLhs, int nLhs, /* LHS of comparison */
137769 const char *zRhs, int nRhs /* RHS of comparison */
137771 int nCmp = MIN(nLhs, nRhs);
137772 int res;
137774 res = memcmp(zLhs, zRhs, nCmp);
137775 if( res==0 ) res = nLhs - nRhs;
137777 return res;
137782 ** Query to see if the entry in the %_segments table with blockid iEnd is
137783 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
137784 ** returning. Otherwise, set *pbRes to 0.
137786 ** Or, if an error occurs while querying the database, return an SQLite
137787 ** error code. The final value of *pbRes is undefined in this case.
137789 ** This is used to test if a segment is an "appendable" segment. If it
137790 ** is, then a NULL entry has been inserted into the %_segments table
137791 ** with blockid %_segdir.end_block.
137793 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
137794 int bRes = 0; /* Result to set *pbRes to */
137795 sqlite3_stmt *pCheck = 0; /* Statement to query database with */
137796 int rc; /* Return code */
137798 rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
137799 if( rc==SQLITE_OK ){
137800 sqlite3_bind_int64(pCheck, 1, iEnd);
137801 if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
137802 rc = sqlite3_reset(pCheck);
137805 *pbRes = bRes;
137806 return rc;
137810 ** This function is called when initializing an incremental-merge operation.
137811 ** It checks if the existing segment with index value iIdx at absolute level
137812 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
137813 ** merge-writer object *pWriter is initialized to write to it.
137815 ** An existing segment can be appended to by an incremental merge if:
137817 ** * It was initially created as an appendable segment (with all required
137818 ** space pre-allocated), and
137820 ** * The first key read from the input (arguments zKey and nKey) is
137821 ** greater than the largest key currently stored in the potential
137822 ** output segment.
137824 static int fts3IncrmergeLoad(
137825 Fts3Table *p, /* Fts3 table handle */
137826 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
137827 int iIdx, /* Index of candidate output segment */
137828 const char *zKey, /* First key to write */
137829 int nKey, /* Number of bytes in nKey */
137830 IncrmergeWriter *pWriter /* Populate this object */
137832 int rc; /* Return code */
137833 sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
137835 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
137836 if( rc==SQLITE_OK ){
137837 sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
137838 sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
137839 sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
137840 const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
137841 int nRoot = 0; /* Size of aRoot[] in bytes */
137842 int rc2; /* Return code from sqlite3_reset() */
137843 int bAppendable = 0; /* Set to true if segment is appendable */
137845 /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
137846 sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
137847 sqlite3_bind_int(pSelect, 2, iIdx);
137848 if( sqlite3_step(pSelect)==SQLITE_ROW ){
137849 iStart = sqlite3_column_int64(pSelect, 1);
137850 iLeafEnd = sqlite3_column_int64(pSelect, 2);
137851 iEnd = sqlite3_column_int64(pSelect, 3);
137852 nRoot = sqlite3_column_bytes(pSelect, 4);
137853 aRoot = sqlite3_column_blob(pSelect, 4);
137854 }else{
137855 return sqlite3_reset(pSelect);
137858 /* Check for the zero-length marker in the %_segments table */
137859 rc = fts3IsAppendable(p, iEnd, &bAppendable);
137861 /* Check that zKey/nKey is larger than the largest key the candidate */
137862 if( rc==SQLITE_OK && bAppendable ){
137863 char *aLeaf = 0;
137864 int nLeaf = 0;
137866 rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
137867 if( rc==SQLITE_OK ){
137868 NodeReader reader;
137869 for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
137870 rc==SQLITE_OK && reader.aNode;
137871 rc = nodeReaderNext(&reader)
137873 assert( reader.aNode );
137875 if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
137876 bAppendable = 0;
137878 nodeReaderRelease(&reader);
137880 sqlite3_free(aLeaf);
137883 if( rc==SQLITE_OK && bAppendable ){
137884 /* It is possible to append to this segment. Set up the IncrmergeWriter
137885 ** object to do so. */
137886 int i;
137887 int nHeight = (int)aRoot[0];
137888 NodeWriter *pNode;
137890 pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
137891 pWriter->iStart = iStart;
137892 pWriter->iEnd = iEnd;
137893 pWriter->iAbsLevel = iAbsLevel;
137894 pWriter->iIdx = iIdx;
137896 for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
137897 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
137900 pNode = &pWriter->aNodeWriter[nHeight];
137901 pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
137902 blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
137903 if( rc==SQLITE_OK ){
137904 memcpy(pNode->block.a, aRoot, nRoot);
137905 pNode->block.n = nRoot;
137908 for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
137909 NodeReader reader;
137910 pNode = &pWriter->aNodeWriter[i];
137912 rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
137913 while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
137914 blobGrowBuffer(&pNode->key, reader.term.n, &rc);
137915 if( rc==SQLITE_OK ){
137916 memcpy(pNode->key.a, reader.term.a, reader.term.n);
137917 pNode->key.n = reader.term.n;
137918 if( i>0 ){
137919 char *aBlock = 0;
137920 int nBlock = 0;
137921 pNode = &pWriter->aNodeWriter[i-1];
137922 pNode->iBlock = reader.iChild;
137923 rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
137924 blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
137925 if( rc==SQLITE_OK ){
137926 memcpy(pNode->block.a, aBlock, nBlock);
137927 pNode->block.n = nBlock;
137929 sqlite3_free(aBlock);
137932 nodeReaderRelease(&reader);
137936 rc2 = sqlite3_reset(pSelect);
137937 if( rc==SQLITE_OK ) rc = rc2;
137940 return rc;
137944 ** Determine the largest segment index value that exists within absolute
137945 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
137946 ** one before returning SQLITE_OK. Or, if there are no segments at all
137947 ** within level iAbsLevel, set *piIdx to zero.
137949 ** If an error occurs, return an SQLite error code. The final value of
137950 ** *piIdx is undefined in this case.
137952 static int fts3IncrmergeOutputIdx(
137953 Fts3Table *p, /* FTS Table handle */
137954 sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
137955 int *piIdx /* OUT: Next free index at iAbsLevel+1 */
137957 int rc;
137958 sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
137960 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
137961 if( rc==SQLITE_OK ){
137962 sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
137963 sqlite3_step(pOutputIdx);
137964 *piIdx = sqlite3_column_int(pOutputIdx, 0);
137965 rc = sqlite3_reset(pOutputIdx);
137968 return rc;
137972 ** Allocate an appendable output segment on absolute level iAbsLevel+1
137973 ** with idx value iIdx.
137975 ** In the %_segdir table, a segment is defined by the values in three
137976 ** columns:
137978 ** start_block
137979 ** leaves_end_block
137980 ** end_block
137982 ** When an appendable segment is allocated, it is estimated that the
137983 ** maximum number of leaf blocks that may be required is the sum of the
137984 ** number of leaf blocks consumed by the input segments, plus the number
137985 ** of input segments, multiplied by two. This value is stored in stack
137986 ** variable nLeafEst.
137988 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
137989 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
137990 ** array of leaf nodes starts at the first block allocated. The array
137991 ** of interior nodes that are parents of the leaf nodes start at block
137992 ** (start_block + (1 + end_block - start_block) / 16). And so on.
137994 ** In the actual code below, the value "16" is replaced with the
137995 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
137997 static int fts3IncrmergeWriter(
137998 Fts3Table *p, /* Fts3 table handle */
137999 sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
138000 int iIdx, /* Index of new output segment */
138001 Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
138002 IncrmergeWriter *pWriter /* Populate this object */
138004 int rc; /* Return Code */
138005 int i; /* Iterator variable */
138006 int nLeafEst = 0; /* Blocks allocated for leaf nodes */
138007 sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
138008 sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
138010 /* Calculate nLeafEst. */
138011 rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
138012 if( rc==SQLITE_OK ){
138013 sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
138014 sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
138015 if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
138016 nLeafEst = sqlite3_column_int(pLeafEst, 0);
138018 rc = sqlite3_reset(pLeafEst);
138020 if( rc!=SQLITE_OK ) return rc;
138022 /* Calculate the first block to use in the output segment */
138023 rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
138024 if( rc==SQLITE_OK ){
138025 if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
138026 pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
138027 pWriter->iEnd = pWriter->iStart - 1;
138028 pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
138030 rc = sqlite3_reset(pFirstBlock);
138032 if( rc!=SQLITE_OK ) return rc;
138034 /* Insert the marker in the %_segments table to make sure nobody tries
138035 ** to steal the space just allocated. This is also used to identify
138036 ** appendable segments. */
138037 rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
138038 if( rc!=SQLITE_OK ) return rc;
138040 pWriter->iAbsLevel = iAbsLevel;
138041 pWriter->nLeafEst = nLeafEst;
138042 pWriter->iIdx = iIdx;
138044 /* Set up the array of NodeWriter objects */
138045 for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
138046 pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
138048 return SQLITE_OK;
138052 ** Remove an entry from the %_segdir table. This involves running the
138053 ** following two statements:
138055 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
138056 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
138058 ** The DELETE statement removes the specific %_segdir level. The UPDATE
138059 ** statement ensures that the remaining segments have contiguously allocated
138060 ** idx values.
138062 static int fts3RemoveSegdirEntry(
138063 Fts3Table *p, /* FTS3 table handle */
138064 sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
138065 int iIdx /* Index of %_segdir entry to delete */
138067 int rc; /* Return code */
138068 sqlite3_stmt *pDelete = 0; /* DELETE statement */
138070 rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
138071 if( rc==SQLITE_OK ){
138072 sqlite3_bind_int64(pDelete, 1, iAbsLevel);
138073 sqlite3_bind_int(pDelete, 2, iIdx);
138074 sqlite3_step(pDelete);
138075 rc = sqlite3_reset(pDelete);
138078 return rc;
138082 ** One or more segments have just been removed from absolute level iAbsLevel.
138083 ** Update the 'idx' values of the remaining segments in the level so that
138084 ** the idx values are a contiguous sequence starting from 0.
138086 static int fts3RepackSegdirLevel(
138087 Fts3Table *p, /* FTS3 table handle */
138088 sqlite3_int64 iAbsLevel /* Absolute level to repack */
138090 int rc; /* Return code */
138091 int *aIdx = 0; /* Array of remaining idx values */
138092 int nIdx = 0; /* Valid entries in aIdx[] */
138093 int nAlloc = 0; /* Allocated size of aIdx[] */
138094 int i; /* Iterator variable */
138095 sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
138096 sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
138098 rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
138099 if( rc==SQLITE_OK ){
138100 int rc2;
138101 sqlite3_bind_int64(pSelect, 1, iAbsLevel);
138102 while( SQLITE_ROW==sqlite3_step(pSelect) ){
138103 if( nIdx>=nAlloc ){
138104 int *aNew;
138105 nAlloc += 16;
138106 aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
138107 if( !aNew ){
138108 rc = SQLITE_NOMEM;
138109 break;
138111 aIdx = aNew;
138113 aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
138115 rc2 = sqlite3_reset(pSelect);
138116 if( rc==SQLITE_OK ) rc = rc2;
138119 if( rc==SQLITE_OK ){
138120 rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
138122 if( rc==SQLITE_OK ){
138123 sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
138126 assert( p->bIgnoreSavepoint==0 );
138127 p->bIgnoreSavepoint = 1;
138128 for(i=0; rc==SQLITE_OK && i<nIdx; i++){
138129 if( aIdx[i]!=i ){
138130 sqlite3_bind_int(pUpdate, 3, aIdx[i]);
138131 sqlite3_bind_int(pUpdate, 1, i);
138132 sqlite3_step(pUpdate);
138133 rc = sqlite3_reset(pUpdate);
138136 p->bIgnoreSavepoint = 0;
138138 sqlite3_free(aIdx);
138139 return rc;
138142 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
138143 pNode->a[0] = (char)iHeight;
138144 if( iChild ){
138145 assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
138146 pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
138147 }else{
138148 assert( pNode->nAlloc>=1 );
138149 pNode->n = 1;
138154 ** The first two arguments are a pointer to and the size of a segment b-tree
138155 ** node. The node may be a leaf or an internal node.
138157 ** This function creates a new node image in blob object *pNew by copying
138158 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
138159 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
138161 static int fts3TruncateNode(
138162 const char *aNode, /* Current node image */
138163 int nNode, /* Size of aNode in bytes */
138164 Blob *pNew, /* OUT: Write new node image here */
138165 const char *zTerm, /* Omit all terms smaller than this */
138166 int nTerm, /* Size of zTerm in bytes */
138167 sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
138169 NodeReader reader; /* Reader object */
138170 Blob prev = {0, 0, 0}; /* Previous term written to new node */
138171 int rc = SQLITE_OK; /* Return code */
138172 int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
138174 /* Allocate required output space */
138175 blobGrowBuffer(pNew, nNode, &rc);
138176 if( rc!=SQLITE_OK ) return rc;
138177 pNew->n = 0;
138179 /* Populate new node buffer */
138180 for(rc = nodeReaderInit(&reader, aNode, nNode);
138181 rc==SQLITE_OK && reader.aNode;
138182 rc = nodeReaderNext(&reader)
138184 if( pNew->n==0 ){
138185 int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
138186 if( res<0 || (bLeaf==0 && res==0) ) continue;
138187 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
138188 *piBlock = reader.iChild;
138190 rc = fts3AppendToNode(
138191 pNew, &prev, reader.term.a, reader.term.n,
138192 reader.aDoclist, reader.nDoclist
138194 if( rc!=SQLITE_OK ) break;
138196 if( pNew->n==0 ){
138197 fts3StartNode(pNew, (int)aNode[0], reader.iChild);
138198 *piBlock = reader.iChild;
138200 assert( pNew->n<=pNew->nAlloc );
138202 nodeReaderRelease(&reader);
138203 sqlite3_free(prev.a);
138204 return rc;
138208 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
138209 ** level iAbsLevel. This may involve deleting entries from the %_segments
138210 ** table, and modifying existing entries in both the %_segments and %_segdir
138211 ** tables.
138213 ** SQLITE_OK is returned if the segment is updated successfully. Or an
138214 ** SQLite error code otherwise.
138216 static int fts3TruncateSegment(
138217 Fts3Table *p, /* FTS3 table handle */
138218 sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
138219 int iIdx, /* Index within level of segment to modify */
138220 const char *zTerm, /* Remove terms smaller than this */
138221 int nTerm /* Number of bytes in buffer zTerm */
138223 int rc = SQLITE_OK; /* Return code */
138224 Blob root = {0,0,0}; /* New root page image */
138225 Blob block = {0,0,0}; /* Buffer used for any other block */
138226 sqlite3_int64 iBlock = 0; /* Block id */
138227 sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
138228 sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
138229 sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
138231 rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
138232 if( rc==SQLITE_OK ){
138233 int rc2; /* sqlite3_reset() return code */
138234 sqlite3_bind_int64(pFetch, 1, iAbsLevel);
138235 sqlite3_bind_int(pFetch, 2, iIdx);
138236 if( SQLITE_ROW==sqlite3_step(pFetch) ){
138237 const char *aRoot = sqlite3_column_blob(pFetch, 4);
138238 int nRoot = sqlite3_column_bytes(pFetch, 4);
138239 iOldStart = sqlite3_column_int64(pFetch, 1);
138240 rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
138242 rc2 = sqlite3_reset(pFetch);
138243 if( rc==SQLITE_OK ) rc = rc2;
138246 while( rc==SQLITE_OK && iBlock ){
138247 char *aBlock = 0;
138248 int nBlock = 0;
138249 iNewStart = iBlock;
138251 rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
138252 if( rc==SQLITE_OK ){
138253 rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
138255 if( rc==SQLITE_OK ){
138256 rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
138258 sqlite3_free(aBlock);
138261 /* Variable iNewStart now contains the first valid leaf node. */
138262 if( rc==SQLITE_OK && iNewStart ){
138263 sqlite3_stmt *pDel = 0;
138264 rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
138265 if( rc==SQLITE_OK ){
138266 sqlite3_bind_int64(pDel, 1, iOldStart);
138267 sqlite3_bind_int64(pDel, 2, iNewStart-1);
138268 sqlite3_step(pDel);
138269 rc = sqlite3_reset(pDel);
138273 if( rc==SQLITE_OK ){
138274 sqlite3_stmt *pChomp = 0;
138275 rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
138276 if( rc==SQLITE_OK ){
138277 sqlite3_bind_int64(pChomp, 1, iNewStart);
138278 sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
138279 sqlite3_bind_int64(pChomp, 3, iAbsLevel);
138280 sqlite3_bind_int(pChomp, 4, iIdx);
138281 sqlite3_step(pChomp);
138282 rc = sqlite3_reset(pChomp);
138286 sqlite3_free(root.a);
138287 sqlite3_free(block.a);
138288 return rc;
138292 ** This function is called after an incrmental-merge operation has run to
138293 ** merge (or partially merge) two or more segments from absolute level
138294 ** iAbsLevel.
138296 ** Each input segment is either removed from the db completely (if all of
138297 ** its data was copied to the output segment by the incrmerge operation)
138298 ** or modified in place so that it no longer contains those entries that
138299 ** have been duplicated in the output segment.
138301 static int fts3IncrmergeChomp(
138302 Fts3Table *p, /* FTS table handle */
138303 sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
138304 Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
138305 int *pnRem /* Number of segments not deleted */
138307 int i;
138308 int nRem = 0;
138309 int rc = SQLITE_OK;
138311 for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
138312 Fts3SegReader *pSeg = 0;
138313 int j;
138315 /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
138316 ** somewhere in the pCsr->apSegment[] array. */
138317 for(j=0; ALWAYS(j<pCsr->nSegment); j++){
138318 pSeg = pCsr->apSegment[j];
138319 if( pSeg->iIdx==i ) break;
138321 assert( j<pCsr->nSegment && pSeg->iIdx==i );
138323 if( pSeg->aNode==0 ){
138324 /* Seg-reader is at EOF. Remove the entire input segment. */
138325 rc = fts3DeleteSegment(p, pSeg);
138326 if( rc==SQLITE_OK ){
138327 rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
138329 *pnRem = 0;
138330 }else{
138331 /* The incremental merge did not copy all the data from this
138332 ** segment to the upper level. The segment is modified in place
138333 ** so that it contains no keys smaller than zTerm/nTerm. */
138334 const char *zTerm = pSeg->zTerm;
138335 int nTerm = pSeg->nTerm;
138336 rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
138337 nRem++;
138341 if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
138342 rc = fts3RepackSegdirLevel(p, iAbsLevel);
138345 *pnRem = nRem;
138346 return rc;
138350 ** Store an incr-merge hint in the database.
138352 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
138353 sqlite3_stmt *pReplace = 0;
138354 int rc; /* Return code */
138356 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
138357 if( rc==SQLITE_OK ){
138358 sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
138359 sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
138360 sqlite3_step(pReplace);
138361 rc = sqlite3_reset(pReplace);
138364 return rc;
138368 ** Load an incr-merge hint from the database. The incr-merge hint, if one
138369 ** exists, is stored in the rowid==1 row of the %_stat table.
138371 ** If successful, populate blob *pHint with the value read from the %_stat
138372 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
138373 ** SQLite error code.
138375 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
138376 sqlite3_stmt *pSelect = 0;
138377 int rc;
138379 pHint->n = 0;
138380 rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
138381 if( rc==SQLITE_OK ){
138382 int rc2;
138383 sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
138384 if( SQLITE_ROW==sqlite3_step(pSelect) ){
138385 const char *aHint = sqlite3_column_blob(pSelect, 0);
138386 int nHint = sqlite3_column_bytes(pSelect, 0);
138387 if( aHint ){
138388 blobGrowBuffer(pHint, nHint, &rc);
138389 if( rc==SQLITE_OK ){
138390 memcpy(pHint->a, aHint, nHint);
138391 pHint->n = nHint;
138395 rc2 = sqlite3_reset(pSelect);
138396 if( rc==SQLITE_OK ) rc = rc2;
138399 return rc;
138403 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
138404 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
138405 ** consists of two varints, the absolute level number of the input segments
138406 ** and the number of input segments.
138408 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
138409 ** set *pRc to an SQLite error code before returning.
138411 static void fts3IncrmergeHintPush(
138412 Blob *pHint, /* Hint blob to append to */
138413 i64 iAbsLevel, /* First varint to store in hint */
138414 int nInput, /* Second varint to store in hint */
138415 int *pRc /* IN/OUT: Error code */
138417 blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
138418 if( *pRc==SQLITE_OK ){
138419 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
138420 pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
138425 ** Read the last entry (most recently pushed) from the hint blob *pHint
138426 ** and then remove the entry. Write the two values read to *piAbsLevel and
138427 ** *pnInput before returning.
138429 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
138430 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
138432 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
138433 const int nHint = pHint->n;
138434 int i;
138436 i = pHint->n-2;
138437 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
138438 while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
138440 pHint->n = i;
138441 i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
138442 i += fts3GetVarint32(&pHint->a[i], pnInput);
138443 if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
138445 return SQLITE_OK;
138450 ** Attempt an incremental merge that writes nMerge leaf blocks.
138452 ** Incremental merges happen nMin segments at a time. The two
138453 ** segments to be merged are the nMin oldest segments (the ones with
138454 ** the smallest indexes) in the highest level that contains at least
138455 ** nMin segments. Multiple merges might occur in an attempt to write the
138456 ** quota of nMerge leaf blocks.
138458 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
138459 int rc; /* Return code */
138460 int nRem = nMerge; /* Number of leaf pages yet to be written */
138461 Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
138462 Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
138463 IncrmergeWriter *pWriter; /* Writer object */
138464 int nSeg = 0; /* Number of input segments */
138465 sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
138466 Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
138467 int bDirtyHint = 0; /* True if blob 'hint' has been modified */
138469 /* Allocate space for the cursor, filter and writer objects */
138470 const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
138471 pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
138472 if( !pWriter ) return SQLITE_NOMEM;
138473 pFilter = (Fts3SegFilter *)&pWriter[1];
138474 pCsr = (Fts3MultiSegReader *)&pFilter[1];
138476 rc = fts3IncrmergeHintLoad(p, &hint);
138477 while( rc==SQLITE_OK && nRem>0 ){
138478 const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
138479 sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
138480 int bUseHint = 0; /* True if attempting to append */
138482 /* Search the %_segdir table for the absolute level with the smallest
138483 ** relative level number that contains at least nMin segments, if any.
138484 ** If one is found, set iAbsLevel to the absolute level number and
138485 ** nSeg to nMin. If no level with at least nMin segments can be found,
138486 ** set nSeg to -1.
138488 rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
138489 sqlite3_bind_int(pFindLevel, 1, nMin);
138490 if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
138491 iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
138492 nSeg = nMin;
138493 }else{
138494 nSeg = -1;
138496 rc = sqlite3_reset(pFindLevel);
138498 /* If the hint read from the %_stat table is not empty, check if the
138499 ** last entry in it specifies a relative level smaller than or equal
138500 ** to the level identified by the block above (if any). If so, this
138501 ** iteration of the loop will work on merging at the hinted level.
138503 if( rc==SQLITE_OK && hint.n ){
138504 int nHint = hint.n;
138505 sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
138506 int nHintSeg = 0; /* Hint number of segments */
138508 rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
138509 if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
138510 iAbsLevel = iHintAbsLevel;
138511 nSeg = nHintSeg;
138512 bUseHint = 1;
138513 bDirtyHint = 1;
138514 }else{
138515 /* This undoes the effect of the HintPop() above - so that no entry
138516 ** is removed from the hint blob. */
138517 hint.n = nHint;
138521 /* If nSeg is less that zero, then there is no level with at least
138522 ** nMin segments and no hint in the %_stat table. No work to do.
138523 ** Exit early in this case. */
138524 if( nSeg<0 ) break;
138526 /* Open a cursor to iterate through the contents of the oldest nSeg
138527 ** indexes of absolute level iAbsLevel. If this cursor is opened using
138528 ** the 'hint' parameters, it is possible that there are less than nSeg
138529 ** segments available in level iAbsLevel. In this case, no work is
138530 ** done on iAbsLevel - fall through to the next iteration of the loop
138531 ** to start work on some other level. */
138532 memset(pWriter, 0, nAlloc);
138533 pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
138534 if( rc==SQLITE_OK ){
138535 rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
138537 if( SQLITE_OK==rc && pCsr->nSegment==nSeg
138538 && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
138539 && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
138541 int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
138542 rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
138543 if( rc==SQLITE_OK ){
138544 if( bUseHint && iIdx>0 ){
138545 const char *zKey = pCsr->zTerm;
138546 int nKey = pCsr->nTerm;
138547 rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
138548 }else{
138549 rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
138553 if( rc==SQLITE_OK && pWriter->nLeafEst ){
138554 fts3LogMerge(nSeg, iAbsLevel);
138556 rc = fts3IncrmergeAppend(p, pWriter, pCsr);
138557 if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
138558 if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
138559 }while( rc==SQLITE_ROW );
138561 /* Update or delete the input segments */
138562 if( rc==SQLITE_OK ){
138563 nRem -= (1 + pWriter->nWork);
138564 rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
138565 if( nSeg!=0 ){
138566 bDirtyHint = 1;
138567 fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
138572 fts3IncrmergeRelease(p, pWriter, &rc);
138575 sqlite3Fts3SegReaderFinish(pCsr);
138578 /* Write the hint values into the %_stat table for the next incr-merger */
138579 if( bDirtyHint && rc==SQLITE_OK ){
138580 rc = fts3IncrmergeHintStore(p, &hint);
138583 sqlite3_free(pWriter);
138584 sqlite3_free(hint.a);
138585 return rc;
138589 ** Convert the text beginning at *pz into an integer and return
138590 ** its value. Advance *pz to point to the first character past
138591 ** the integer.
138593 static int fts3Getint(const char **pz){
138594 const char *z = *pz;
138595 int i = 0;
138596 while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
138597 *pz = z;
138598 return i;
138602 ** Process statements of the form:
138604 ** INSERT INTO table(table) VALUES('merge=A,B');
138606 ** A and B are integers that decode to be the number of leaf pages
138607 ** written for the merge, and the minimum number of segments on a level
138608 ** before it will be selected for a merge, respectively.
138610 static int fts3DoIncrmerge(
138611 Fts3Table *p, /* FTS3 table handle */
138612 const char *zParam /* Nul-terminated string containing "A,B" */
138614 int rc;
138615 int nMin = (FTS3_MERGE_COUNT / 2);
138616 int nMerge = 0;
138617 const char *z = zParam;
138619 /* Read the first integer value */
138620 nMerge = fts3Getint(&z);
138622 /* If the first integer value is followed by a ',', read the second
138623 ** integer value. */
138624 if( z[0]==',' && z[1]!='\0' ){
138626 nMin = fts3Getint(&z);
138629 if( z[0]!='\0' || nMin<2 ){
138630 rc = SQLITE_ERROR;
138631 }else{
138632 rc = SQLITE_OK;
138633 if( !p->bHasStat ){
138634 assert( p->bFts4==0 );
138635 sqlite3Fts3CreateStatTable(&rc, p);
138637 if( rc==SQLITE_OK ){
138638 rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
138640 sqlite3Fts3SegmentsClose(p);
138642 return rc;
138646 ** Process statements of the form:
138648 ** INSERT INTO table(table) VALUES('automerge=X');
138650 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
138651 ** turn it on. The setting is persistent.
138653 static int fts3DoAutoincrmerge(
138654 Fts3Table *p, /* FTS3 table handle */
138655 const char *zParam /* Nul-terminated string containing boolean */
138657 int rc = SQLITE_OK;
138658 sqlite3_stmt *pStmt = 0;
138659 p->bAutoincrmerge = fts3Getint(&zParam)!=0;
138660 if( !p->bHasStat ){
138661 assert( p->bFts4==0 );
138662 sqlite3Fts3CreateStatTable(&rc, p);
138663 if( rc ) return rc;
138665 rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
138666 if( rc ) return rc;
138667 sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
138668 sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
138669 sqlite3_step(pStmt);
138670 rc = sqlite3_reset(pStmt);
138671 return rc;
138675 ** Return a 64-bit checksum for the FTS index entry specified by the
138676 ** arguments to this function.
138678 static u64 fts3ChecksumEntry(
138679 const char *zTerm, /* Pointer to buffer containing term */
138680 int nTerm, /* Size of zTerm in bytes */
138681 int iLangid, /* Language id for current row */
138682 int iIndex, /* Index (0..Fts3Table.nIndex-1) */
138683 i64 iDocid, /* Docid for current row. */
138684 int iCol, /* Column number */
138685 int iPos /* Position */
138687 int i;
138688 u64 ret = (u64)iDocid;
138690 ret += (ret<<3) + iLangid;
138691 ret += (ret<<3) + iIndex;
138692 ret += (ret<<3) + iCol;
138693 ret += (ret<<3) + iPos;
138694 for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
138696 return ret;
138700 ** Return a checksum of all entries in the FTS index that correspond to
138701 ** language id iLangid. The checksum is calculated by XORing the checksums
138702 ** of each individual entry (see fts3ChecksumEntry()) together.
138704 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
138705 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
138706 ** return value is undefined in this case.
138708 static u64 fts3ChecksumIndex(
138709 Fts3Table *p, /* FTS3 table handle */
138710 int iLangid, /* Language id to return cksum for */
138711 int iIndex, /* Index to cksum (0..p->nIndex-1) */
138712 int *pRc /* OUT: Return code */
138714 Fts3SegFilter filter;
138715 Fts3MultiSegReader csr;
138716 int rc;
138717 u64 cksum = 0;
138719 assert( *pRc==SQLITE_OK );
138721 memset(&filter, 0, sizeof(filter));
138722 memset(&csr, 0, sizeof(csr));
138723 filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
138724 filter.flags |= FTS3_SEGMENT_SCAN;
138726 rc = sqlite3Fts3SegReaderCursor(
138727 p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
138729 if( rc==SQLITE_OK ){
138730 rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
138733 if( rc==SQLITE_OK ){
138734 while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
138735 char *pCsr = csr.aDoclist;
138736 char *pEnd = &pCsr[csr.nDoclist];
138738 i64 iDocid = 0;
138739 i64 iCol = 0;
138740 i64 iPos = 0;
138742 pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
138743 while( pCsr<pEnd ){
138744 i64 iVal = 0;
138745 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
138746 if( pCsr<pEnd ){
138747 if( iVal==0 || iVal==1 ){
138748 iCol = 0;
138749 iPos = 0;
138750 if( iVal ){
138751 pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
138752 }else{
138753 pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
138754 iDocid += iVal;
138756 }else{
138757 iPos += (iVal - 2);
138758 cksum = cksum ^ fts3ChecksumEntry(
138759 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
138760 (int)iCol, (int)iPos
138767 sqlite3Fts3SegReaderFinish(&csr);
138769 *pRc = rc;
138770 return cksum;
138774 ** Check if the contents of the FTS index match the current contents of the
138775 ** content table. If no error occurs and the contents do match, set *pbOk
138776 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
138777 ** to false before returning.
138779 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
138780 ** code. The final value of *pbOk is undefined in this case.
138782 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
138783 int rc = SQLITE_OK; /* Return code */
138784 u64 cksum1 = 0; /* Checksum based on FTS index contents */
138785 u64 cksum2 = 0; /* Checksum based on %_content contents */
138786 sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
138788 /* This block calculates the checksum according to the FTS index. */
138789 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
138790 if( rc==SQLITE_OK ){
138791 int rc2;
138792 sqlite3_bind_int(pAllLangid, 1, p->nIndex);
138793 while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
138794 int iLangid = sqlite3_column_int(pAllLangid, 0);
138795 int i;
138796 for(i=0; i<p->nIndex; i++){
138797 cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
138800 rc2 = sqlite3_reset(pAllLangid);
138801 if( rc==SQLITE_OK ) rc = rc2;
138804 /* This block calculates the checksum according to the %_content table */
138805 rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
138806 if( rc==SQLITE_OK ){
138807 sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
138808 sqlite3_stmt *pStmt = 0;
138809 char *zSql;
138811 zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
138812 if( !zSql ){
138813 rc = SQLITE_NOMEM;
138814 }else{
138815 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
138816 sqlite3_free(zSql);
138819 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
138820 i64 iDocid = sqlite3_column_int64(pStmt, 0);
138821 int iLang = langidFromSelect(p, pStmt);
138822 int iCol;
138824 for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
138825 const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
138826 int nText = sqlite3_column_bytes(pStmt, iCol+1);
138827 sqlite3_tokenizer_cursor *pT = 0;
138829 rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
138830 while( rc==SQLITE_OK ){
138831 char const *zToken; /* Buffer containing token */
138832 int nToken = 0; /* Number of bytes in token */
138833 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
138834 int iPos = 0; /* Position of token in zText */
138836 rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
138837 if( rc==SQLITE_OK ){
138838 int i;
138839 cksum2 = cksum2 ^ fts3ChecksumEntry(
138840 zToken, nToken, iLang, 0, iDocid, iCol, iPos
138842 for(i=1; i<p->nIndex; i++){
138843 if( p->aIndex[i].nPrefix<=nToken ){
138844 cksum2 = cksum2 ^ fts3ChecksumEntry(
138845 zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
138851 if( pT ) pModule->xClose(pT);
138852 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
138856 sqlite3_finalize(pStmt);
138859 *pbOk = (cksum1==cksum2);
138860 return rc;
138864 ** Run the integrity-check. If no error occurs and the current contents of
138865 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
138866 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
138868 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
138869 ** error code.
138871 ** The integrity-check works as follows. For each token and indexed token
138872 ** prefix in the document set, a 64-bit checksum is calculated (by code
138873 ** in fts3ChecksumEntry()) based on the following:
138875 ** + The index number (0 for the main index, 1 for the first prefix
138876 ** index etc.),
138877 ** + The token (or token prefix) text itself,
138878 ** + The language-id of the row it appears in,
138879 ** + The docid of the row it appears in,
138880 ** + The column it appears in, and
138881 ** + The tokens position within that column.
138883 ** The checksums for all entries in the index are XORed together to create
138884 ** a single checksum for the entire index.
138886 ** The integrity-check code calculates the same checksum in two ways:
138888 ** 1. By scanning the contents of the FTS index, and
138889 ** 2. By scanning and tokenizing the content table.
138891 ** If the two checksums are identical, the integrity-check is deemed to have
138892 ** passed.
138894 static int fts3DoIntegrityCheck(
138895 Fts3Table *p /* FTS3 table handle */
138897 int rc;
138898 int bOk = 0;
138899 rc = fts3IntegrityCheck(p, &bOk);
138900 if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
138901 return rc;
138905 ** Handle a 'special' INSERT of the form:
138907 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
138909 ** Argument pVal contains the result of <expr>. Currently the only
138910 ** meaningful value to insert is the text 'optimize'.
138912 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
138913 int rc; /* Return Code */
138914 const char *zVal = (const char *)sqlite3_value_text(pVal);
138915 int nVal = sqlite3_value_bytes(pVal);
138917 if( !zVal ){
138918 return SQLITE_NOMEM;
138919 }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
138920 rc = fts3DoOptimize(p, 0);
138921 }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
138922 rc = fts3DoRebuild(p);
138923 }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
138924 rc = fts3DoIntegrityCheck(p);
138925 }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
138926 rc = fts3DoIncrmerge(p, &zVal[6]);
138927 }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
138928 rc = fts3DoAutoincrmerge(p, &zVal[10]);
138929 #ifdef SQLITE_TEST
138930 }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
138931 p->nNodeSize = atoi(&zVal[9]);
138932 rc = SQLITE_OK;
138933 }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
138934 p->nMaxPendingData = atoi(&zVal[11]);
138935 rc = SQLITE_OK;
138936 }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
138937 p->bNoIncrDoclist = atoi(&zVal[21]);
138938 rc = SQLITE_OK;
138939 #endif
138940 }else{
138941 rc = SQLITE_ERROR;
138944 return rc;
138947 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
138949 ** Delete all cached deferred doclists. Deferred doclists are cached
138950 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
138952 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
138953 Fts3DeferredToken *pDef;
138954 for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
138955 fts3PendingListDelete(pDef->pList);
138956 pDef->pList = 0;
138961 ** Free all entries in the pCsr->pDeffered list. Entries are added to
138962 ** this list using sqlite3Fts3DeferToken().
138964 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
138965 Fts3DeferredToken *pDef;
138966 Fts3DeferredToken *pNext;
138967 for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
138968 pNext = pDef->pNext;
138969 fts3PendingListDelete(pDef->pList);
138970 sqlite3_free(pDef);
138972 pCsr->pDeferred = 0;
138976 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
138977 ** based on the row that pCsr currently points to.
138979 ** A deferred-doclist is like any other doclist with position information
138980 ** included, except that it only contains entries for a single row of the
138981 ** table, not for all rows.
138983 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
138984 int rc = SQLITE_OK; /* Return code */
138985 if( pCsr->pDeferred ){
138986 int i; /* Used to iterate through table columns */
138987 sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
138988 Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
138990 Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
138991 sqlite3_tokenizer *pT = p->pTokenizer;
138992 sqlite3_tokenizer_module const *pModule = pT->pModule;
138994 assert( pCsr->isRequireSeek==0 );
138995 iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
138997 for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
138998 if( p->abNotindexed[i]==0 ){
138999 const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
139000 sqlite3_tokenizer_cursor *pTC = 0;
139002 rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
139003 while( rc==SQLITE_OK ){
139004 char const *zToken; /* Buffer containing token */
139005 int nToken = 0; /* Number of bytes in token */
139006 int iDum1 = 0, iDum2 = 0; /* Dummy variables */
139007 int iPos = 0; /* Position of token in zText */
139009 rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
139010 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
139011 Fts3PhraseToken *pPT = pDef->pToken;
139012 if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
139013 && (pPT->bFirst==0 || iPos==0)
139014 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
139015 && (0==memcmp(zToken, pPT->z, pPT->n))
139017 fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
139021 if( pTC ) pModule->xClose(pTC);
139022 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
139026 for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
139027 if( pDef->pList ){
139028 rc = fts3PendingListAppendVarint(&pDef->pList, 0);
139033 return rc;
139036 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
139037 Fts3DeferredToken *p,
139038 char **ppData,
139039 int *pnData
139041 char *pRet;
139042 int nSkip;
139043 sqlite3_int64 dummy;
139045 *ppData = 0;
139046 *pnData = 0;
139048 if( p->pList==0 ){
139049 return SQLITE_OK;
139052 pRet = (char *)sqlite3_malloc(p->pList->nData);
139053 if( !pRet ) return SQLITE_NOMEM;
139055 nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
139056 *pnData = p->pList->nData - nSkip;
139057 *ppData = pRet;
139059 memcpy(pRet, &p->pList->aData[nSkip], *pnData);
139060 return SQLITE_OK;
139064 ** Add an entry for token pToken to the pCsr->pDeferred list.
139066 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
139067 Fts3Cursor *pCsr, /* Fts3 table cursor */
139068 Fts3PhraseToken *pToken, /* Token to defer */
139069 int iCol /* Column that token must appear in (or -1) */
139071 Fts3DeferredToken *pDeferred;
139072 pDeferred = sqlite3_malloc(sizeof(*pDeferred));
139073 if( !pDeferred ){
139074 return SQLITE_NOMEM;
139076 memset(pDeferred, 0, sizeof(*pDeferred));
139077 pDeferred->pToken = pToken;
139078 pDeferred->pNext = pCsr->pDeferred;
139079 pDeferred->iCol = iCol;
139080 pCsr->pDeferred = pDeferred;
139082 assert( pToken->pDeferred==0 );
139083 pToken->pDeferred = pDeferred;
139085 return SQLITE_OK;
139087 #endif
139090 ** SQLite value pRowid contains the rowid of a row that may or may not be
139091 ** present in the FTS3 table. If it is, delete it and adjust the contents
139092 ** of subsiduary data structures accordingly.
139094 static int fts3DeleteByRowid(
139095 Fts3Table *p,
139096 sqlite3_value *pRowid,
139097 int *pnChng, /* IN/OUT: Decrement if row is deleted */
139098 u32 *aSzDel
139100 int rc = SQLITE_OK; /* Return code */
139101 int bFound = 0; /* True if *pRowid really is in the table */
139103 fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
139104 if( bFound && rc==SQLITE_OK ){
139105 int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
139106 rc = fts3IsEmpty(p, pRowid, &isEmpty);
139107 if( rc==SQLITE_OK ){
139108 if( isEmpty ){
139109 /* Deleting this row means the whole table is empty. In this case
139110 ** delete the contents of all three tables and throw away any
139111 ** data in the pendingTerms hash table. */
139112 rc = fts3DeleteAll(p, 1);
139113 *pnChng = 0;
139114 memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
139115 }else{
139116 *pnChng = *pnChng - 1;
139117 if( p->zContentTbl==0 ){
139118 fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
139120 if( p->bHasDocsize ){
139121 fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
139127 return rc;
139131 ** This function does the work for the xUpdate method of FTS3 virtual
139132 ** tables. The schema of the virtual table being:
139134 ** CREATE TABLE <table name>(
139135 ** <user columns>,
139136 ** <table name> HIDDEN,
139137 ** docid HIDDEN,
139138 ** <langid> HIDDEN
139139 ** );
139143 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
139144 sqlite3_vtab *pVtab, /* FTS3 vtab object */
139145 int nArg, /* Size of argument array */
139146 sqlite3_value **apVal, /* Array of arguments */
139147 sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
139149 Fts3Table *p = (Fts3Table *)pVtab;
139150 int rc = SQLITE_OK; /* Return Code */
139151 int isRemove = 0; /* True for an UPDATE or DELETE */
139152 u32 *aSzIns = 0; /* Sizes of inserted documents */
139153 u32 *aSzDel = 0; /* Sizes of deleted documents */
139154 int nChng = 0; /* Net change in number of documents */
139155 int bInsertDone = 0;
139157 assert( p->pSegments==0 );
139158 assert(
139159 nArg==1 /* DELETE operations */
139160 || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
139163 /* Check for a "special" INSERT operation. One of the form:
139165 ** INSERT INTO xyz(xyz) VALUES('command');
139167 if( nArg>1
139168 && sqlite3_value_type(apVal[0])==SQLITE_NULL
139169 && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
139171 rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
139172 goto update_out;
139175 if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
139176 rc = SQLITE_CONSTRAINT;
139177 goto update_out;
139180 /* Allocate space to hold the change in document sizes */
139181 aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
139182 if( aSzDel==0 ){
139183 rc = SQLITE_NOMEM;
139184 goto update_out;
139186 aSzIns = &aSzDel[p->nColumn+1];
139187 memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
139189 rc = fts3Writelock(p);
139190 if( rc!=SQLITE_OK ) goto update_out;
139192 /* If this is an INSERT operation, or an UPDATE that modifies the rowid
139193 ** value, then this operation requires constraint handling.
139195 ** If the on-conflict mode is REPLACE, this means that the existing row
139196 ** should be deleted from the database before inserting the new row. Or,
139197 ** if the on-conflict mode is other than REPLACE, then this method must
139198 ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
139199 ** modify the database file.
139201 if( nArg>1 && p->zContentTbl==0 ){
139202 /* Find the value object that holds the new rowid value. */
139203 sqlite3_value *pNewRowid = apVal[3+p->nColumn];
139204 if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
139205 pNewRowid = apVal[1];
139208 if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
139209 sqlite3_value_type(apVal[0])==SQLITE_NULL
139210 || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
139212 /* The new rowid is not NULL (in this case the rowid will be
139213 ** automatically assigned and there is no chance of a conflict), and
139214 ** the statement is either an INSERT or an UPDATE that modifies the
139215 ** rowid column. So if the conflict mode is REPLACE, then delete any
139216 ** existing row with rowid=pNewRowid.
139218 ** Or, if the conflict mode is not REPLACE, insert the new record into
139219 ** the %_content table. If we hit the duplicate rowid constraint (or any
139220 ** other error) while doing so, return immediately.
139222 ** This branch may also run if pNewRowid contains a value that cannot
139223 ** be losslessly converted to an integer. In this case, the eventual
139224 ** call to fts3InsertData() (either just below or further on in this
139225 ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
139226 ** invoked, it will delete zero rows (since no row will have
139227 ** docid=$pNewRowid if $pNewRowid is not an integer value).
139229 if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
139230 rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
139231 }else{
139232 rc = fts3InsertData(p, apVal, pRowid);
139233 bInsertDone = 1;
139237 if( rc!=SQLITE_OK ){
139238 goto update_out;
139241 /* If this is a DELETE or UPDATE operation, remove the old record. */
139242 if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
139243 assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
139244 rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
139245 isRemove = 1;
139248 /* If this is an INSERT or UPDATE operation, insert the new record. */
139249 if( nArg>1 && rc==SQLITE_OK ){
139250 int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
139251 if( bInsertDone==0 ){
139252 rc = fts3InsertData(p, apVal, pRowid);
139253 if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
139254 rc = FTS_CORRUPT_VTAB;
139257 if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
139258 rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
139260 if( rc==SQLITE_OK ){
139261 assert( p->iPrevDocid==*pRowid );
139262 rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
139264 if( p->bHasDocsize ){
139265 fts3InsertDocsize(&rc, p, aSzIns);
139267 nChng++;
139270 if( p->bFts4 ){
139271 fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
139274 update_out:
139275 sqlite3_free(aSzDel);
139276 sqlite3Fts3SegmentsClose(p);
139277 return rc;
139281 ** Flush any data in the pending-terms hash table to disk. If successful,
139282 ** merge all segments in the database (including the new segment, if
139283 ** there was any data to flush) into a single segment.
139285 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
139286 int rc;
139287 rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
139288 if( rc==SQLITE_OK ){
139289 rc = fts3DoOptimize(p, 1);
139290 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
139291 int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
139292 if( rc2!=SQLITE_OK ) rc = rc2;
139293 }else{
139294 sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
139295 sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
139298 sqlite3Fts3SegmentsClose(p);
139299 return rc;
139302 #endif
139304 /************** End of fts3_write.c ******************************************/
139305 /************** Begin file fts3_snippet.c ************************************/
139307 ** 2009 Oct 23
139309 ** The author disclaims copyright to this source code. In place of
139310 ** a legal notice, here is a blessing:
139312 ** May you do good and not evil.
139313 ** May you find forgiveness for yourself and forgive others.
139314 ** May you share freely, never taking more than you give.
139316 ******************************************************************************
139319 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
139321 /* #include <string.h> */
139322 /* #include <assert.h> */
139325 ** Characters that may appear in the second argument to matchinfo().
139327 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
139328 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
139329 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
139330 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
139331 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
139332 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
139333 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
139336 ** The default value for the second argument to matchinfo().
139338 #define FTS3_MATCHINFO_DEFAULT "pcx"
139342 ** Used as an fts3ExprIterate() context when loading phrase doclists to
139343 ** Fts3Expr.aDoclist[]/nDoclist.
139345 typedef struct LoadDoclistCtx LoadDoclistCtx;
139346 struct LoadDoclistCtx {
139347 Fts3Cursor *pCsr; /* FTS3 Cursor */
139348 int nPhrase; /* Number of phrases seen so far */
139349 int nToken; /* Number of tokens seen so far */
139353 ** The following types are used as part of the implementation of the
139354 ** fts3BestSnippet() routine.
139356 typedef struct SnippetIter SnippetIter;
139357 typedef struct SnippetPhrase SnippetPhrase;
139358 typedef struct SnippetFragment SnippetFragment;
139360 struct SnippetIter {
139361 Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
139362 int iCol; /* Extract snippet from this column */
139363 int nSnippet; /* Requested snippet length (in tokens) */
139364 int nPhrase; /* Number of phrases in query */
139365 SnippetPhrase *aPhrase; /* Array of size nPhrase */
139366 int iCurrent; /* First token of current snippet */
139369 struct SnippetPhrase {
139370 int nToken; /* Number of tokens in phrase */
139371 char *pList; /* Pointer to start of phrase position list */
139372 int iHead; /* Next value in position list */
139373 char *pHead; /* Position list data following iHead */
139374 int iTail; /* Next value in trailing position list */
139375 char *pTail; /* Position list data following iTail */
139378 struct SnippetFragment {
139379 int iCol; /* Column snippet is extracted from */
139380 int iPos; /* Index of first token in snippet */
139381 u64 covered; /* Mask of query phrases covered */
139382 u64 hlmask; /* Mask of snippet terms to highlight */
139386 ** This type is used as an fts3ExprIterate() context object while
139387 ** accumulating the data returned by the matchinfo() function.
139389 typedef struct MatchInfo MatchInfo;
139390 struct MatchInfo {
139391 Fts3Cursor *pCursor; /* FTS3 Cursor */
139392 int nCol; /* Number of columns in table */
139393 int nPhrase; /* Number of matchable phrases in query */
139394 sqlite3_int64 nDoc; /* Number of docs in database */
139395 u32 *aMatchinfo; /* Pre-allocated buffer */
139401 ** The snippet() and offsets() functions both return text values. An instance
139402 ** of the following structure is used to accumulate those values while the
139403 ** functions are running. See fts3StringAppend() for details.
139405 typedef struct StrBuffer StrBuffer;
139406 struct StrBuffer {
139407 char *z; /* Pointer to buffer containing string */
139408 int n; /* Length of z in bytes (excl. nul-term) */
139409 int nAlloc; /* Allocated size of buffer z in bytes */
139414 ** This function is used to help iterate through a position-list. A position
139415 ** list is a list of unique integers, sorted from smallest to largest. Each
139416 ** element of the list is represented by an FTS3 varint that takes the value
139417 ** of the difference between the current element and the previous one plus
139418 ** two. For example, to store the position-list:
139420 ** 4 9 113
139422 ** the three varints:
139424 ** 6 7 106
139426 ** are encoded.
139428 ** When this function is called, *pp points to the start of an element of
139429 ** the list. *piPos contains the value of the previous entry in the list.
139430 ** After it returns, *piPos contains the value of the next element of the
139431 ** list and *pp is advanced to the following varint.
139433 static void fts3GetDeltaPosition(char **pp, int *piPos){
139434 int iVal;
139435 *pp += fts3GetVarint32(*pp, &iVal);
139436 *piPos += (iVal-2);
139440 ** Helper function for fts3ExprIterate() (see below).
139442 static int fts3ExprIterate2(
139443 Fts3Expr *pExpr, /* Expression to iterate phrases of */
139444 int *piPhrase, /* Pointer to phrase counter */
139445 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
139446 void *pCtx /* Second argument to pass to callback */
139448 int rc; /* Return code */
139449 int eType = pExpr->eType; /* Type of expression node pExpr */
139451 if( eType!=FTSQUERY_PHRASE ){
139452 assert( pExpr->pLeft && pExpr->pRight );
139453 rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
139454 if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
139455 rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
139457 }else{
139458 rc = x(pExpr, *piPhrase, pCtx);
139459 (*piPhrase)++;
139461 return rc;
139465 ** Iterate through all phrase nodes in an FTS3 query, except those that
139466 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
139467 ** For each phrase node found, the supplied callback function is invoked.
139469 ** If the callback function returns anything other than SQLITE_OK,
139470 ** the iteration is abandoned and the error code returned immediately.
139471 ** Otherwise, SQLITE_OK is returned after a callback has been made for
139472 ** all eligible phrase nodes.
139474 static int fts3ExprIterate(
139475 Fts3Expr *pExpr, /* Expression to iterate phrases of */
139476 int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
139477 void *pCtx /* Second argument to pass to callback */
139479 int iPhrase = 0; /* Variable used as the phrase counter */
139480 return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
139484 ** This is an fts3ExprIterate() callback used while loading the doclists
139485 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
139486 ** fts3ExprLoadDoclists().
139488 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
139489 int rc = SQLITE_OK;
139490 Fts3Phrase *pPhrase = pExpr->pPhrase;
139491 LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
139493 UNUSED_PARAMETER(iPhrase);
139495 p->nPhrase++;
139496 p->nToken += pPhrase->nToken;
139498 return rc;
139502 ** Load the doclists for each phrase in the query associated with FTS3 cursor
139503 ** pCsr.
139505 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
139506 ** phrases in the expression (all phrases except those directly or
139507 ** indirectly descended from the right-hand-side of a NOT operator). If
139508 ** pnToken is not NULL, then it is set to the number of tokens in all
139509 ** matchable phrases of the expression.
139511 static int fts3ExprLoadDoclists(
139512 Fts3Cursor *pCsr, /* Fts3 cursor for current query */
139513 int *pnPhrase, /* OUT: Number of phrases in query */
139514 int *pnToken /* OUT: Number of tokens in query */
139516 int rc; /* Return Code */
139517 LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
139518 sCtx.pCsr = pCsr;
139519 rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
139520 if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
139521 if( pnToken ) *pnToken = sCtx.nToken;
139522 return rc;
139525 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
139526 (*(int *)ctx)++;
139527 UNUSED_PARAMETER(pExpr);
139528 UNUSED_PARAMETER(iPhrase);
139529 return SQLITE_OK;
139531 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
139532 int nPhrase = 0;
139533 (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
139534 return nPhrase;
139538 ** Advance the position list iterator specified by the first two
139539 ** arguments so that it points to the first element with a value greater
139540 ** than or equal to parameter iNext.
139542 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
139543 char *pIter = *ppIter;
139544 if( pIter ){
139545 int iIter = *piIter;
139547 while( iIter<iNext ){
139548 if( 0==(*pIter & 0xFE) ){
139549 iIter = -1;
139550 pIter = 0;
139551 break;
139553 fts3GetDeltaPosition(&pIter, &iIter);
139556 *piIter = iIter;
139557 *ppIter = pIter;
139562 ** Advance the snippet iterator to the next candidate snippet.
139564 static int fts3SnippetNextCandidate(SnippetIter *pIter){
139565 int i; /* Loop counter */
139567 if( pIter->iCurrent<0 ){
139568 /* The SnippetIter object has just been initialized. The first snippet
139569 ** candidate always starts at offset 0 (even if this candidate has a
139570 ** score of 0.0).
139572 pIter->iCurrent = 0;
139574 /* Advance the 'head' iterator of each phrase to the first offset that
139575 ** is greater than or equal to (iNext+nSnippet).
139577 for(i=0; i<pIter->nPhrase; i++){
139578 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
139579 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
139581 }else{
139582 int iStart;
139583 int iEnd = 0x7FFFFFFF;
139585 for(i=0; i<pIter->nPhrase; i++){
139586 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
139587 if( pPhrase->pHead && pPhrase->iHead<iEnd ){
139588 iEnd = pPhrase->iHead;
139591 if( iEnd==0x7FFFFFFF ){
139592 return 1;
139595 pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
139596 for(i=0; i<pIter->nPhrase; i++){
139597 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
139598 fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
139599 fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
139603 return 0;
139607 ** Retrieve information about the current candidate snippet of snippet
139608 ** iterator pIter.
139610 static void fts3SnippetDetails(
139611 SnippetIter *pIter, /* Snippet iterator */
139612 u64 mCovered, /* Bitmask of phrases already covered */
139613 int *piToken, /* OUT: First token of proposed snippet */
139614 int *piScore, /* OUT: "Score" for this snippet */
139615 u64 *pmCover, /* OUT: Bitmask of phrases covered */
139616 u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
139618 int iStart = pIter->iCurrent; /* First token of snippet */
139619 int iScore = 0; /* Score of this snippet */
139620 int i; /* Loop counter */
139621 u64 mCover = 0; /* Mask of phrases covered by this snippet */
139622 u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
139624 for(i=0; i<pIter->nPhrase; i++){
139625 SnippetPhrase *pPhrase = &pIter->aPhrase[i];
139626 if( pPhrase->pTail ){
139627 char *pCsr = pPhrase->pTail;
139628 int iCsr = pPhrase->iTail;
139630 while( iCsr<(iStart+pIter->nSnippet) ){
139631 int j;
139632 u64 mPhrase = (u64)1 << i;
139633 u64 mPos = (u64)1 << (iCsr - iStart);
139634 assert( iCsr>=iStart );
139635 if( (mCover|mCovered)&mPhrase ){
139636 iScore++;
139637 }else{
139638 iScore += 1000;
139640 mCover |= mPhrase;
139642 for(j=0; j<pPhrase->nToken; j++){
139643 mHighlight |= (mPos>>j);
139646 if( 0==(*pCsr & 0x0FE) ) break;
139647 fts3GetDeltaPosition(&pCsr, &iCsr);
139652 /* Set the output variables before returning. */
139653 *piToken = iStart;
139654 *piScore = iScore;
139655 *pmCover = mCover;
139656 *pmHighlight = mHighlight;
139660 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
139661 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
139663 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
139664 SnippetIter *p = (SnippetIter *)ctx;
139665 SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
139666 char *pCsr;
139667 int rc;
139669 pPhrase->nToken = pExpr->pPhrase->nToken;
139670 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
139671 assert( rc==SQLITE_OK || pCsr==0 );
139672 if( pCsr ){
139673 int iFirst = 0;
139674 pPhrase->pList = pCsr;
139675 fts3GetDeltaPosition(&pCsr, &iFirst);
139676 assert( iFirst>=0 );
139677 pPhrase->pHead = pCsr;
139678 pPhrase->pTail = pCsr;
139679 pPhrase->iHead = iFirst;
139680 pPhrase->iTail = iFirst;
139681 }else{
139682 assert( rc!=SQLITE_OK || (
139683 pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
139687 return rc;
139691 ** Select the fragment of text consisting of nFragment contiguous tokens
139692 ** from column iCol that represent the "best" snippet. The best snippet
139693 ** is the snippet with the highest score, where scores are calculated
139694 ** by adding:
139696 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
139698 ** (b) +1000 points for the first occurrence of each matchable phrase in
139699 ** the snippet for which the corresponding mCovered bit is not set.
139701 ** The selected snippet parameters are stored in structure *pFragment before
139702 ** returning. The score of the selected snippet is stored in *piScore
139703 ** before returning.
139705 static int fts3BestSnippet(
139706 int nSnippet, /* Desired snippet length */
139707 Fts3Cursor *pCsr, /* Cursor to create snippet for */
139708 int iCol, /* Index of column to create snippet from */
139709 u64 mCovered, /* Mask of phrases already covered */
139710 u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
139711 SnippetFragment *pFragment, /* OUT: Best snippet found */
139712 int *piScore /* OUT: Score of snippet pFragment */
139714 int rc; /* Return Code */
139715 int nList; /* Number of phrases in expression */
139716 SnippetIter sIter; /* Iterates through snippet candidates */
139717 int nByte; /* Number of bytes of space to allocate */
139718 int iBestScore = -1; /* Best snippet score found so far */
139719 int i; /* Loop counter */
139721 memset(&sIter, 0, sizeof(sIter));
139723 /* Iterate through the phrases in the expression to count them. The same
139724 ** callback makes sure the doclists are loaded for each phrase.
139726 rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
139727 if( rc!=SQLITE_OK ){
139728 return rc;
139731 /* Now that it is known how many phrases there are, allocate and zero
139732 ** the required space using malloc().
139734 nByte = sizeof(SnippetPhrase) * nList;
139735 sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
139736 if( !sIter.aPhrase ){
139737 return SQLITE_NOMEM;
139739 memset(sIter.aPhrase, 0, nByte);
139741 /* Initialize the contents of the SnippetIter object. Then iterate through
139742 ** the set of phrases in the expression to populate the aPhrase[] array.
139744 sIter.pCsr = pCsr;
139745 sIter.iCol = iCol;
139746 sIter.nSnippet = nSnippet;
139747 sIter.nPhrase = nList;
139748 sIter.iCurrent = -1;
139749 (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
139751 /* Set the *pmSeen output variable. */
139752 for(i=0; i<nList; i++){
139753 if( sIter.aPhrase[i].pHead ){
139754 *pmSeen |= (u64)1 << i;
139758 /* Loop through all candidate snippets. Store the best snippet in
139759 ** *pFragment. Store its associated 'score' in iBestScore.
139761 pFragment->iCol = iCol;
139762 while( !fts3SnippetNextCandidate(&sIter) ){
139763 int iPos;
139764 int iScore;
139765 u64 mCover;
139766 u64 mHighlight;
139767 fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
139768 assert( iScore>=0 );
139769 if( iScore>iBestScore ){
139770 pFragment->iPos = iPos;
139771 pFragment->hlmask = mHighlight;
139772 pFragment->covered = mCover;
139773 iBestScore = iScore;
139777 sqlite3_free(sIter.aPhrase);
139778 *piScore = iBestScore;
139779 return SQLITE_OK;
139784 ** Append a string to the string-buffer passed as the first argument.
139786 ** If nAppend is negative, then the length of the string zAppend is
139787 ** determined using strlen().
139789 static int fts3StringAppend(
139790 StrBuffer *pStr, /* Buffer to append to */
139791 const char *zAppend, /* Pointer to data to append to buffer */
139792 int nAppend /* Size of zAppend in bytes (or -1) */
139794 if( nAppend<0 ){
139795 nAppend = (int)strlen(zAppend);
139798 /* If there is insufficient space allocated at StrBuffer.z, use realloc()
139799 ** to grow the buffer until so that it is big enough to accomadate the
139800 ** appended data.
139802 if( pStr->n+nAppend+1>=pStr->nAlloc ){
139803 int nAlloc = pStr->nAlloc+nAppend+100;
139804 char *zNew = sqlite3_realloc(pStr->z, nAlloc);
139805 if( !zNew ){
139806 return SQLITE_NOMEM;
139808 pStr->z = zNew;
139809 pStr->nAlloc = nAlloc;
139811 assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
139813 /* Append the data to the string buffer. */
139814 memcpy(&pStr->z[pStr->n], zAppend, nAppend);
139815 pStr->n += nAppend;
139816 pStr->z[pStr->n] = '\0';
139818 return SQLITE_OK;
139822 ** The fts3BestSnippet() function often selects snippets that end with a
139823 ** query term. That is, the final term of the snippet is always a term
139824 ** that requires highlighting. For example, if 'X' is a highlighted term
139825 ** and '.' is a non-highlighted term, BestSnippet() may select:
139827 ** ........X.....X
139829 ** This function "shifts" the beginning of the snippet forward in the
139830 ** document so that there are approximately the same number of
139831 ** non-highlighted terms to the right of the final highlighted term as there
139832 ** are to the left of the first highlighted term. For example, to this:
139834 ** ....X.....X....
139836 ** This is done as part of extracting the snippet text, not when selecting
139837 ** the snippet. Snippet selection is done based on doclists only, so there
139838 ** is no way for fts3BestSnippet() to know whether or not the document
139839 ** actually contains terms that follow the final highlighted term.
139841 static int fts3SnippetShift(
139842 Fts3Table *pTab, /* FTS3 table snippet comes from */
139843 int iLangid, /* Language id to use in tokenizing */
139844 int nSnippet, /* Number of tokens desired for snippet */
139845 const char *zDoc, /* Document text to extract snippet from */
139846 int nDoc, /* Size of buffer zDoc in bytes */
139847 int *piPos, /* IN/OUT: First token of snippet */
139848 u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
139850 u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
139852 if( hlmask ){
139853 int nLeft; /* Tokens to the left of first highlight */
139854 int nRight; /* Tokens to the right of last highlight */
139855 int nDesired; /* Ideal number of tokens to shift forward */
139857 for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
139858 for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
139859 nDesired = (nLeft-nRight)/2;
139861 /* Ideally, the start of the snippet should be pushed forward in the
139862 ** document nDesired tokens. This block checks if there are actually
139863 ** nDesired tokens to the right of the snippet. If so, *piPos and
139864 ** *pHlMask are updated to shift the snippet nDesired tokens to the
139865 ** right. Otherwise, the snippet is shifted by the number of tokens
139866 ** available.
139868 if( nDesired>0 ){
139869 int nShift; /* Number of tokens to shift snippet by */
139870 int iCurrent = 0; /* Token counter */
139871 int rc; /* Return Code */
139872 sqlite3_tokenizer_module *pMod;
139873 sqlite3_tokenizer_cursor *pC;
139874 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
139876 /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
139877 ** or more tokens in zDoc/nDoc.
139879 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
139880 if( rc!=SQLITE_OK ){
139881 return rc;
139883 while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
139884 const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
139885 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
139887 pMod->xClose(pC);
139888 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
139890 nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
139891 assert( nShift<=nDesired );
139892 if( nShift>0 ){
139893 *piPos += nShift;
139894 *pHlmask = hlmask >> nShift;
139898 return SQLITE_OK;
139902 ** Extract the snippet text for fragment pFragment from cursor pCsr and
139903 ** append it to string buffer pOut.
139905 static int fts3SnippetText(
139906 Fts3Cursor *pCsr, /* FTS3 Cursor */
139907 SnippetFragment *pFragment, /* Snippet to extract */
139908 int iFragment, /* Fragment number */
139909 int isLast, /* True for final fragment in snippet */
139910 int nSnippet, /* Number of tokens in extracted snippet */
139911 const char *zOpen, /* String inserted before highlighted term */
139912 const char *zClose, /* String inserted after highlighted term */
139913 const char *zEllipsis, /* String inserted between snippets */
139914 StrBuffer *pOut /* Write output here */
139916 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
139917 int rc; /* Return code */
139918 const char *zDoc; /* Document text to extract snippet from */
139919 int nDoc; /* Size of zDoc in bytes */
139920 int iCurrent = 0; /* Current token number of document */
139921 int iEnd = 0; /* Byte offset of end of current token */
139922 int isShiftDone = 0; /* True after snippet is shifted */
139923 int iPos = pFragment->iPos; /* First token of snippet */
139924 u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
139925 int iCol = pFragment->iCol+1; /* Query column to extract text from */
139926 sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
139927 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
139929 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
139930 if( zDoc==0 ){
139931 if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
139932 return SQLITE_NOMEM;
139934 return SQLITE_OK;
139936 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
139938 /* Open a token cursor on the document. */
139939 pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
139940 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
139941 if( rc!=SQLITE_OK ){
139942 return rc;
139945 while( rc==SQLITE_OK ){
139946 const char *ZDUMMY; /* Dummy argument used with tokenizer */
139947 int DUMMY1 = -1; /* Dummy argument used with tokenizer */
139948 int iBegin = 0; /* Offset in zDoc of start of token */
139949 int iFin = 0; /* Offset in zDoc of end of token */
139950 int isHighlight = 0; /* True for highlighted terms */
139952 /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
139953 ** in the FTS code the variable that the third argument to xNext points to
139954 ** is initialized to zero before the first (*but not necessarily
139955 ** subsequent*) call to xNext(). This is done for a particular application
139956 ** that needs to know whether or not the tokenizer is being used for
139957 ** snippet generation or for some other purpose.
139959 ** Extreme care is required when writing code to depend on this
139960 ** initialization. It is not a documented part of the tokenizer interface.
139961 ** If a tokenizer is used directly by any code outside of FTS, this
139962 ** convention might not be respected. */
139963 rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
139964 if( rc!=SQLITE_OK ){
139965 if( rc==SQLITE_DONE ){
139966 /* Special case - the last token of the snippet is also the last token
139967 ** of the column. Append any punctuation that occurred between the end
139968 ** of the previous token and the end of the document to the output.
139969 ** Then break out of the loop. */
139970 rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
139972 break;
139974 if( iCurrent<iPos ){ continue; }
139976 if( !isShiftDone ){
139977 int n = nDoc - iBegin;
139978 rc = fts3SnippetShift(
139979 pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
139981 isShiftDone = 1;
139983 /* Now that the shift has been done, check if the initial "..." are
139984 ** required. They are required if (a) this is not the first fragment,
139985 ** or (b) this fragment does not begin at position 0 of its column.
139987 if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
139988 rc = fts3StringAppend(pOut, zEllipsis, -1);
139990 if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
139993 if( iCurrent>=(iPos+nSnippet) ){
139994 if( isLast ){
139995 rc = fts3StringAppend(pOut, zEllipsis, -1);
139997 break;
140000 /* Set isHighlight to true if this term should be highlighted. */
140001 isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
140003 if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
140004 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
140005 if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
140006 if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
140008 iEnd = iFin;
140011 pMod->xClose(pC);
140012 return rc;
140017 ** This function is used to count the entries in a column-list (a
140018 ** delta-encoded list of term offsets within a single column of a single
140019 ** row). When this function is called, *ppCollist should point to the
140020 ** beginning of the first varint in the column-list (the varint that
140021 ** contains the position of the first matching term in the column data).
140022 ** Before returning, *ppCollist is set to point to the first byte after
140023 ** the last varint in the column-list (either the 0x00 signifying the end
140024 ** of the position-list, or the 0x01 that precedes the column number of
140025 ** the next column in the position-list).
140027 ** The number of elements in the column-list is returned.
140029 static int fts3ColumnlistCount(char **ppCollist){
140030 char *pEnd = *ppCollist;
140031 char c = 0;
140032 int nEntry = 0;
140034 /* A column-list is terminated by either a 0x01 or 0x00. */
140035 while( 0xFE & (*pEnd | c) ){
140036 c = *pEnd++ & 0x80;
140037 if( !c ) nEntry++;
140040 *ppCollist = pEnd;
140041 return nEntry;
140045 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
140046 ** for a single query.
140048 ** fts3ExprIterate() callback to load the 'global' elements of a
140049 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
140050 ** of the matchinfo array that are constant for all rows returned by the
140051 ** current query.
140053 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
140054 ** function populates Matchinfo.aMatchinfo[] as follows:
140056 ** for(iCol=0; iCol<nCol; iCol++){
140057 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
140058 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
140061 ** where X is the number of matches for phrase iPhrase is column iCol of all
140062 ** rows of the table. Y is the number of rows for which column iCol contains
140063 ** at least one instance of phrase iPhrase.
140065 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
140066 ** Y values are set to nDoc, where nDoc is the number of documents in the
140067 ** file system. This is done because the full-text index doclist is required
140068 ** to calculate these values properly, and the full-text index doclist is
140069 ** not available for deferred tokens.
140071 static int fts3ExprGlobalHitsCb(
140072 Fts3Expr *pExpr, /* Phrase expression node */
140073 int iPhrase, /* Phrase number (numbered from zero) */
140074 void *pCtx /* Pointer to MatchInfo structure */
140076 MatchInfo *p = (MatchInfo *)pCtx;
140077 return sqlite3Fts3EvalPhraseStats(
140078 p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
140083 ** fts3ExprIterate() callback used to collect the "local" part of the
140084 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
140085 ** array that are different for each row returned by the query.
140087 static int fts3ExprLocalHitsCb(
140088 Fts3Expr *pExpr, /* Phrase expression node */
140089 int iPhrase, /* Phrase number */
140090 void *pCtx /* Pointer to MatchInfo structure */
140092 int rc = SQLITE_OK;
140093 MatchInfo *p = (MatchInfo *)pCtx;
140094 int iStart = iPhrase * p->nCol * 3;
140095 int i;
140097 for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
140098 char *pCsr;
140099 rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
140100 if( pCsr ){
140101 p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
140102 }else{
140103 p->aMatchinfo[iStart+i*3] = 0;
140107 return rc;
140110 static int fts3MatchinfoCheck(
140111 Fts3Table *pTab,
140112 char cArg,
140113 char **pzErr
140115 if( (cArg==FTS3_MATCHINFO_NPHRASE)
140116 || (cArg==FTS3_MATCHINFO_NCOL)
140117 || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
140118 || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
140119 || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
140120 || (cArg==FTS3_MATCHINFO_LCS)
140121 || (cArg==FTS3_MATCHINFO_HITS)
140123 return SQLITE_OK;
140125 *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
140126 return SQLITE_ERROR;
140129 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
140130 int nVal; /* Number of integers output by cArg */
140132 switch( cArg ){
140133 case FTS3_MATCHINFO_NDOC:
140134 case FTS3_MATCHINFO_NPHRASE:
140135 case FTS3_MATCHINFO_NCOL:
140136 nVal = 1;
140137 break;
140139 case FTS3_MATCHINFO_AVGLENGTH:
140140 case FTS3_MATCHINFO_LENGTH:
140141 case FTS3_MATCHINFO_LCS:
140142 nVal = pInfo->nCol;
140143 break;
140145 default:
140146 assert( cArg==FTS3_MATCHINFO_HITS );
140147 nVal = pInfo->nCol * pInfo->nPhrase * 3;
140148 break;
140151 return nVal;
140154 static int fts3MatchinfoSelectDoctotal(
140155 Fts3Table *pTab,
140156 sqlite3_stmt **ppStmt,
140157 sqlite3_int64 *pnDoc,
140158 const char **paLen
140160 sqlite3_stmt *pStmt;
140161 const char *a;
140162 sqlite3_int64 nDoc;
140164 if( !*ppStmt ){
140165 int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
140166 if( rc!=SQLITE_OK ) return rc;
140168 pStmt = *ppStmt;
140169 assert( sqlite3_data_count(pStmt)==1 );
140171 a = sqlite3_column_blob(pStmt, 0);
140172 a += sqlite3Fts3GetVarint(a, &nDoc);
140173 if( nDoc==0 ) return FTS_CORRUPT_VTAB;
140174 *pnDoc = (u32)nDoc;
140176 if( paLen ) *paLen = a;
140177 return SQLITE_OK;
140181 ** An instance of the following structure is used to store state while
140182 ** iterating through a multi-column position-list corresponding to the
140183 ** hits for a single phrase on a single row in order to calculate the
140184 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
140186 typedef struct LcsIterator LcsIterator;
140187 struct LcsIterator {
140188 Fts3Expr *pExpr; /* Pointer to phrase expression */
140189 int iPosOffset; /* Tokens count up to end of this phrase */
140190 char *pRead; /* Cursor used to iterate through aDoclist */
140191 int iPos; /* Current position */
140195 ** If LcsIterator.iCol is set to the following value, the iterator has
140196 ** finished iterating through all offsets for all columns.
140198 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
140200 static int fts3MatchinfoLcsCb(
140201 Fts3Expr *pExpr, /* Phrase expression node */
140202 int iPhrase, /* Phrase number (numbered from zero) */
140203 void *pCtx /* Pointer to MatchInfo structure */
140205 LcsIterator *aIter = (LcsIterator *)pCtx;
140206 aIter[iPhrase].pExpr = pExpr;
140207 return SQLITE_OK;
140211 ** Advance the iterator passed as an argument to the next position. Return
140212 ** 1 if the iterator is at EOF or if it now points to the start of the
140213 ** position list for the next column.
140215 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
140216 char *pRead = pIter->pRead;
140217 sqlite3_int64 iRead;
140218 int rc = 0;
140220 pRead += sqlite3Fts3GetVarint(pRead, &iRead);
140221 if( iRead==0 || iRead==1 ){
140222 pRead = 0;
140223 rc = 1;
140224 }else{
140225 pIter->iPos += (int)(iRead-2);
140228 pIter->pRead = pRead;
140229 return rc;
140233 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
140235 ** If the call is successful, the longest-common-substring lengths for each
140236 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
140237 ** array before returning. SQLITE_OK is returned in this case.
140239 ** Otherwise, if an error occurs, an SQLite error code is returned and the
140240 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
140241 ** undefined.
140243 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
140244 LcsIterator *aIter;
140245 int i;
140246 int iCol;
140247 int nToken = 0;
140249 /* Allocate and populate the array of LcsIterator objects. The array
140250 ** contains one element for each matchable phrase in the query.
140252 aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
140253 if( !aIter ) return SQLITE_NOMEM;
140254 memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
140255 (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
140257 for(i=0; i<pInfo->nPhrase; i++){
140258 LcsIterator *pIter = &aIter[i];
140259 nToken -= pIter->pExpr->pPhrase->nToken;
140260 pIter->iPosOffset = nToken;
140263 for(iCol=0; iCol<pInfo->nCol; iCol++){
140264 int nLcs = 0; /* LCS value for this column */
140265 int nLive = 0; /* Number of iterators in aIter not at EOF */
140267 for(i=0; i<pInfo->nPhrase; i++){
140268 int rc;
140269 LcsIterator *pIt = &aIter[i];
140270 rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
140271 if( rc!=SQLITE_OK ) return rc;
140272 if( pIt->pRead ){
140273 pIt->iPos = pIt->iPosOffset;
140274 fts3LcsIteratorAdvance(&aIter[i]);
140275 nLive++;
140279 while( nLive>0 ){
140280 LcsIterator *pAdv = 0; /* The iterator to advance by one position */
140281 int nThisLcs = 0; /* LCS for the current iterator positions */
140283 for(i=0; i<pInfo->nPhrase; i++){
140284 LcsIterator *pIter = &aIter[i];
140285 if( pIter->pRead==0 ){
140286 /* This iterator is already at EOF for this column. */
140287 nThisLcs = 0;
140288 }else{
140289 if( pAdv==0 || pIter->iPos<pAdv->iPos ){
140290 pAdv = pIter;
140292 if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
140293 nThisLcs++;
140294 }else{
140295 nThisLcs = 1;
140297 if( nThisLcs>nLcs ) nLcs = nThisLcs;
140300 if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
140303 pInfo->aMatchinfo[iCol] = nLcs;
140306 sqlite3_free(aIter);
140307 return SQLITE_OK;
140311 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
140312 ** be returned by the matchinfo() function. Argument zArg contains the
140313 ** format string passed as the second argument to matchinfo (or the
140314 ** default value "pcx" if no second argument was specified). The format
140315 ** string has already been validated and the pInfo->aMatchinfo[] array
140316 ** is guaranteed to be large enough for the output.
140318 ** If bGlobal is true, then populate all fields of the matchinfo() output.
140319 ** If it is false, then assume that those fields that do not change between
140320 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
140321 ** have already been populated.
140323 ** Return SQLITE_OK if successful, or an SQLite error code if an error
140324 ** occurs. If a value other than SQLITE_OK is returned, the state the
140325 ** pInfo->aMatchinfo[] buffer is left in is undefined.
140327 static int fts3MatchinfoValues(
140328 Fts3Cursor *pCsr, /* FTS3 cursor object */
140329 int bGlobal, /* True to grab the global stats */
140330 MatchInfo *pInfo, /* Matchinfo context object */
140331 const char *zArg /* Matchinfo format string */
140333 int rc = SQLITE_OK;
140334 int i;
140335 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140336 sqlite3_stmt *pSelect = 0;
140338 for(i=0; rc==SQLITE_OK && zArg[i]; i++){
140340 switch( zArg[i] ){
140341 case FTS3_MATCHINFO_NPHRASE:
140342 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
140343 break;
140345 case FTS3_MATCHINFO_NCOL:
140346 if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
140347 break;
140349 case FTS3_MATCHINFO_NDOC:
140350 if( bGlobal ){
140351 sqlite3_int64 nDoc = 0;
140352 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
140353 pInfo->aMatchinfo[0] = (u32)nDoc;
140355 break;
140357 case FTS3_MATCHINFO_AVGLENGTH:
140358 if( bGlobal ){
140359 sqlite3_int64 nDoc; /* Number of rows in table */
140360 const char *a; /* Aggregate column length array */
140362 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
140363 if( rc==SQLITE_OK ){
140364 int iCol;
140365 for(iCol=0; iCol<pInfo->nCol; iCol++){
140366 u32 iVal;
140367 sqlite3_int64 nToken;
140368 a += sqlite3Fts3GetVarint(a, &nToken);
140369 iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
140370 pInfo->aMatchinfo[iCol] = iVal;
140374 break;
140376 case FTS3_MATCHINFO_LENGTH: {
140377 sqlite3_stmt *pSelectDocsize = 0;
140378 rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
140379 if( rc==SQLITE_OK ){
140380 int iCol;
140381 const char *a = sqlite3_column_blob(pSelectDocsize, 0);
140382 for(iCol=0; iCol<pInfo->nCol; iCol++){
140383 sqlite3_int64 nToken;
140384 a += sqlite3Fts3GetVarint(a, &nToken);
140385 pInfo->aMatchinfo[iCol] = (u32)nToken;
140388 sqlite3_reset(pSelectDocsize);
140389 break;
140392 case FTS3_MATCHINFO_LCS:
140393 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
140394 if( rc==SQLITE_OK ){
140395 rc = fts3MatchinfoLcs(pCsr, pInfo);
140397 break;
140399 default: {
140400 Fts3Expr *pExpr;
140401 assert( zArg[i]==FTS3_MATCHINFO_HITS );
140402 pExpr = pCsr->pExpr;
140403 rc = fts3ExprLoadDoclists(pCsr, 0, 0);
140404 if( rc!=SQLITE_OK ) break;
140405 if( bGlobal ){
140406 if( pCsr->pDeferred ){
140407 rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
140408 if( rc!=SQLITE_OK ) break;
140410 rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
140411 if( rc!=SQLITE_OK ) break;
140413 (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
140414 break;
140418 pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
140421 sqlite3_reset(pSelect);
140422 return rc;
140427 ** Populate pCsr->aMatchinfo[] with data for the current row. The
140428 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
140430 static int fts3GetMatchinfo(
140431 Fts3Cursor *pCsr, /* FTS3 Cursor object */
140432 const char *zArg /* Second argument to matchinfo() function */
140434 MatchInfo sInfo;
140435 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140436 int rc = SQLITE_OK;
140437 int bGlobal = 0; /* Collect 'global' stats as well as local */
140439 memset(&sInfo, 0, sizeof(MatchInfo));
140440 sInfo.pCursor = pCsr;
140441 sInfo.nCol = pTab->nColumn;
140443 /* If there is cached matchinfo() data, but the format string for the
140444 ** cache does not match the format string for this request, discard
140445 ** the cached data. */
140446 if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
140447 assert( pCsr->aMatchinfo );
140448 sqlite3_free(pCsr->aMatchinfo);
140449 pCsr->zMatchinfo = 0;
140450 pCsr->aMatchinfo = 0;
140453 /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
140454 ** matchinfo function has been called for this query. In this case
140455 ** allocate the array used to accumulate the matchinfo data and
140456 ** initialize those elements that are constant for every row.
140458 if( pCsr->aMatchinfo==0 ){
140459 int nMatchinfo = 0; /* Number of u32 elements in match-info */
140460 int nArg; /* Bytes in zArg */
140461 int i; /* Used to iterate through zArg */
140463 /* Determine the number of phrases in the query */
140464 pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
140465 sInfo.nPhrase = pCsr->nPhrase;
140467 /* Determine the number of integers in the buffer returned by this call. */
140468 for(i=0; zArg[i]; i++){
140469 nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
140472 /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
140473 nArg = (int)strlen(zArg);
140474 pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
140475 if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
140477 pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
140478 pCsr->nMatchinfo = nMatchinfo;
140479 memcpy(pCsr->zMatchinfo, zArg, nArg+1);
140480 memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
140481 pCsr->isMatchinfoNeeded = 1;
140482 bGlobal = 1;
140485 sInfo.aMatchinfo = pCsr->aMatchinfo;
140486 sInfo.nPhrase = pCsr->nPhrase;
140487 if( pCsr->isMatchinfoNeeded ){
140488 rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
140489 pCsr->isMatchinfoNeeded = 0;
140492 return rc;
140496 ** Implementation of snippet() function.
140498 SQLITE_PRIVATE void sqlite3Fts3Snippet(
140499 sqlite3_context *pCtx, /* SQLite function call context */
140500 Fts3Cursor *pCsr, /* Cursor object */
140501 const char *zStart, /* Snippet start text - "<b>" */
140502 const char *zEnd, /* Snippet end text - "</b>" */
140503 const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
140504 int iCol, /* Extract snippet from this column */
140505 int nToken /* Approximate number of tokens in snippet */
140507 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140508 int rc = SQLITE_OK;
140509 int i;
140510 StrBuffer res = {0, 0, 0};
140512 /* The returned text includes up to four fragments of text extracted from
140513 ** the data in the current row. The first iteration of the for(...) loop
140514 ** below attempts to locate a single fragment of text nToken tokens in
140515 ** size that contains at least one instance of all phrases in the query
140516 ** expression that appear in the current row. If such a fragment of text
140517 ** cannot be found, the second iteration of the loop attempts to locate
140518 ** a pair of fragments, and so on.
140520 int nSnippet = 0; /* Number of fragments in this snippet */
140521 SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
140522 int nFToken = -1; /* Number of tokens in each fragment */
140524 if( !pCsr->pExpr ){
140525 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
140526 return;
140529 for(nSnippet=1; 1; nSnippet++){
140531 int iSnip; /* Loop counter 0..nSnippet-1 */
140532 u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
140533 u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
140535 if( nToken>=0 ){
140536 nFToken = (nToken+nSnippet-1) / nSnippet;
140537 }else{
140538 nFToken = -1 * nToken;
140541 for(iSnip=0; iSnip<nSnippet; iSnip++){
140542 int iBestScore = -1; /* Best score of columns checked so far */
140543 int iRead; /* Used to iterate through columns */
140544 SnippetFragment *pFragment = &aSnippet[iSnip];
140546 memset(pFragment, 0, sizeof(*pFragment));
140548 /* Loop through all columns of the table being considered for snippets.
140549 ** If the iCol argument to this function was negative, this means all
140550 ** columns of the FTS3 table. Otherwise, only column iCol is considered.
140552 for(iRead=0; iRead<pTab->nColumn; iRead++){
140553 SnippetFragment sF = {0, 0, 0, 0};
140554 int iS;
140555 #if defined(__minix)
140556 iS = 0; /* LSC: Fix -Os compilation: -Werror=maybe-uninitialized */
140557 #endif /* defined(__minix) */
140558 if( iCol>=0 && iRead!=iCol ) continue;
140560 /* Find the best snippet of nFToken tokens in column iRead. */
140561 rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
140562 if( rc!=SQLITE_OK ){
140563 goto snippet_out;
140565 if( iS>iBestScore ){
140566 *pFragment = sF;
140567 iBestScore = iS;
140571 mCovered |= pFragment->covered;
140574 /* If all query phrases seen by fts3BestSnippet() are present in at least
140575 ** one of the nSnippet snippet fragments, break out of the loop.
140577 assert( (mCovered&mSeen)==mCovered );
140578 if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
140581 assert( nFToken>0 );
140583 for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
140584 rc = fts3SnippetText(pCsr, &aSnippet[i],
140585 i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
140589 snippet_out:
140590 sqlite3Fts3SegmentsClose(pTab);
140591 if( rc!=SQLITE_OK ){
140592 sqlite3_result_error_code(pCtx, rc);
140593 sqlite3_free(res.z);
140594 }else{
140595 sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
140600 typedef struct TermOffset TermOffset;
140601 typedef struct TermOffsetCtx TermOffsetCtx;
140603 struct TermOffset {
140604 char *pList; /* Position-list */
140605 int iPos; /* Position just read from pList */
140606 int iOff; /* Offset of this term from read positions */
140609 struct TermOffsetCtx {
140610 Fts3Cursor *pCsr;
140611 int iCol; /* Column of table to populate aTerm for */
140612 int iTerm;
140613 sqlite3_int64 iDocid;
140614 TermOffset *aTerm;
140618 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
140620 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
140621 TermOffsetCtx *p = (TermOffsetCtx *)ctx;
140622 int nTerm; /* Number of tokens in phrase */
140623 int iTerm; /* For looping through nTerm phrase terms */
140624 char *pList; /* Pointer to position list for phrase */
140625 int iPos = 0; /* First position in position-list */
140626 int rc;
140628 UNUSED_PARAMETER(iPhrase);
140629 rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
140630 nTerm = pExpr->pPhrase->nToken;
140631 if( pList ){
140632 fts3GetDeltaPosition(&pList, &iPos);
140633 assert( iPos>=0 );
140636 for(iTerm=0; iTerm<nTerm; iTerm++){
140637 TermOffset *pT = &p->aTerm[p->iTerm++];
140638 pT->iOff = nTerm-iTerm-1;
140639 pT->pList = pList;
140640 pT->iPos = iPos;
140643 return rc;
140647 ** Implementation of offsets() function.
140649 SQLITE_PRIVATE void sqlite3Fts3Offsets(
140650 sqlite3_context *pCtx, /* SQLite function call context */
140651 Fts3Cursor *pCsr /* Cursor object */
140653 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140654 sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
140655 int rc; /* Return Code */
140656 int nToken; /* Number of tokens in query */
140657 int iCol; /* Column currently being processed */
140658 StrBuffer res = {0, 0, 0}; /* Result string */
140659 TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
140661 if( !pCsr->pExpr ){
140662 sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
140663 return;
140666 memset(&sCtx, 0, sizeof(sCtx));
140667 assert( pCsr->isRequireSeek==0 );
140669 /* Count the number of terms in the query */
140670 rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
140671 if( rc!=SQLITE_OK ) goto offsets_out;
140673 /* Allocate the array of TermOffset iterators. */
140674 sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
140675 if( 0==sCtx.aTerm ){
140676 rc = SQLITE_NOMEM;
140677 goto offsets_out;
140679 sCtx.iDocid = pCsr->iPrevId;
140680 sCtx.pCsr = pCsr;
140682 /* Loop through the table columns, appending offset information to
140683 ** string-buffer res for each column.
140685 for(iCol=0; iCol<pTab->nColumn; iCol++){
140686 sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
140687 const char *ZDUMMY; /* Dummy argument used with xNext() */
140688 int NDUMMY = 0; /* Dummy argument used with xNext() */
140689 int iStart = 0;
140690 int iEnd = 0;
140691 int iCurrent = 0;
140692 const char *zDoc;
140693 int nDoc;
140695 /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
140696 ** no way that this operation can fail, so the return code from
140697 ** fts3ExprIterate() can be discarded.
140699 sCtx.iCol = iCol;
140700 sCtx.iTerm = 0;
140701 (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
140703 /* Retreive the text stored in column iCol. If an SQL NULL is stored
140704 ** in column iCol, jump immediately to the next iteration of the loop.
140705 ** If an OOM occurs while retrieving the data (this can happen if SQLite
140706 ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
140707 ** to the caller.
140709 zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
140710 nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
140711 if( zDoc==0 ){
140712 if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
140713 continue;
140715 rc = SQLITE_NOMEM;
140716 goto offsets_out;
140719 /* Initialize a tokenizer iterator to iterate through column iCol. */
140720 rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
140721 zDoc, nDoc, &pC
140723 if( rc!=SQLITE_OK ) goto offsets_out;
140725 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
140726 while( rc==SQLITE_OK ){
140727 int i; /* Used to loop through terms */
140728 int iMinPos = 0x7FFFFFFF; /* Position of next token */
140729 TermOffset *pTerm = 0; /* TermOffset associated with next token */
140731 for(i=0; i<nToken; i++){
140732 TermOffset *pT = &sCtx.aTerm[i];
140733 if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
140734 iMinPos = pT->iPos-pT->iOff;
140735 pTerm = pT;
140739 if( !pTerm ){
140740 /* All offsets for this column have been gathered. */
140741 rc = SQLITE_DONE;
140742 }else{
140743 assert( iCurrent<=iMinPos );
140744 if( 0==(0xFE&*pTerm->pList) ){
140745 pTerm->pList = 0;
140746 }else{
140747 fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
140749 while( rc==SQLITE_OK && iCurrent<iMinPos ){
140750 rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
140752 if( rc==SQLITE_OK ){
140753 char aBuffer[64];
140754 sqlite3_snprintf(sizeof(aBuffer), aBuffer,
140755 "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
140757 rc = fts3StringAppend(&res, aBuffer, -1);
140758 }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
140759 rc = FTS_CORRUPT_VTAB;
140763 if( rc==SQLITE_DONE ){
140764 rc = SQLITE_OK;
140767 pMod->xClose(pC);
140768 if( rc!=SQLITE_OK ) goto offsets_out;
140771 offsets_out:
140772 sqlite3_free(sCtx.aTerm);
140773 assert( rc!=SQLITE_DONE );
140774 sqlite3Fts3SegmentsClose(pTab);
140775 if( rc!=SQLITE_OK ){
140776 sqlite3_result_error_code(pCtx, rc);
140777 sqlite3_free(res.z);
140778 }else{
140779 sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
140781 return;
140785 ** Implementation of matchinfo() function.
140787 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
140788 sqlite3_context *pContext, /* Function call context */
140789 Fts3Cursor *pCsr, /* FTS3 table cursor */
140790 const char *zArg /* Second arg to matchinfo() function */
140792 Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
140793 int rc;
140794 int i;
140795 const char *zFormat;
140797 if( zArg ){
140798 for(i=0; zArg[i]; i++){
140799 char *zErr = 0;
140800 if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
140801 sqlite3_result_error(pContext, zErr, -1);
140802 sqlite3_free(zErr);
140803 return;
140806 zFormat = zArg;
140807 }else{
140808 zFormat = FTS3_MATCHINFO_DEFAULT;
140811 if( !pCsr->pExpr ){
140812 sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
140813 return;
140816 /* Retrieve matchinfo() data. */
140817 rc = fts3GetMatchinfo(pCsr, zFormat);
140818 sqlite3Fts3SegmentsClose(pTab);
140820 if( rc!=SQLITE_OK ){
140821 sqlite3_result_error_code(pContext, rc);
140822 }else{
140823 int n = pCsr->nMatchinfo * sizeof(u32);
140824 sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
140828 #endif
140830 /************** End of fts3_snippet.c ****************************************/
140831 /************** Begin file fts3_unicode.c ************************************/
140833 ** 2012 May 24
140835 ** The author disclaims copyright to this source code. In place of
140836 ** a legal notice, here is a blessing:
140838 ** May you do good and not evil.
140839 ** May you find forgiveness for yourself and forgive others.
140840 ** May you share freely, never taking more than you give.
140842 ******************************************************************************
140844 ** Implementation of the "unicode" full-text-search tokenizer.
140847 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
140849 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140851 /* #include <assert.h> */
140852 /* #include <stdlib.h> */
140853 /* #include <stdio.h> */
140854 /* #include <string.h> */
140858 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
140859 ** from the sqlite3 source file utf.c. If this file is compiled as part
140860 ** of the amalgamation, they are not required.
140862 #ifndef SQLITE_AMALGAMATION
140864 static const unsigned char sqlite3Utf8Trans1[] = {
140865 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
140866 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
140867 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
140868 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
140869 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
140870 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
140871 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
140872 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
140875 #define READ_UTF8(zIn, zTerm, c) \
140876 c = *(zIn++); \
140877 if( c>=0xc0 ){ \
140878 c = sqlite3Utf8Trans1[c-0xc0]; \
140879 while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
140880 c = (c<<6) + (0x3f & *(zIn++)); \
140882 if( c<0x80 \
140883 || (c&0xFFFFF800)==0xD800 \
140884 || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
140887 #define WRITE_UTF8(zOut, c) { \
140888 if( c<0x00080 ){ \
140889 *zOut++ = (u8)(c&0xFF); \
140891 else if( c<0x00800 ){ \
140892 *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
140893 *zOut++ = 0x80 + (u8)(c & 0x3F); \
140895 else if( c<0x10000 ){ \
140896 *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
140897 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
140898 *zOut++ = 0x80 + (u8)(c & 0x3F); \
140899 }else{ \
140900 *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
140901 *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
140902 *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
140903 *zOut++ = 0x80 + (u8)(c & 0x3F); \
140907 #endif /* ifndef SQLITE_AMALGAMATION */
140909 typedef struct unicode_tokenizer unicode_tokenizer;
140910 typedef struct unicode_cursor unicode_cursor;
140912 struct unicode_tokenizer {
140913 sqlite3_tokenizer base;
140914 int bRemoveDiacritic;
140915 int nException;
140916 int *aiException;
140919 struct unicode_cursor {
140920 sqlite3_tokenizer_cursor base;
140921 const unsigned char *aInput; /* Input text being tokenized */
140922 int nInput; /* Size of aInput[] in bytes */
140923 int iOff; /* Current offset within aInput[] */
140924 int iToken; /* Index of next token to be returned */
140925 char *zToken; /* storage for current token */
140926 int nAlloc; /* space allocated at zToken */
140931 ** Destroy a tokenizer allocated by unicodeCreate().
140933 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
140934 if( pTokenizer ){
140935 unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
140936 sqlite3_free(p->aiException);
140937 sqlite3_free(p);
140939 return SQLITE_OK;
140943 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
140944 ** statement has specified that the tokenizer for this table shall consider
140945 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
140946 ** token characters (if bAlnum==1).
140948 ** For each codepoint in the zIn/nIn string, this function checks if the
140949 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
140950 ** If so, no action is taken. Otherwise, the codepoint is added to the
140951 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
140952 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
140953 ** codepoints in the aiException[] array.
140955 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
140956 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
140957 ** It is not possible to change the behavior of the tokenizer with respect
140958 ** to these codepoints.
140960 static int unicodeAddExceptions(
140961 unicode_tokenizer *p, /* Tokenizer to add exceptions to */
140962 int bAlnum, /* Replace Isalnum() return value with this */
140963 const char *zIn, /* Array of characters to make exceptions */
140964 int nIn /* Length of z in bytes */
140966 const unsigned char *z = (const unsigned char *)zIn;
140967 const unsigned char *zTerm = &z[nIn];
140968 int iCode;
140969 int nEntry = 0;
140971 assert( bAlnum==0 || bAlnum==1 );
140973 while( z<zTerm ){
140974 READ_UTF8(z, zTerm, iCode);
140975 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
140976 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
140977 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
140979 nEntry++;
140983 if( nEntry ){
140984 int *aNew; /* New aiException[] array */
140985 int nNew; /* Number of valid entries in array aNew[] */
140987 aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
140988 if( aNew==0 ) return SQLITE_NOMEM;
140989 nNew = p->nException;
140991 z = (const unsigned char *)zIn;
140992 while( z<zTerm ){
140993 READ_UTF8(z, zTerm, iCode);
140994 if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
140995 && sqlite3FtsUnicodeIsdiacritic(iCode)==0
140997 int i, j;
140998 for(i=0; i<nNew && aNew[i]<iCode; i++);
140999 for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
141000 aNew[i] = iCode;
141001 nNew++;
141004 p->aiException = aNew;
141005 p->nException = nNew;
141008 return SQLITE_OK;
141012 ** Return true if the p->aiException[] array contains the value iCode.
141014 static int unicodeIsException(unicode_tokenizer *p, int iCode){
141015 if( p->nException>0 ){
141016 int *a = p->aiException;
141017 int iLo = 0;
141018 int iHi = p->nException-1;
141020 while( iHi>=iLo ){
141021 int iTest = (iHi + iLo) / 2;
141022 if( iCode==a[iTest] ){
141023 return 1;
141024 }else if( iCode>a[iTest] ){
141025 iLo = iTest+1;
141026 }else{
141027 iHi = iTest-1;
141032 return 0;
141036 ** Return true if, for the purposes of tokenization, codepoint iCode is
141037 ** considered a token character (not a separator).
141039 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
141040 assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
141041 return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
141045 ** Create a new tokenizer instance.
141047 static int unicodeCreate(
141048 int nArg, /* Size of array argv[] */
141049 const char * const *azArg, /* Tokenizer creation arguments */
141050 sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
141052 unicode_tokenizer *pNew; /* New tokenizer object */
141053 int i;
141054 int rc = SQLITE_OK;
141056 pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
141057 if( pNew==NULL ) return SQLITE_NOMEM;
141058 memset(pNew, 0, sizeof(unicode_tokenizer));
141059 pNew->bRemoveDiacritic = 1;
141061 for(i=0; rc==SQLITE_OK && i<nArg; i++){
141062 const char *z = azArg[i];
141063 int n = strlen(z);
141065 if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
141066 pNew->bRemoveDiacritic = 1;
141068 else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
141069 pNew->bRemoveDiacritic = 0;
141071 else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
141072 rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
141074 else if( n>=11 && memcmp("separators=", z, 11)==0 ){
141075 rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
141077 else{
141078 /* Unrecognized argument */
141079 rc = SQLITE_ERROR;
141083 if( rc!=SQLITE_OK ){
141084 unicodeDestroy((sqlite3_tokenizer *)pNew);
141085 pNew = 0;
141087 *pp = (sqlite3_tokenizer *)pNew;
141088 return rc;
141092 ** Prepare to begin tokenizing a particular string. The input
141093 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
141094 ** used to incrementally tokenize this string is returned in
141095 ** *ppCursor.
141097 static int unicodeOpen(
141098 sqlite3_tokenizer *p, /* The tokenizer */
141099 const char *aInput, /* Input string */
141100 int nInput, /* Size of string aInput in bytes */
141101 sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
141103 unicode_cursor *pCsr;
141105 pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
141106 if( pCsr==0 ){
141107 return SQLITE_NOMEM;
141109 memset(pCsr, 0, sizeof(unicode_cursor));
141111 pCsr->aInput = (const unsigned char *)aInput;
141112 if( aInput==0 ){
141113 pCsr->nInput = 0;
141114 }else if( nInput<0 ){
141115 pCsr->nInput = (int)strlen(aInput);
141116 }else{
141117 pCsr->nInput = nInput;
141120 *pp = &pCsr->base;
141121 UNUSED_PARAMETER(p);
141122 return SQLITE_OK;
141126 ** Close a tokenization cursor previously opened by a call to
141127 ** simpleOpen() above.
141129 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
141130 unicode_cursor *pCsr = (unicode_cursor *) pCursor;
141131 sqlite3_free(pCsr->zToken);
141132 sqlite3_free(pCsr);
141133 return SQLITE_OK;
141137 ** Extract the next token from a tokenization cursor. The cursor must
141138 ** have been opened by a prior call to simpleOpen().
141140 static int unicodeNext(
141141 sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
141142 const char **paToken, /* OUT: Token text */
141143 int *pnToken, /* OUT: Number of bytes at *paToken */
141144 int *piStart, /* OUT: Starting offset of token */
141145 int *piEnd, /* OUT: Ending offset of token */
141146 int *piPos /* OUT: Position integer of token */
141148 unicode_cursor *pCsr = (unicode_cursor *)pC;
141149 unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
141150 int iCode;
141151 char *zOut;
141152 const unsigned char *z = &pCsr->aInput[pCsr->iOff];
141153 const unsigned char *zStart = z;
141154 const unsigned char *zEnd;
141155 const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
141157 /* Scan past any delimiter characters before the start of the next token.
141158 ** Return SQLITE_DONE early if this takes us all the way to the end of
141159 ** the input. */
141160 while( z<zTerm ){
141161 READ_UTF8(z, zTerm, iCode);
141162 if( unicodeIsAlnum(p, iCode) ) break;
141163 zStart = z;
141165 if( zStart>=zTerm ) return SQLITE_DONE;
141167 zOut = pCsr->zToken;
141169 int iOut;
141171 /* Grow the output buffer if required. */
141172 if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
141173 char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
141174 if( !zNew ) return SQLITE_NOMEM;
141175 zOut = &zNew[zOut - pCsr->zToken];
141176 pCsr->zToken = zNew;
141177 pCsr->nAlloc += 64;
141180 /* Write the folded case of the last character read to the output */
141181 zEnd = z;
141182 iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
141183 if( iOut ){
141184 WRITE_UTF8(zOut, iOut);
141187 /* If the cursor is not at EOF, read the next character */
141188 if( z>=zTerm ) break;
141189 READ_UTF8(z, zTerm, iCode);
141190 }while( unicodeIsAlnum(p, iCode)
141191 || sqlite3FtsUnicodeIsdiacritic(iCode)
141194 /* Set the output variables and return. */
141195 pCsr->iOff = (z - pCsr->aInput);
141196 *paToken = pCsr->zToken;
141197 *pnToken = zOut - pCsr->zToken;
141198 *piStart = (zStart - pCsr->aInput);
141199 *piEnd = (zEnd - pCsr->aInput);
141200 *piPos = pCsr->iToken++;
141201 return SQLITE_OK;
141205 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
141206 ** structure for the unicode tokenizer.
141208 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
141209 static const sqlite3_tokenizer_module module = {
141211 unicodeCreate,
141212 unicodeDestroy,
141213 unicodeOpen,
141214 unicodeClose,
141215 unicodeNext,
141218 *ppModule = &module;
141221 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141222 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
141224 /************** End of fts3_unicode.c ****************************************/
141225 /************** Begin file fts3_unicode2.c ***********************************/
141227 ** 2012 May 25
141229 ** The author disclaims copyright to this source code. In place of
141230 ** a legal notice, here is a blessing:
141232 ** May you do good and not evil.
141233 ** May you find forgiveness for yourself and forgive others.
141234 ** May you share freely, never taking more than you give.
141236 ******************************************************************************
141240 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
141243 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
141244 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
141246 /* #include <assert.h> */
141249 ** Return true if the argument corresponds to a unicode codepoint
141250 ** classified as either a letter or a number. Otherwise false.
141252 ** The results are undefined if the value passed to this function
141253 ** is less than zero.
141255 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
141256 /* Each unsigned integer in the following array corresponds to a contiguous
141257 ** range of unicode codepoints that are not either letters or numbers (i.e.
141258 ** codepoints for which this function should return 0).
141260 ** The most significant 22 bits in each 32-bit value contain the first
141261 ** codepoint in the range. The least significant 10 bits are used to store
141262 ** the size of the range (always at least 1). In other words, the value
141263 ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
141264 ** C. It is not possible to represent a range larger than 1023 codepoints
141265 ** using this format.
141267 const static unsigned int aEntry[] = {
141268 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
141269 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
141270 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
141271 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
141272 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
141273 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
141274 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
141275 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
141276 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
141277 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
141278 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
141279 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
141280 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
141281 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
141282 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
141283 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
141284 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
141285 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
141286 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
141287 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
141288 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
141289 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
141290 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
141291 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
141292 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
141293 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
141294 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
141295 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
141296 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
141297 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
141298 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
141299 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
141300 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
141301 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
141302 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
141303 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
141304 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
141305 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
141306 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
141307 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
141308 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
141309 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
141310 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
141311 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
141312 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
141313 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
141314 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
141315 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
141316 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
141317 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
141318 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
141319 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
141320 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
141321 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
141322 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
141323 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
141324 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
141325 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
141326 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
141327 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
141328 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
141329 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
141330 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
141331 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
141332 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
141333 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
141334 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
141335 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
141336 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
141337 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
141338 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
141339 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
141340 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
141341 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
141342 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
141343 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
141344 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
141345 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
141346 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
141347 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
141348 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
141349 0x380400F0,
141351 static const unsigned int aAscii[4] = {
141352 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
141355 if( c<128 ){
141356 return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
141357 }else if( c<(1<<22) ){
141358 unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
141359 int iRes;
141360 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
141361 int iLo = 0;
141362 while( iHi>=iLo ){
141363 int iTest = (iHi + iLo) / 2;
141364 if( key >= aEntry[iTest] ){
141365 iRes = iTest;
141366 iLo = iTest+1;
141367 }else{
141368 iHi = iTest-1;
141371 assert( aEntry[0]<key );
141372 assert( key>=aEntry[iRes] );
141373 return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
141375 return 1;
141380 ** If the argument is a codepoint corresponding to a lowercase letter
141381 ** in the ASCII range with a diacritic added, return the codepoint
141382 ** of the ASCII letter only. For example, if passed 235 - "LATIN
141383 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
141384 ** E"). The resuls of passing a codepoint that corresponds to an
141385 ** uppercase letter are undefined.
141387 static int remove_diacritic(int c){
141388 unsigned short aDia[] = {
141389 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
141390 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
141391 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
141392 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
141393 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
141394 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
141395 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
141396 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
141397 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
141398 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
141399 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
141400 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
141401 62924, 63050, 63082, 63274, 63390,
141403 char aChar[] = {
141404 '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
141405 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
141406 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
141407 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
141408 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
141409 '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
141410 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
141411 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
141412 'e', 'i', 'o', 'u', 'y',
141415 unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
141416 int iRes = 0;
141417 int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
141418 int iLo = 0;
141419 while( iHi>=iLo ){
141420 int iTest = (iHi + iLo) / 2;
141421 if( key >= aDia[iTest] ){
141422 iRes = iTest;
141423 iLo = iTest+1;
141424 }else{
141425 iHi = iTest-1;
141428 assert( key>=aDia[iRes] );
141429 return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
141434 ** Return true if the argument interpreted as a unicode codepoint
141435 ** is a diacritical modifier character.
141437 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
141438 unsigned int mask0 = 0x08029FDF;
141439 unsigned int mask1 = 0x000361F8;
141440 if( c<768 || c>817 ) return 0;
141441 return (c < 768+32) ?
141442 (mask0 & (1 << (c-768))) :
141443 (mask1 & (1 << (c-768-32)));
141448 ** Interpret the argument as a unicode codepoint. If the codepoint
141449 ** is an upper case character that has a lower case equivalent,
141450 ** return the codepoint corresponding to the lower case version.
141451 ** Otherwise, return a copy of the argument.
141453 ** The results are undefined if the value passed to this function
141454 ** is less than zero.
141456 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
141457 /* Each entry in the following array defines a rule for folding a range
141458 ** of codepoints to lower case. The rule applies to a range of nRange
141459 ** codepoints starting at codepoint iCode.
141461 ** If the least significant bit in flags is clear, then the rule applies
141462 ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
141463 ** need to be folded). Or, if it is set, then the rule only applies to
141464 ** every second codepoint in the range, starting with codepoint C.
141466 ** The 7 most significant bits in flags are an index into the aiOff[]
141467 ** array. If a specific codepoint C does require folding, then its lower
141468 ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
141470 ** The contents of this array are generated by parsing the CaseFolding.txt
141471 ** file distributed as part of the "Unicode Character Database". See
141472 ** http://www.unicode.org for details.
141474 static const struct TableEntry {
141475 unsigned short iCode;
141476 unsigned char flags;
141477 unsigned char nRange;
141478 } aEntry[] = {
141479 {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
141480 {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
141481 {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
141482 {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
141483 {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
141484 {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
141485 {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
141486 {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
141487 {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
141488 {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
141489 {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
141490 {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
141491 {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
141492 {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
141493 {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
141494 {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
141495 {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
141496 {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
141497 {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
141498 {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
141499 {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
141500 {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
141501 {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
141502 {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
141503 {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
141504 {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
141505 {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
141506 {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
141507 {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
141508 {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
141509 {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
141510 {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
141511 {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
141512 {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
141513 {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
141514 {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
141515 {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
141516 {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
141517 {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
141518 {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
141519 {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
141520 {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
141521 {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
141522 {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
141523 {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
141524 {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
141525 {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
141526 {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
141527 {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
141528 {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
141529 {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
141530 {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
141531 {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
141532 {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
141533 {65313, 14, 26},
141535 static const unsigned short aiOff[] = {
141536 1, 2, 8, 15, 16, 26, 28, 32,
141537 37, 38, 40, 48, 63, 64, 69, 71,
141538 79, 80, 116, 202, 203, 205, 206, 207,
141539 209, 210, 211, 213, 214, 217, 218, 219,
141540 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
141541 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
141542 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
141543 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
141544 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
141545 65514, 65521, 65527, 65528, 65529,
141548 int ret = c;
141550 assert( c>=0 );
141551 assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
141553 if( c<128 ){
141554 if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
141555 }else if( c<65536 ){
141556 int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
141557 int iLo = 0;
141558 int iRes = -1;
141560 while( iHi>=iLo ){
141561 int iTest = (iHi + iLo) / 2;
141562 int cmp = (c - aEntry[iTest].iCode);
141563 if( cmp>=0 ){
141564 iRes = iTest;
141565 iLo = iTest+1;
141566 }else{
141567 iHi = iTest-1;
141570 assert( iRes<0 || c>=aEntry[iRes].iCode );
141572 if( iRes>=0 ){
141573 const struct TableEntry *p = &aEntry[iRes];
141574 if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
141575 ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
141576 assert( ret>0 );
141580 if( bRemoveDiacritic ) ret = remove_diacritic(ret);
141583 else if( c>=66560 && c<66600 ){
141584 ret = c + 40;
141587 return ret;
141589 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
141590 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
141592 /************** End of fts3_unicode2.c ***************************************/
141593 /************** Begin file rtree.c *******************************************/
141595 ** 2001 September 15
141597 ** The author disclaims copyright to this source code. In place of
141598 ** a legal notice, here is a blessing:
141600 ** May you do good and not evil.
141601 ** May you find forgiveness for yourself and forgive others.
141602 ** May you share freely, never taking more than you give.
141604 *************************************************************************
141605 ** This file contains code for implementations of the r-tree and r*-tree
141606 ** algorithms packaged as an SQLite virtual table module.
141610 ** Database Format of R-Tree Tables
141611 ** --------------------------------
141613 ** The data structure for a single virtual r-tree table is stored in three
141614 ** native SQLite tables declared as follows. In each case, the '%' character
141615 ** in the table name is replaced with the user-supplied name of the r-tree
141616 ** table.
141618 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
141619 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
141620 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
141622 ** The data for each node of the r-tree structure is stored in the %_node
141623 ** table. For each node that is not the root node of the r-tree, there is
141624 ** an entry in the %_parent table associating the node with its parent.
141625 ** And for each row of data in the table, there is an entry in the %_rowid
141626 ** table that maps from the entries rowid to the id of the node that it
141627 ** is stored on.
141629 ** The root node of an r-tree always exists, even if the r-tree table is
141630 ** empty. The nodeno of the root node is always 1. All other nodes in the
141631 ** table must be the same size as the root node. The content of each node
141632 ** is formatted as follows:
141634 ** 1. If the node is the root node (node 1), then the first 2 bytes
141635 ** of the node contain the tree depth as a big-endian integer.
141636 ** For non-root nodes, the first 2 bytes are left unused.
141638 ** 2. The next 2 bytes contain the number of entries currently
141639 ** stored in the node.
141641 ** 3. The remainder of the node contains the node entries. Each entry
141642 ** consists of a single 8-byte integer followed by an even number
141643 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
141644 ** of a record. For internal nodes it is the node number of a
141645 ** child page.
141648 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
141651 ** This file contains an implementation of a couple of different variants
141652 ** of the r-tree algorithm. See the README file for further details. The
141653 ** same data-structure is used for all, but the algorithms for insert and
141654 ** delete operations vary. The variants used are selected at compile time
141655 ** by defining the following symbols:
141658 /* Either, both or none of the following may be set to activate
141659 ** r*tree variant algorithms.
141661 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
141662 #define VARIANT_RSTARTREE_REINSERT 1
141665 ** Exactly one of the following must be set to 1.
141667 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
141668 #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
141669 #define VARIANT_RSTARTREE_SPLIT 1
141671 #define VARIANT_GUTTMAN_SPLIT \
141672 (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
141674 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
141675 #define PickNext QuadraticPickNext
141676 #define PickSeeds QuadraticPickSeeds
141677 #define AssignCells splitNodeGuttman
141678 #endif
141679 #if VARIANT_GUTTMAN_LINEAR_SPLIT
141680 #define PickNext LinearPickNext
141681 #define PickSeeds LinearPickSeeds
141682 #define AssignCells splitNodeGuttman
141683 #endif
141684 #if VARIANT_RSTARTREE_SPLIT
141685 #define AssignCells splitNodeStartree
141686 #endif
141688 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
141689 # define NDEBUG 1
141690 #endif
141692 #ifndef SQLITE_CORE
141693 SQLITE_EXTENSION_INIT1
141694 #else
141695 #endif
141697 /* #include <string.h> */
141698 /* #include <assert.h> */
141700 #ifndef SQLITE_AMALGAMATION
141701 #include "sqlite3rtree.h"
141702 typedef sqlite3_int64 i64;
141703 typedef unsigned char u8;
141704 typedef unsigned int u32;
141705 #endif
141707 /* The following macro is used to suppress compiler warnings.
141709 #ifndef UNUSED_PARAMETER
141710 # define UNUSED_PARAMETER(x) (void)(x)
141711 #endif
141713 typedef struct Rtree Rtree;
141714 typedef struct RtreeCursor RtreeCursor;
141715 typedef struct RtreeNode RtreeNode;
141716 typedef struct RtreeCell RtreeCell;
141717 typedef struct RtreeConstraint RtreeConstraint;
141718 typedef struct RtreeMatchArg RtreeMatchArg;
141719 typedef struct RtreeGeomCallback RtreeGeomCallback;
141720 typedef union RtreeCoord RtreeCoord;
141722 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
141723 #define RTREE_MAX_DIMENSIONS 5
141725 /* Size of hash table Rtree.aHash. This hash table is not expected to
141726 ** ever contain very many entries, so a fixed number of buckets is
141727 ** used.
141729 #define HASHSIZE 128
141731 /* The xBestIndex method of this virtual table requires an estimate of
141732 ** the number of rows in the virtual table to calculate the costs of
141733 ** various strategies. If possible, this estimate is loaded from the
141734 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
141735 ** Otherwise, if no sqlite_stat1 entry is available, use
141736 ** RTREE_DEFAULT_ROWEST.
141738 #define RTREE_DEFAULT_ROWEST 1048576
141739 #define RTREE_MIN_ROWEST 100
141742 ** An rtree virtual-table object.
141744 struct Rtree {
141745 sqlite3_vtab base;
141746 sqlite3 *db; /* Host database connection */
141747 int iNodeSize; /* Size in bytes of each node in the node table */
141748 int nDim; /* Number of dimensions */
141749 int nBytesPerCell; /* Bytes consumed per cell */
141750 int iDepth; /* Current depth of the r-tree structure */
141751 char *zDb; /* Name of database containing r-tree table */
141752 char *zName; /* Name of r-tree table */
141753 RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
141754 int nBusy; /* Current number of users of this structure */
141755 i64 nRowEst; /* Estimated number of rows in this table */
141757 /* List of nodes removed during a CondenseTree operation. List is
141758 ** linked together via the pointer normally used for hash chains -
141759 ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
141760 ** headed by the node (leaf nodes have RtreeNode.iNode==0).
141762 RtreeNode *pDeleted;
141763 int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
141765 /* Statements to read/write/delete a record from xxx_node */
141766 sqlite3_stmt *pReadNode;
141767 sqlite3_stmt *pWriteNode;
141768 sqlite3_stmt *pDeleteNode;
141770 /* Statements to read/write/delete a record from xxx_rowid */
141771 sqlite3_stmt *pReadRowid;
141772 sqlite3_stmt *pWriteRowid;
141773 sqlite3_stmt *pDeleteRowid;
141775 /* Statements to read/write/delete a record from xxx_parent */
141776 sqlite3_stmt *pReadParent;
141777 sqlite3_stmt *pWriteParent;
141778 sqlite3_stmt *pDeleteParent;
141780 int eCoordType;
141783 /* Possible values for eCoordType: */
141784 #define RTREE_COORD_REAL32 0
141785 #define RTREE_COORD_INT32 1
141788 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
141789 ** only deal with integer coordinates. No floating point operations
141790 ** will be done.
141792 #ifdef SQLITE_RTREE_INT_ONLY
141793 typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
141794 typedef int RtreeValue; /* Low accuracy coordinate */
141795 #else
141796 typedef double RtreeDValue; /* High accuracy coordinate */
141797 typedef float RtreeValue; /* Low accuracy coordinate */
141798 #endif
141801 ** The minimum number of cells allowed for a node is a third of the
141802 ** maximum. In Gutman's notation:
141804 ** m = M/3
141806 ** If an R*-tree "Reinsert" operation is required, the same number of
141807 ** cells are removed from the overfull node and reinserted into the tree.
141809 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
141810 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
141811 #define RTREE_MAXCELLS 51
141814 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
141815 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
141816 ** Therefore all non-root nodes must contain at least 3 entries. Since
141817 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
141818 ** 40 or less.
141820 #define RTREE_MAX_DEPTH 40
141823 ** An rtree cursor object.
141825 struct RtreeCursor {
141826 sqlite3_vtab_cursor base;
141827 RtreeNode *pNode; /* Node cursor is currently pointing at */
141828 int iCell; /* Index of current cell in pNode */
141829 int iStrategy; /* Copy of idxNum search parameter */
141830 int nConstraint; /* Number of entries in aConstraint */
141831 RtreeConstraint *aConstraint; /* Search constraints. */
141834 union RtreeCoord {
141835 RtreeValue f;
141836 int i;
141840 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
141841 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
141842 ** variable pRtree points to the Rtree structure associated with the
141843 ** RtreeCoord.
141845 #ifdef SQLITE_RTREE_INT_ONLY
141846 # define DCOORD(coord) ((RtreeDValue)coord.i)
141847 #else
141848 # define DCOORD(coord) ( \
141849 (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
141850 ((double)coord.f) : \
141851 ((double)coord.i) \
141853 #endif
141856 ** A search constraint.
141858 struct RtreeConstraint {
141859 int iCoord; /* Index of constrained coordinate */
141860 int op; /* Constraining operation */
141861 RtreeDValue rValue; /* Constraint value. */
141862 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
141863 sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
141866 /* Possible values for RtreeConstraint.op */
141867 #define RTREE_EQ 0x41
141868 #define RTREE_LE 0x42
141869 #define RTREE_LT 0x43
141870 #define RTREE_GE 0x44
141871 #define RTREE_GT 0x45
141872 #define RTREE_MATCH 0x46
141875 ** An rtree structure node.
141877 struct RtreeNode {
141878 RtreeNode *pParent; /* Parent node */
141879 i64 iNode;
141880 int nRef;
141881 int isDirty;
141882 u8 *zData;
141883 RtreeNode *pNext; /* Next node in this hash chain */
141885 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
141888 ** Structure to store a deserialized rtree record.
141890 struct RtreeCell {
141891 i64 iRowid;
141892 RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
141897 ** Value for the first field of every RtreeMatchArg object. The MATCH
141898 ** operator tests that the first field of a blob operand matches this
141899 ** value to avoid operating on invalid blobs (which could cause a segfault).
141901 #define RTREE_GEOMETRY_MAGIC 0x891245AB
141904 ** An instance of this structure must be supplied as a blob argument to
141905 ** the right-hand-side of an SQL MATCH operator used to constrain an
141906 ** r-tree query.
141908 struct RtreeMatchArg {
141909 u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
141910 int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
141911 void *pContext;
141912 int nParam;
141913 RtreeDValue aParam[1];
141917 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
141918 ** a single instance of the following structure is allocated. It is used
141919 ** as the context for the user-function created by by s_r_g_c(). The object
141920 ** is eventually deleted by the destructor mechanism provided by
141921 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
141922 ** the geometry callback function).
141924 struct RtreeGeomCallback {
141925 int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
141926 void *pContext;
141929 #ifndef MAX
141930 # define MAX(x,y) ((x) < (y) ? (y) : (x))
141931 #endif
141932 #ifndef MIN
141933 # define MIN(x,y) ((x) > (y) ? (y) : (x))
141934 #endif
141937 ** Functions to deserialize a 16 bit integer, 32 bit real number and
141938 ** 64 bit integer. The deserialized value is returned.
141940 static int readInt16(u8 *p){
141941 return (p[0]<<8) + p[1];
141943 static void readCoord(u8 *p, RtreeCoord *pCoord){
141944 u32 i = (
141945 (((u32)p[0]) << 24) +
141946 (((u32)p[1]) << 16) +
141947 (((u32)p[2]) << 8) +
141948 (((u32)p[3]) << 0)
141950 *(u32 *)pCoord = i;
141952 static i64 readInt64(u8 *p){
141953 return (
141954 (((i64)p[0]) << 56) +
141955 (((i64)p[1]) << 48) +
141956 (((i64)p[2]) << 40) +
141957 (((i64)p[3]) << 32) +
141958 (((i64)p[4]) << 24) +
141959 (((i64)p[5]) << 16) +
141960 (((i64)p[6]) << 8) +
141961 (((i64)p[7]) << 0)
141966 ** Functions to serialize a 16 bit integer, 32 bit real number and
141967 ** 64 bit integer. The value returned is the number of bytes written
141968 ** to the argument buffer (always 2, 4 and 8 respectively).
141970 static int writeInt16(u8 *p, int i){
141971 p[0] = (i>> 8)&0xFF;
141972 p[1] = (i>> 0)&0xFF;
141973 return 2;
141975 static int writeCoord(u8 *p, RtreeCoord *pCoord){
141976 u32 i;
141977 assert( sizeof(RtreeCoord)==4 );
141978 assert( sizeof(u32)==4 );
141979 i = *(u32 *)pCoord;
141980 p[0] = (i>>24)&0xFF;
141981 p[1] = (i>>16)&0xFF;
141982 p[2] = (i>> 8)&0xFF;
141983 p[3] = (i>> 0)&0xFF;
141984 return 4;
141986 static int writeInt64(u8 *p, i64 i){
141987 p[0] = (i>>56)&0xFF;
141988 p[1] = (i>>48)&0xFF;
141989 p[2] = (i>>40)&0xFF;
141990 p[3] = (i>>32)&0xFF;
141991 p[4] = (i>>24)&0xFF;
141992 p[5] = (i>>16)&0xFF;
141993 p[6] = (i>> 8)&0xFF;
141994 p[7] = (i>> 0)&0xFF;
141995 return 8;
141999 ** Increment the reference count of node p.
142001 static void nodeReference(RtreeNode *p){
142002 if( p ){
142003 p->nRef++;
142008 ** Clear the content of node p (set all bytes to 0x00).
142010 static void nodeZero(Rtree *pRtree, RtreeNode *p){
142011 memset(&p->zData[2], 0, pRtree->iNodeSize-2);
142012 p->isDirty = 1;
142016 ** Given a node number iNode, return the corresponding key to use
142017 ** in the Rtree.aHash table.
142019 static int nodeHash(i64 iNode){
142020 return (
142021 (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
142022 (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
142023 ) % HASHSIZE;
142027 ** Search the node hash table for node iNode. If found, return a pointer
142028 ** to it. Otherwise, return 0.
142030 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
142031 RtreeNode *p;
142032 for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
142033 return p;
142037 ** Add node pNode to the node hash table.
142039 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
142040 int iHash;
142041 assert( pNode->pNext==0 );
142042 iHash = nodeHash(pNode->iNode);
142043 pNode->pNext = pRtree->aHash[iHash];
142044 pRtree->aHash[iHash] = pNode;
142048 ** Remove node pNode from the node hash table.
142050 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
142051 RtreeNode **pp;
142052 if( pNode->iNode!=0 ){
142053 pp = &pRtree->aHash[nodeHash(pNode->iNode)];
142054 for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
142055 *pp = pNode->pNext;
142056 pNode->pNext = 0;
142061 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
142062 ** indicating that node has not yet been assigned a node number. It is
142063 ** assigned a node number when nodeWrite() is called to write the
142064 ** node contents out to the database.
142066 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
142067 RtreeNode *pNode;
142068 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
142069 if( pNode ){
142070 memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
142071 pNode->zData = (u8 *)&pNode[1];
142072 pNode->nRef = 1;
142073 pNode->pParent = pParent;
142074 pNode->isDirty = 1;
142075 nodeReference(pParent);
142077 return pNode;
142081 ** Obtain a reference to an r-tree node.
142083 static int
142084 nodeAcquire(
142085 Rtree *pRtree, /* R-tree structure */
142086 i64 iNode, /* Node number to load */
142087 RtreeNode *pParent, /* Either the parent node or NULL */
142088 RtreeNode **ppNode /* OUT: Acquired node */
142090 int rc;
142091 int rc2 = SQLITE_OK;
142092 RtreeNode *pNode;
142094 /* Check if the requested node is already in the hash table. If so,
142095 ** increase its reference count and return it.
142097 if( (pNode = nodeHashLookup(pRtree, iNode)) ){
142098 assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
142099 if( pParent && !pNode->pParent ){
142100 nodeReference(pParent);
142101 pNode->pParent = pParent;
142103 pNode->nRef++;
142104 *ppNode = pNode;
142105 return SQLITE_OK;
142108 sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
142109 rc = sqlite3_step(pRtree->pReadNode);
142110 if( rc==SQLITE_ROW ){
142111 const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
142112 if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
142113 pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
142114 if( !pNode ){
142115 rc2 = SQLITE_NOMEM;
142116 }else{
142117 pNode->pParent = pParent;
142118 pNode->zData = (u8 *)&pNode[1];
142119 pNode->nRef = 1;
142120 pNode->iNode = iNode;
142121 pNode->isDirty = 0;
142122 pNode->pNext = 0;
142123 memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
142124 nodeReference(pParent);
142128 rc = sqlite3_reset(pRtree->pReadNode);
142129 if( rc==SQLITE_OK ) rc = rc2;
142131 /* If the root node was just loaded, set pRtree->iDepth to the height
142132 ** of the r-tree structure. A height of zero means all data is stored on
142133 ** the root node. A height of one means the children of the root node
142134 ** are the leaves, and so on. If the depth as specified on the root node
142135 ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
142137 if( pNode && iNode==1 ){
142138 pRtree->iDepth = readInt16(pNode->zData);
142139 if( pRtree->iDepth>RTREE_MAX_DEPTH ){
142140 rc = SQLITE_CORRUPT_VTAB;
142144 /* If no error has occurred so far, check if the "number of entries"
142145 ** field on the node is too large. If so, set the return code to
142146 ** SQLITE_CORRUPT_VTAB.
142148 if( pNode && rc==SQLITE_OK ){
142149 if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
142150 rc = SQLITE_CORRUPT_VTAB;
142154 if( rc==SQLITE_OK ){
142155 if( pNode!=0 ){
142156 nodeHashInsert(pRtree, pNode);
142157 }else{
142158 rc = SQLITE_CORRUPT_VTAB;
142160 *ppNode = pNode;
142161 }else{
142162 sqlite3_free(pNode);
142163 *ppNode = 0;
142166 return rc;
142170 ** Overwrite cell iCell of node pNode with the contents of pCell.
142172 static void nodeOverwriteCell(
142173 Rtree *pRtree,
142174 RtreeNode *pNode,
142175 RtreeCell *pCell,
142176 int iCell
142178 int ii;
142179 u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
142180 p += writeInt64(p, pCell->iRowid);
142181 for(ii=0; ii<(pRtree->nDim*2); ii++){
142182 p += writeCoord(p, &pCell->aCoord[ii]);
142184 pNode->isDirty = 1;
142188 ** Remove cell the cell with index iCell from node pNode.
142190 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
142191 u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
142192 u8 *pSrc = &pDst[pRtree->nBytesPerCell];
142193 int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
142194 memmove(pDst, pSrc, nByte);
142195 writeInt16(&pNode->zData[2], NCELL(pNode)-1);
142196 pNode->isDirty = 1;
142200 ** Insert the contents of cell pCell into node pNode. If the insert
142201 ** is successful, return SQLITE_OK.
142203 ** If there is not enough free space in pNode, return SQLITE_FULL.
142205 static int
142206 nodeInsertCell(
142207 Rtree *pRtree,
142208 RtreeNode *pNode,
142209 RtreeCell *pCell
142211 int nCell; /* Current number of cells in pNode */
142212 int nMaxCell; /* Maximum number of cells for pNode */
142214 nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
142215 nCell = NCELL(pNode);
142217 assert( nCell<=nMaxCell );
142218 if( nCell<nMaxCell ){
142219 nodeOverwriteCell(pRtree, pNode, pCell, nCell);
142220 writeInt16(&pNode->zData[2], nCell+1);
142221 pNode->isDirty = 1;
142224 return (nCell==nMaxCell);
142228 ** If the node is dirty, write it out to the database.
142230 static int
142231 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
142232 int rc = SQLITE_OK;
142233 if( pNode->isDirty ){
142234 sqlite3_stmt *p = pRtree->pWriteNode;
142235 if( pNode->iNode ){
142236 sqlite3_bind_int64(p, 1, pNode->iNode);
142237 }else{
142238 sqlite3_bind_null(p, 1);
142240 sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
142241 sqlite3_step(p);
142242 pNode->isDirty = 0;
142243 rc = sqlite3_reset(p);
142244 if( pNode->iNode==0 && rc==SQLITE_OK ){
142245 pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
142246 nodeHashInsert(pRtree, pNode);
142249 return rc;
142253 ** Release a reference to a node. If the node is dirty and the reference
142254 ** count drops to zero, the node data is written to the database.
142256 static int
142257 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
142258 int rc = SQLITE_OK;
142259 if( pNode ){
142260 assert( pNode->nRef>0 );
142261 pNode->nRef--;
142262 if( pNode->nRef==0 ){
142263 if( pNode->iNode==1 ){
142264 pRtree->iDepth = -1;
142266 if( pNode->pParent ){
142267 rc = nodeRelease(pRtree, pNode->pParent);
142269 if( rc==SQLITE_OK ){
142270 rc = nodeWrite(pRtree, pNode);
142272 nodeHashDelete(pRtree, pNode);
142273 sqlite3_free(pNode);
142276 return rc;
142280 ** Return the 64-bit integer value associated with cell iCell of
142281 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
142282 ** an internal node, then the 64-bit integer is a child page number.
142284 static i64 nodeGetRowid(
142285 Rtree *pRtree,
142286 RtreeNode *pNode,
142287 int iCell
142289 assert( iCell<NCELL(pNode) );
142290 return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
142294 ** Return coordinate iCoord from cell iCell in node pNode.
142296 static void nodeGetCoord(
142297 Rtree *pRtree,
142298 RtreeNode *pNode,
142299 int iCell,
142300 int iCoord,
142301 RtreeCoord *pCoord /* Space to write result to */
142303 readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
142307 ** Deserialize cell iCell of node pNode. Populate the structure pointed
142308 ** to by pCell with the results.
142310 static void nodeGetCell(
142311 Rtree *pRtree,
142312 RtreeNode *pNode,
142313 int iCell,
142314 RtreeCell *pCell
142316 int ii;
142317 pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
142318 for(ii=0; ii<pRtree->nDim*2; ii++){
142319 nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
142324 /* Forward declaration for the function that does the work of
142325 ** the virtual table module xCreate() and xConnect() methods.
142327 static int rtreeInit(
142328 sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
142332 ** Rtree virtual table module xCreate method.
142334 static int rtreeCreate(
142335 sqlite3 *db,
142336 void *pAux,
142337 int argc, const char *const*argv,
142338 sqlite3_vtab **ppVtab,
142339 char **pzErr
142341 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
142345 ** Rtree virtual table module xConnect method.
142347 static int rtreeConnect(
142348 sqlite3 *db,
142349 void *pAux,
142350 int argc, const char *const*argv,
142351 sqlite3_vtab **ppVtab,
142352 char **pzErr
142354 return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
142358 ** Increment the r-tree reference count.
142360 static void rtreeReference(Rtree *pRtree){
142361 pRtree->nBusy++;
142365 ** Decrement the r-tree reference count. When the reference count reaches
142366 ** zero the structure is deleted.
142368 static void rtreeRelease(Rtree *pRtree){
142369 pRtree->nBusy--;
142370 if( pRtree->nBusy==0 ){
142371 sqlite3_finalize(pRtree->pReadNode);
142372 sqlite3_finalize(pRtree->pWriteNode);
142373 sqlite3_finalize(pRtree->pDeleteNode);
142374 sqlite3_finalize(pRtree->pReadRowid);
142375 sqlite3_finalize(pRtree->pWriteRowid);
142376 sqlite3_finalize(pRtree->pDeleteRowid);
142377 sqlite3_finalize(pRtree->pReadParent);
142378 sqlite3_finalize(pRtree->pWriteParent);
142379 sqlite3_finalize(pRtree->pDeleteParent);
142380 sqlite3_free(pRtree);
142385 ** Rtree virtual table module xDisconnect method.
142387 static int rtreeDisconnect(sqlite3_vtab *pVtab){
142388 rtreeRelease((Rtree *)pVtab);
142389 return SQLITE_OK;
142393 ** Rtree virtual table module xDestroy method.
142395 static int rtreeDestroy(sqlite3_vtab *pVtab){
142396 Rtree *pRtree = (Rtree *)pVtab;
142397 int rc;
142398 char *zCreate = sqlite3_mprintf(
142399 "DROP TABLE '%q'.'%q_node';"
142400 "DROP TABLE '%q'.'%q_rowid';"
142401 "DROP TABLE '%q'.'%q_parent';",
142402 pRtree->zDb, pRtree->zName,
142403 pRtree->zDb, pRtree->zName,
142404 pRtree->zDb, pRtree->zName
142406 if( !zCreate ){
142407 rc = SQLITE_NOMEM;
142408 }else{
142409 rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
142410 sqlite3_free(zCreate);
142412 if( rc==SQLITE_OK ){
142413 rtreeRelease(pRtree);
142416 return rc;
142420 ** Rtree virtual table module xOpen method.
142422 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
142423 int rc = SQLITE_NOMEM;
142424 RtreeCursor *pCsr;
142426 pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
142427 if( pCsr ){
142428 memset(pCsr, 0, sizeof(RtreeCursor));
142429 pCsr->base.pVtab = pVTab;
142430 rc = SQLITE_OK;
142432 *ppCursor = (sqlite3_vtab_cursor *)pCsr;
142434 return rc;
142439 ** Free the RtreeCursor.aConstraint[] array and its contents.
142441 static void freeCursorConstraints(RtreeCursor *pCsr){
142442 if( pCsr->aConstraint ){
142443 int i; /* Used to iterate through constraint array */
142444 for(i=0; i<pCsr->nConstraint; i++){
142445 sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
142446 if( pGeom ){
142447 if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
142448 sqlite3_free(pGeom);
142451 sqlite3_free(pCsr->aConstraint);
142452 pCsr->aConstraint = 0;
142457 ** Rtree virtual table module xClose method.
142459 static int rtreeClose(sqlite3_vtab_cursor *cur){
142460 Rtree *pRtree = (Rtree *)(cur->pVtab);
142461 int rc;
142462 RtreeCursor *pCsr = (RtreeCursor *)cur;
142463 freeCursorConstraints(pCsr);
142464 rc = nodeRelease(pRtree, pCsr->pNode);
142465 sqlite3_free(pCsr);
142466 return rc;
142470 ** Rtree virtual table module xEof method.
142472 ** Return non-zero if the cursor does not currently point to a valid
142473 ** record (i.e if the scan has finished), or zero otherwise.
142475 static int rtreeEof(sqlite3_vtab_cursor *cur){
142476 RtreeCursor *pCsr = (RtreeCursor *)cur;
142477 return (pCsr->pNode==0);
142481 ** The r-tree constraint passed as the second argument to this function is
142482 ** guaranteed to be a MATCH constraint.
142484 static int testRtreeGeom(
142485 Rtree *pRtree, /* R-Tree object */
142486 RtreeConstraint *pConstraint, /* MATCH constraint to test */
142487 RtreeCell *pCell, /* Cell to test */
142488 int *pbRes /* OUT: Test result */
142490 int i;
142491 RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
142492 int nCoord = pRtree->nDim*2;
142494 assert( pConstraint->op==RTREE_MATCH );
142495 assert( pConstraint->pGeom );
142497 for(i=0; i<nCoord; i++){
142498 aCoord[i] = DCOORD(pCell->aCoord[i]);
142500 return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
142504 ** Cursor pCursor currently points to a cell in a non-leaf page.
142505 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
142506 ** (excluded) by the constraints in the pCursor->aConstraint[]
142507 ** array, or false otherwise.
142509 ** Return SQLITE_OK if successful or an SQLite error code if an error
142510 ** occurs within a geometry callback.
142512 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
142513 RtreeCell cell;
142514 int ii;
142515 int bRes = 0;
142516 int rc = SQLITE_OK;
142518 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
142519 for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
142520 RtreeConstraint *p = &pCursor->aConstraint[ii];
142521 RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
142522 RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
142524 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
142525 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
142528 switch( p->op ){
142529 case RTREE_LE: case RTREE_LT:
142530 bRes = p->rValue<cell_min;
142531 break;
142533 case RTREE_GE: case RTREE_GT:
142534 bRes = p->rValue>cell_max;
142535 break;
142537 case RTREE_EQ:
142538 bRes = (p->rValue>cell_max || p->rValue<cell_min);
142539 break;
142541 default: {
142542 assert( p->op==RTREE_MATCH );
142543 rc = testRtreeGeom(pRtree, p, &cell, &bRes);
142544 bRes = !bRes;
142545 break;
142550 *pbEof = bRes;
142551 return rc;
142555 ** Test if the cell that cursor pCursor currently points to
142556 ** would be filtered (excluded) by the constraints in the
142557 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
142558 ** returning. If the cell is not filtered (excluded) by the constraints,
142559 ** set pbEof to zero.
142561 ** Return SQLITE_OK if successful or an SQLite error code if an error
142562 ** occurs within a geometry callback.
142564 ** This function assumes that the cell is part of a leaf node.
142566 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
142567 RtreeCell cell;
142568 int ii;
142569 *pbEof = 0;
142571 nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
142572 for(ii=0; ii<pCursor->nConstraint; ii++){
142573 RtreeConstraint *p = &pCursor->aConstraint[ii];
142574 RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
142575 int res;
142576 assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
142577 || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
142579 switch( p->op ){
142580 case RTREE_LE: res = (coord<=p->rValue); break;
142581 case RTREE_LT: res = (coord<p->rValue); break;
142582 case RTREE_GE: res = (coord>=p->rValue); break;
142583 case RTREE_GT: res = (coord>p->rValue); break;
142584 case RTREE_EQ: res = (coord==p->rValue); break;
142585 default: {
142586 int rc;
142587 assert( p->op==RTREE_MATCH );
142588 rc = testRtreeGeom(pRtree, p, &cell, &res);
142589 if( rc!=SQLITE_OK ){
142590 return rc;
142592 break;
142596 if( !res ){
142597 *pbEof = 1;
142598 return SQLITE_OK;
142602 return SQLITE_OK;
142606 ** Cursor pCursor currently points at a node that heads a sub-tree of
142607 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
142608 ** to point to the left-most cell of the sub-tree that matches the
142609 ** configured constraints.
142611 static int descendToCell(
142612 Rtree *pRtree,
142613 RtreeCursor *pCursor,
142614 int iHeight,
142615 int *pEof /* OUT: Set to true if cannot descend */
142617 int isEof;
142618 int rc;
142619 int ii;
142620 RtreeNode *pChild;
142621 sqlite3_int64 iRowid;
142623 RtreeNode *pSavedNode = pCursor->pNode;
142624 int iSavedCell = pCursor->iCell;
142626 assert( iHeight>=0 );
142628 if( iHeight==0 ){
142629 rc = testRtreeEntry(pRtree, pCursor, &isEof);
142630 }else{
142631 rc = testRtreeCell(pRtree, pCursor, &isEof);
142633 if( rc!=SQLITE_OK || isEof || iHeight==0 ){
142634 goto descend_to_cell_out;
142637 iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
142638 rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
142639 if( rc!=SQLITE_OK ){
142640 goto descend_to_cell_out;
142643 nodeRelease(pRtree, pCursor->pNode);
142644 pCursor->pNode = pChild;
142645 isEof = 1;
142646 for(ii=0; isEof && ii<NCELL(pChild); ii++){
142647 pCursor->iCell = ii;
142648 rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
142649 if( rc!=SQLITE_OK ){
142650 goto descend_to_cell_out;
142654 if( isEof ){
142655 assert( pCursor->pNode==pChild );
142656 nodeReference(pSavedNode);
142657 nodeRelease(pRtree, pChild);
142658 pCursor->pNode = pSavedNode;
142659 pCursor->iCell = iSavedCell;
142662 descend_to_cell_out:
142663 *pEof = isEof;
142664 return rc;
142668 ** One of the cells in node pNode is guaranteed to have a 64-bit
142669 ** integer value equal to iRowid. Return the index of this cell.
142671 static int nodeRowidIndex(
142672 Rtree *pRtree,
142673 RtreeNode *pNode,
142674 i64 iRowid,
142675 int *piIndex
142677 int ii;
142678 int nCell = NCELL(pNode);
142679 for(ii=0; ii<nCell; ii++){
142680 if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
142681 *piIndex = ii;
142682 return SQLITE_OK;
142685 return SQLITE_CORRUPT_VTAB;
142689 ** Return the index of the cell containing a pointer to node pNode
142690 ** in its parent. If pNode is the root node, return -1.
142692 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
142693 RtreeNode *pParent = pNode->pParent;
142694 if( pParent ){
142695 return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
142697 *piIndex = -1;
142698 return SQLITE_OK;
142702 ** Rtree virtual table module xNext method.
142704 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
142705 Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
142706 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
142707 int rc = SQLITE_OK;
142709 /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
142710 ** already at EOF. It is against the rules to call the xNext() method of
142711 ** a cursor that has already reached EOF.
142713 assert( pCsr->pNode );
142715 if( pCsr->iStrategy==1 ){
142716 /* This "scan" is a direct lookup by rowid. There is no next entry. */
142717 nodeRelease(pRtree, pCsr->pNode);
142718 pCsr->pNode = 0;
142719 }else{
142720 /* Move to the next entry that matches the configured constraints. */
142721 int iHeight = 0;
142722 while( pCsr->pNode ){
142723 RtreeNode *pNode = pCsr->pNode;
142724 int nCell = NCELL(pNode);
142725 for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
142726 int isEof;
142727 rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
142728 if( rc!=SQLITE_OK || !isEof ){
142729 return rc;
142732 pCsr->pNode = pNode->pParent;
142733 rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
142734 if( rc!=SQLITE_OK ){
142735 return rc;
142737 nodeReference(pCsr->pNode);
142738 nodeRelease(pRtree, pNode);
142739 iHeight++;
142743 return rc;
142747 ** Rtree virtual table module xRowid method.
142749 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
142750 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
142751 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
142753 assert(pCsr->pNode);
142754 *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
142756 return SQLITE_OK;
142760 ** Rtree virtual table module xColumn method.
142762 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
142763 Rtree *pRtree = (Rtree *)cur->pVtab;
142764 RtreeCursor *pCsr = (RtreeCursor *)cur;
142766 if( i==0 ){
142767 i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
142768 sqlite3_result_int64(ctx, iRowid);
142769 }else{
142770 RtreeCoord c;
142771 nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
142772 #ifndef SQLITE_RTREE_INT_ONLY
142773 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
142774 sqlite3_result_double(ctx, c.f);
142775 }else
142776 #endif
142778 assert( pRtree->eCoordType==RTREE_COORD_INT32 );
142779 sqlite3_result_int(ctx, c.i);
142783 return SQLITE_OK;
142787 ** Use nodeAcquire() to obtain the leaf node containing the record with
142788 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
142789 ** return SQLITE_OK. If there is no such record in the table, set
142790 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
142791 ** to zero and return an SQLite error code.
142793 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
142794 int rc;
142795 *ppLeaf = 0;
142796 sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
142797 if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
142798 i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
142799 rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
142800 sqlite3_reset(pRtree->pReadRowid);
142801 }else{
142802 rc = sqlite3_reset(pRtree->pReadRowid);
142804 return rc;
142808 ** This function is called to configure the RtreeConstraint object passed
142809 ** as the second argument for a MATCH constraint. The value passed as the
142810 ** first argument to this function is the right-hand operand to the MATCH
142811 ** operator.
142813 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
142814 RtreeMatchArg *p;
142815 sqlite3_rtree_geometry *pGeom;
142816 int nBlob;
142818 /* Check that value is actually a blob. */
142819 if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
142821 /* Check that the blob is roughly the right size. */
142822 nBlob = sqlite3_value_bytes(pValue);
142823 if( nBlob<(int)sizeof(RtreeMatchArg)
142824 || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
142826 return SQLITE_ERROR;
142829 pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
142830 sizeof(sqlite3_rtree_geometry) + nBlob
142832 if( !pGeom ) return SQLITE_NOMEM;
142833 memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
142834 p = (RtreeMatchArg *)&pGeom[1];
142836 memcpy(p, sqlite3_value_blob(pValue), nBlob);
142837 if( p->magic!=RTREE_GEOMETRY_MAGIC
142838 || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
142840 sqlite3_free(pGeom);
142841 return SQLITE_ERROR;
142844 pGeom->pContext = p->pContext;
142845 pGeom->nParam = p->nParam;
142846 pGeom->aParam = p->aParam;
142848 pCons->xGeom = p->xGeom;
142849 pCons->pGeom = pGeom;
142850 return SQLITE_OK;
142854 ** Rtree virtual table module xFilter method.
142856 static int rtreeFilter(
142857 sqlite3_vtab_cursor *pVtabCursor,
142858 int idxNum, const char *idxStr,
142859 int argc, sqlite3_value **argv
142861 Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
142862 RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
142864 RtreeNode *pRoot = 0;
142865 int ii;
142866 int rc = SQLITE_OK;
142868 rtreeReference(pRtree);
142870 freeCursorConstraints(pCsr);
142871 pCsr->iStrategy = idxNum;
142873 if( idxNum==1 ){
142874 /* Special case - lookup by rowid. */
142875 RtreeNode *pLeaf; /* Leaf on which the required cell resides */
142876 i64 iRowid = sqlite3_value_int64(argv[0]);
142877 rc = findLeafNode(pRtree, iRowid, &pLeaf);
142878 pCsr->pNode = pLeaf;
142879 if( pLeaf ){
142880 assert( rc==SQLITE_OK );
142881 rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
142883 }else{
142884 /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
142885 ** with the configured constraints.
142887 if( argc>0 ){
142888 pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
142889 pCsr->nConstraint = argc;
142890 if( !pCsr->aConstraint ){
142891 rc = SQLITE_NOMEM;
142892 }else{
142893 memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
142894 assert( (idxStr==0 && argc==0)
142895 || (idxStr && (int)strlen(idxStr)==argc*2) );
142896 for(ii=0; ii<argc; ii++){
142897 RtreeConstraint *p = &pCsr->aConstraint[ii];
142898 p->op = idxStr[ii*2];
142899 p->iCoord = idxStr[ii*2+1]-'a';
142900 if( p->op==RTREE_MATCH ){
142901 /* A MATCH operator. The right-hand-side must be a blob that
142902 ** can be cast into an RtreeMatchArg object. One created using
142903 ** an sqlite3_rtree_geometry_callback() SQL user function.
142905 rc = deserializeGeometry(argv[ii], p);
142906 if( rc!=SQLITE_OK ){
142907 break;
142909 }else{
142910 #ifdef SQLITE_RTREE_INT_ONLY
142911 p->rValue = sqlite3_value_int64(argv[ii]);
142912 #else
142913 p->rValue = sqlite3_value_double(argv[ii]);
142914 #endif
142920 if( rc==SQLITE_OK ){
142921 pCsr->pNode = 0;
142922 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
142924 if( rc==SQLITE_OK ){
142925 int isEof = 1;
142926 int nCell = NCELL(pRoot);
142927 pCsr->pNode = pRoot;
142928 for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
142929 assert( pCsr->pNode==pRoot );
142930 rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
142931 if( !isEof ){
142932 break;
142935 if( rc==SQLITE_OK && isEof ){
142936 assert( pCsr->pNode==pRoot );
142937 nodeRelease(pRtree, pRoot);
142938 pCsr->pNode = 0;
142940 assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
142944 rtreeRelease(pRtree);
142945 return rc;
142949 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
142950 ** extension is currently being used by a version of SQLite too old to
142951 ** support estimatedRows. In that case this function is a no-op.
142953 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
142954 #if SQLITE_VERSION_NUMBER>=3008002
142955 if( sqlite3_libversion_number()>=3008002 ){
142956 pIdxInfo->estimatedRows = nRow;
142958 #endif
142962 ** Rtree virtual table module xBestIndex method. There are three
142963 ** table scan strategies to choose from (in order from most to
142964 ** least desirable):
142966 ** idxNum idxStr Strategy
142967 ** ------------------------------------------------
142968 ** 1 Unused Direct lookup by rowid.
142969 ** 2 See below R-tree query or full-table scan.
142970 ** ------------------------------------------------
142972 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
142973 ** 2 is used, idxStr is formatted to contain 2 bytes for each
142974 ** constraint used. The first two bytes of idxStr correspond to
142975 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
142976 ** (argvIndex==1) etc.
142978 ** The first of each pair of bytes in idxStr identifies the constraint
142979 ** operator as follows:
142981 ** Operator Byte Value
142982 ** ----------------------
142983 ** = 0x41 ('A')
142984 ** <= 0x42 ('B')
142985 ** < 0x43 ('C')
142986 ** >= 0x44 ('D')
142987 ** > 0x45 ('E')
142988 ** MATCH 0x46 ('F')
142989 ** ----------------------
142991 ** The second of each pair of bytes identifies the coordinate column
142992 ** to which the constraint applies. The leftmost coordinate column
142993 ** is 'a', the second from the left 'b' etc.
142995 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
142996 Rtree *pRtree = (Rtree*)tab;
142997 int rc = SQLITE_OK;
142998 int ii;
142999 i64 nRow; /* Estimated rows returned by this scan */
143001 int iIdx = 0;
143002 char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
143003 memset(zIdxStr, 0, sizeof(zIdxStr));
143005 assert( pIdxInfo->idxStr==0 );
143006 for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
143007 struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
143009 if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
143010 /* We have an equality constraint on the rowid. Use strategy 1. */
143011 int jj;
143012 for(jj=0; jj<ii; jj++){
143013 pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
143014 pIdxInfo->aConstraintUsage[jj].omit = 0;
143016 pIdxInfo->idxNum = 1;
143017 pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
143018 pIdxInfo->aConstraintUsage[jj].omit = 1;
143020 /* This strategy involves a two rowid lookups on an B-Tree structures
143021 ** and then a linear search of an R-Tree node. This should be
143022 ** considered almost as quick as a direct rowid lookup (for which
143023 ** sqlite uses an internal cost of 0.0). It is expected to return
143024 ** a single row.
143026 pIdxInfo->estimatedCost = 30.0;
143027 setEstimatedRows(pIdxInfo, 1);
143028 return SQLITE_OK;
143031 if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
143032 u8 op;
143033 switch( p->op ){
143034 case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
143035 case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
143036 case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
143037 case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
143038 case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
143039 default:
143040 assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
143041 op = RTREE_MATCH;
143042 break;
143044 zIdxStr[iIdx++] = op;
143045 zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
143046 pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
143047 pIdxInfo->aConstraintUsage[ii].omit = 1;
143051 pIdxInfo->idxNum = 2;
143052 pIdxInfo->needToFreeIdxStr = 1;
143053 if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
143054 return SQLITE_NOMEM;
143057 nRow = pRtree->nRowEst / (iIdx + 1);
143058 pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
143059 setEstimatedRows(pIdxInfo, nRow);
143061 return rc;
143065 ** Return the N-dimensional volumn of the cell stored in *p.
143067 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
143068 RtreeDValue area = (RtreeDValue)1;
143069 int ii;
143070 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
143071 area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
143073 return area;
143077 ** Return the margin length of cell p. The margin length is the sum
143078 ** of the objects size in each dimension.
143080 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
143081 RtreeDValue margin = (RtreeDValue)0;
143082 int ii;
143083 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
143084 margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
143086 return margin;
143090 ** Store the union of cells p1 and p2 in p1.
143092 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
143093 int ii;
143094 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
143095 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
143096 p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
143097 p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
143099 }else{
143100 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
143101 p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
143102 p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
143108 ** Return true if the area covered by p2 is a subset of the area covered
143109 ** by p1. False otherwise.
143111 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
143112 int ii;
143113 int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
143114 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
143115 RtreeCoord *a1 = &p1->aCoord[ii];
143116 RtreeCoord *a2 = &p2->aCoord[ii];
143117 if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
143118 || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
143120 return 0;
143123 return 1;
143127 ** Return the amount cell p would grow by if it were unioned with pCell.
143129 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
143130 RtreeDValue area;
143131 RtreeCell cell;
143132 memcpy(&cell, p, sizeof(RtreeCell));
143133 area = cellArea(pRtree, &cell);
143134 cellUnion(pRtree, &cell, pCell);
143135 return (cellArea(pRtree, &cell)-area);
143138 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
143139 static RtreeDValue cellOverlap(
143140 Rtree *pRtree,
143141 RtreeCell *p,
143142 RtreeCell *aCell,
143143 int nCell,
143144 int iExclude
143146 int ii;
143147 RtreeDValue overlap = 0.0;
143148 for(ii=0; ii<nCell; ii++){
143149 #if VARIANT_RSTARTREE_CHOOSESUBTREE
143150 if( ii!=iExclude )
143151 #else
143152 assert( iExclude==-1 );
143153 UNUSED_PARAMETER(iExclude);
143154 #endif
143156 int jj;
143157 RtreeDValue o = (RtreeDValue)1;
143158 for(jj=0; jj<(pRtree->nDim*2); jj+=2){
143159 RtreeDValue x1, x2;
143161 x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
143162 x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
143164 if( x2<x1 ){
143165 o = 0.0;
143166 break;
143167 }else{
143168 o = o * (x2-x1);
143171 overlap += o;
143174 return overlap;
143176 #endif
143178 #if VARIANT_RSTARTREE_CHOOSESUBTREE
143179 static RtreeDValue cellOverlapEnlargement(
143180 Rtree *pRtree,
143181 RtreeCell *p,
143182 RtreeCell *pInsert,
143183 RtreeCell *aCell,
143184 int nCell,
143185 int iExclude
143187 RtreeDValue before, after;
143188 before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
143189 cellUnion(pRtree, p, pInsert);
143190 after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
143191 return (after-before);
143193 #endif
143197 ** This function implements the ChooseLeaf algorithm from Gutman[84].
143198 ** ChooseSubTree in r*tree terminology.
143200 static int ChooseLeaf(
143201 Rtree *pRtree, /* Rtree table */
143202 RtreeCell *pCell, /* Cell to insert into rtree */
143203 int iHeight, /* Height of sub-tree rooted at pCell */
143204 RtreeNode **ppLeaf /* OUT: Selected leaf page */
143206 int rc;
143207 int ii;
143208 RtreeNode *pNode;
143209 rc = nodeAcquire(pRtree, 1, 0, &pNode);
143211 for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
143212 int iCell;
143213 sqlite3_int64 iBest = 0;
143215 RtreeDValue fMinGrowth = 0.0;
143216 RtreeDValue fMinArea = 0.0;
143217 #if VARIANT_RSTARTREE_CHOOSESUBTREE
143218 RtreeDValue fMinOverlap = 0.0;
143219 RtreeDValue overlap;
143220 #endif
143222 int nCell = NCELL(pNode);
143223 RtreeCell cell;
143224 RtreeNode *pChild;
143226 RtreeCell *aCell = 0;
143228 #if VARIANT_RSTARTREE_CHOOSESUBTREE
143229 if( ii==(pRtree->iDepth-1) ){
143230 int jj;
143231 aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
143232 if( !aCell ){
143233 rc = SQLITE_NOMEM;
143234 nodeRelease(pRtree, pNode);
143235 pNode = 0;
143236 continue;
143238 for(jj=0; jj<nCell; jj++){
143239 nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
143242 #endif
143244 /* Select the child node which will be enlarged the least if pCell
143245 ** is inserted into it. Resolve ties by choosing the entry with
143246 ** the smallest area.
143248 for(iCell=0; iCell<nCell; iCell++){
143249 int bBest = 0;
143250 RtreeDValue growth;
143251 RtreeDValue area;
143252 nodeGetCell(pRtree, pNode, iCell, &cell);
143253 growth = cellGrowth(pRtree, &cell, pCell);
143254 area = cellArea(pRtree, &cell);
143256 #if VARIANT_RSTARTREE_CHOOSESUBTREE
143257 if( ii==(pRtree->iDepth-1) ){
143258 overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
143259 }else{
143260 overlap = 0.0;
143262 if( (iCell==0)
143263 || (overlap<fMinOverlap)
143264 || (overlap==fMinOverlap && growth<fMinGrowth)
143265 || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
143267 bBest = 1;
143268 fMinOverlap = overlap;
143270 #else
143271 if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
143272 bBest = 1;
143274 #endif
143275 if( bBest ){
143276 fMinGrowth = growth;
143277 fMinArea = area;
143278 iBest = cell.iRowid;
143282 sqlite3_free(aCell);
143283 rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
143284 nodeRelease(pRtree, pNode);
143285 pNode = pChild;
143288 *ppLeaf = pNode;
143289 return rc;
143293 ** A cell with the same content as pCell has just been inserted into
143294 ** the node pNode. This function updates the bounding box cells in
143295 ** all ancestor elements.
143297 static int AdjustTree(
143298 Rtree *pRtree, /* Rtree table */
143299 RtreeNode *pNode, /* Adjust ancestry of this node. */
143300 RtreeCell *pCell /* This cell was just inserted */
143302 RtreeNode *p = pNode;
143303 while( p->pParent ){
143304 RtreeNode *pParent = p->pParent;
143305 RtreeCell cell;
143306 int iCell;
143308 if( nodeParentIndex(pRtree, p, &iCell) ){
143309 return SQLITE_CORRUPT_VTAB;
143312 nodeGetCell(pRtree, pParent, iCell, &cell);
143313 if( !cellContains(pRtree, &cell, pCell) ){
143314 cellUnion(pRtree, &cell, pCell);
143315 nodeOverwriteCell(pRtree, pParent, &cell, iCell);
143318 p = pParent;
143320 return SQLITE_OK;
143324 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
143326 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
143327 sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
143328 sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
143329 sqlite3_step(pRtree->pWriteRowid);
143330 return sqlite3_reset(pRtree->pWriteRowid);
143334 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
143336 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
143337 sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
143338 sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
143339 sqlite3_step(pRtree->pWriteParent);
143340 return sqlite3_reset(pRtree->pWriteParent);
143343 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
143345 #if VARIANT_GUTTMAN_LINEAR_SPLIT
143347 ** Implementation of the linear variant of the PickNext() function from
143348 ** Guttman[84].
143350 static RtreeCell *LinearPickNext(
143351 Rtree *pRtree,
143352 RtreeCell *aCell,
143353 int nCell,
143354 RtreeCell *pLeftBox,
143355 RtreeCell *pRightBox,
143356 int *aiUsed
143358 int ii;
143359 for(ii=0; aiUsed[ii]; ii++);
143360 aiUsed[ii] = 1;
143361 return &aCell[ii];
143365 ** Implementation of the linear variant of the PickSeeds() function from
143366 ** Guttman[84].
143368 static void LinearPickSeeds(
143369 Rtree *pRtree,
143370 RtreeCell *aCell,
143371 int nCell,
143372 int *piLeftSeed,
143373 int *piRightSeed
143375 int i;
143376 int iLeftSeed = 0;
143377 int iRightSeed = 1;
143378 RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
143380 /* Pick two "seed" cells from the array of cells. The algorithm used
143381 ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
143382 ** indices of the two seed cells in the array are stored in local
143383 ** variables iLeftSeek and iRightSeed.
143385 for(i=0; i<pRtree->nDim; i++){
143386 RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
143387 RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
143388 RtreeDValue x3 = x1;
143389 RtreeDValue x4 = x2;
143390 int jj;
143392 int iCellLeft = 0;
143393 int iCellRight = 0;
143395 for(jj=1; jj<nCell; jj++){
143396 RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
143397 RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
143399 if( left<x1 ) x1 = left;
143400 if( right>x4 ) x4 = right;
143401 if( left>x3 ){
143402 x3 = left;
143403 iCellRight = jj;
143405 if( right<x2 ){
143406 x2 = right;
143407 iCellLeft = jj;
143411 if( x4!=x1 ){
143412 RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
143413 if( normalwidth>maxNormalInnerWidth ){
143414 iLeftSeed = iCellLeft;
143415 iRightSeed = iCellRight;
143420 *piLeftSeed = iLeftSeed;
143421 *piRightSeed = iRightSeed;
143423 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
143425 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
143427 ** Implementation of the quadratic variant of the PickNext() function from
143428 ** Guttman[84].
143430 static RtreeCell *QuadraticPickNext(
143431 Rtree *pRtree,
143432 RtreeCell *aCell,
143433 int nCell,
143434 RtreeCell *pLeftBox,
143435 RtreeCell *pRightBox,
143436 int *aiUsed
143438 #define FABS(a) ((a)<0.0?-1.0*(a):(a))
143440 int iSelect = -1;
143441 RtreeDValue fDiff;
143442 int ii;
143443 for(ii=0; ii<nCell; ii++){
143444 if( aiUsed[ii]==0 ){
143445 RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
143446 RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
143447 RtreeDValue diff = FABS(right-left);
143448 if( iSelect<0 || diff>fDiff ){
143449 fDiff = diff;
143450 iSelect = ii;
143454 aiUsed[iSelect] = 1;
143455 return &aCell[iSelect];
143459 ** Implementation of the quadratic variant of the PickSeeds() function from
143460 ** Guttman[84].
143462 static void QuadraticPickSeeds(
143463 Rtree *pRtree,
143464 RtreeCell *aCell,
143465 int nCell,
143466 int *piLeftSeed,
143467 int *piRightSeed
143469 int ii;
143470 int jj;
143472 int iLeftSeed = 0;
143473 int iRightSeed = 1;
143474 RtreeDValue fWaste = 0.0;
143476 for(ii=0; ii<nCell; ii++){
143477 for(jj=ii+1; jj<nCell; jj++){
143478 RtreeDValue right = cellArea(pRtree, &aCell[jj]);
143479 RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
143480 RtreeDValue waste = growth - right;
143482 if( waste>fWaste ){
143483 iLeftSeed = ii;
143484 iRightSeed = jj;
143485 fWaste = waste;
143490 *piLeftSeed = iLeftSeed;
143491 *piRightSeed = iRightSeed;
143493 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
143496 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
143497 ** nIdx. The aIdx array contains the set of integers from 0 to
143498 ** (nIdx-1) in no particular order. This function sorts the values
143499 ** in aIdx according to the indexed values in aDistance. For
143500 ** example, assuming the inputs:
143502 ** aIdx = { 0, 1, 2, 3 }
143503 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
143505 ** this function sets the aIdx array to contain:
143507 ** aIdx = { 0, 1, 2, 3 }
143509 ** The aSpare array is used as temporary working space by the
143510 ** sorting algorithm.
143512 static void SortByDistance(
143513 int *aIdx,
143514 int nIdx,
143515 RtreeDValue *aDistance,
143516 int *aSpare
143518 if( nIdx>1 ){
143519 int iLeft = 0;
143520 int iRight = 0;
143522 int nLeft = nIdx/2;
143523 int nRight = nIdx-nLeft;
143524 int *aLeft = aIdx;
143525 int *aRight = &aIdx[nLeft];
143527 SortByDistance(aLeft, nLeft, aDistance, aSpare);
143528 SortByDistance(aRight, nRight, aDistance, aSpare);
143530 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
143531 aLeft = aSpare;
143533 while( iLeft<nLeft || iRight<nRight ){
143534 if( iLeft==nLeft ){
143535 aIdx[iLeft+iRight] = aRight[iRight];
143536 iRight++;
143537 }else if( iRight==nRight ){
143538 aIdx[iLeft+iRight] = aLeft[iLeft];
143539 iLeft++;
143540 }else{
143541 RtreeDValue fLeft = aDistance[aLeft[iLeft]];
143542 RtreeDValue fRight = aDistance[aRight[iRight]];
143543 if( fLeft<fRight ){
143544 aIdx[iLeft+iRight] = aLeft[iLeft];
143545 iLeft++;
143546 }else{
143547 aIdx[iLeft+iRight] = aRight[iRight];
143548 iRight++;
143553 #if 0
143554 /* Check that the sort worked */
143556 int jj;
143557 for(jj=1; jj<nIdx; jj++){
143558 RtreeDValue left = aDistance[aIdx[jj-1]];
143559 RtreeDValue right = aDistance[aIdx[jj]];
143560 assert( left<=right );
143563 #endif
143568 ** Arguments aIdx, aCell and aSpare all point to arrays of size
143569 ** nIdx. The aIdx array contains the set of integers from 0 to
143570 ** (nIdx-1) in no particular order. This function sorts the values
143571 ** in aIdx according to dimension iDim of the cells in aCell. The
143572 ** minimum value of dimension iDim is considered first, the
143573 ** maximum used to break ties.
143575 ** The aSpare array is used as temporary working space by the
143576 ** sorting algorithm.
143578 static void SortByDimension(
143579 Rtree *pRtree,
143580 int *aIdx,
143581 int nIdx,
143582 int iDim,
143583 RtreeCell *aCell,
143584 int *aSpare
143586 if( nIdx>1 ){
143588 int iLeft = 0;
143589 int iRight = 0;
143591 int nLeft = nIdx/2;
143592 int nRight = nIdx-nLeft;
143593 int *aLeft = aIdx;
143594 int *aRight = &aIdx[nLeft];
143596 SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
143597 SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
143599 memcpy(aSpare, aLeft, sizeof(int)*nLeft);
143600 aLeft = aSpare;
143601 while( iLeft<nLeft || iRight<nRight ){
143602 RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
143603 RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
143604 RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
143605 RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
143606 if( (iLeft!=nLeft) && ((iRight==nRight)
143607 || (xleft1<xright1)
143608 || (xleft1==xright1 && xleft2<xright2)
143610 aIdx[iLeft+iRight] = aLeft[iLeft];
143611 iLeft++;
143612 }else{
143613 aIdx[iLeft+iRight] = aRight[iRight];
143614 iRight++;
143618 #if 0
143619 /* Check that the sort worked */
143621 int jj;
143622 for(jj=1; jj<nIdx; jj++){
143623 RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
143624 RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
143625 RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
143626 RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
143627 assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
143630 #endif
143634 #if VARIANT_RSTARTREE_SPLIT
143636 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
143638 static int splitNodeStartree(
143639 Rtree *pRtree,
143640 RtreeCell *aCell,
143641 int nCell,
143642 RtreeNode *pLeft,
143643 RtreeNode *pRight,
143644 RtreeCell *pBboxLeft,
143645 RtreeCell *pBboxRight
143647 int **aaSorted;
143648 int *aSpare;
143649 int ii;
143651 int iBestDim = 0;
143652 int iBestSplit = 0;
143653 RtreeDValue fBestMargin = 0.0;
143655 int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
143657 aaSorted = (int **)sqlite3_malloc(nByte);
143658 if( !aaSorted ){
143659 return SQLITE_NOMEM;
143662 aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
143663 memset(aaSorted, 0, nByte);
143664 for(ii=0; ii<pRtree->nDim; ii++){
143665 int jj;
143666 aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
143667 for(jj=0; jj<nCell; jj++){
143668 aaSorted[ii][jj] = jj;
143670 SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
143673 for(ii=0; ii<pRtree->nDim; ii++){
143674 RtreeDValue margin = 0.0;
143675 RtreeDValue fBestOverlap = 0.0;
143676 RtreeDValue fBestArea = 0.0;
143677 int iBestLeft = 0;
143678 int nLeft;
143681 nLeft=RTREE_MINCELLS(pRtree);
143682 nLeft<=(nCell-RTREE_MINCELLS(pRtree));
143683 nLeft++
143685 RtreeCell left;
143686 RtreeCell right;
143687 int kk;
143688 RtreeDValue overlap;
143689 RtreeDValue area;
143691 memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
143692 memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
143693 for(kk=1; kk<(nCell-1); kk++){
143694 if( kk<nLeft ){
143695 cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
143696 }else{
143697 cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
143700 margin += cellMargin(pRtree, &left);
143701 margin += cellMargin(pRtree, &right);
143702 overlap = cellOverlap(pRtree, &left, &right, 1, -1);
143703 area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
143704 if( (nLeft==RTREE_MINCELLS(pRtree))
143705 || (overlap<fBestOverlap)
143706 || (overlap==fBestOverlap && area<fBestArea)
143708 iBestLeft = nLeft;
143709 fBestOverlap = overlap;
143710 fBestArea = area;
143714 if( ii==0 || margin<fBestMargin ){
143715 iBestDim = ii;
143716 fBestMargin = margin;
143717 iBestSplit = iBestLeft;
143721 memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
143722 memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
143723 for(ii=0; ii<nCell; ii++){
143724 RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
143725 RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
143726 RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
143727 nodeInsertCell(pRtree, pTarget, pCell);
143728 cellUnion(pRtree, pBbox, pCell);
143731 sqlite3_free(aaSorted);
143732 return SQLITE_OK;
143734 #endif
143736 #if VARIANT_GUTTMAN_SPLIT
143738 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
143740 static int splitNodeGuttman(
143741 Rtree *pRtree,
143742 RtreeCell *aCell,
143743 int nCell,
143744 RtreeNode *pLeft,
143745 RtreeNode *pRight,
143746 RtreeCell *pBboxLeft,
143747 RtreeCell *pBboxRight
143749 int iLeftSeed = 0;
143750 int iRightSeed = 1;
143751 int *aiUsed;
143752 int i;
143754 aiUsed = sqlite3_malloc(sizeof(int)*nCell);
143755 if( !aiUsed ){
143756 return SQLITE_NOMEM;
143758 memset(aiUsed, 0, sizeof(int)*nCell);
143760 PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
143762 memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
143763 memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
143764 nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
143765 nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
143766 aiUsed[iLeftSeed] = 1;
143767 aiUsed[iRightSeed] = 1;
143769 for(i=nCell-2; i>0; i--){
143770 RtreeCell *pNext;
143771 pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
143772 RtreeDValue diff =
143773 cellGrowth(pRtree, pBboxLeft, pNext) -
143774 cellGrowth(pRtree, pBboxRight, pNext)
143776 if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
143777 || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
143779 nodeInsertCell(pRtree, pRight, pNext);
143780 cellUnion(pRtree, pBboxRight, pNext);
143781 }else{
143782 nodeInsertCell(pRtree, pLeft, pNext);
143783 cellUnion(pRtree, pBboxLeft, pNext);
143787 sqlite3_free(aiUsed);
143788 return SQLITE_OK;
143790 #endif
143792 static int updateMapping(
143793 Rtree *pRtree,
143794 i64 iRowid,
143795 RtreeNode *pNode,
143796 int iHeight
143798 int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
143799 xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
143800 if( iHeight>0 ){
143801 RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
143802 if( pChild ){
143803 nodeRelease(pRtree, pChild->pParent);
143804 nodeReference(pNode);
143805 pChild->pParent = pNode;
143808 return xSetMapping(pRtree, iRowid, pNode->iNode);
143811 static int SplitNode(
143812 Rtree *pRtree,
143813 RtreeNode *pNode,
143814 RtreeCell *pCell,
143815 int iHeight
143817 int i;
143818 int newCellIsRight = 0;
143820 int rc = SQLITE_OK;
143821 int nCell = NCELL(pNode);
143822 RtreeCell *aCell;
143823 int *aiUsed;
143825 RtreeNode *pLeft = 0;
143826 RtreeNode *pRight = 0;
143828 RtreeCell leftbbox;
143829 RtreeCell rightbbox;
143831 /* Allocate an array and populate it with a copy of pCell and
143832 ** all cells from node pLeft. Then zero the original node.
143834 aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
143835 if( !aCell ){
143836 rc = SQLITE_NOMEM;
143837 goto splitnode_out;
143839 aiUsed = (int *)&aCell[nCell+1];
143840 memset(aiUsed, 0, sizeof(int)*(nCell+1));
143841 for(i=0; i<nCell; i++){
143842 nodeGetCell(pRtree, pNode, i, &aCell[i]);
143844 nodeZero(pRtree, pNode);
143845 memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
143846 nCell++;
143848 if( pNode->iNode==1 ){
143849 pRight = nodeNew(pRtree, pNode);
143850 pLeft = nodeNew(pRtree, pNode);
143851 pRtree->iDepth++;
143852 pNode->isDirty = 1;
143853 writeInt16(pNode->zData, pRtree->iDepth);
143854 }else{
143855 pLeft = pNode;
143856 pRight = nodeNew(pRtree, pLeft->pParent);
143857 nodeReference(pLeft);
143860 if( !pLeft || !pRight ){
143861 rc = SQLITE_NOMEM;
143862 goto splitnode_out;
143865 memset(pLeft->zData, 0, pRtree->iNodeSize);
143866 memset(pRight->zData, 0, pRtree->iNodeSize);
143868 rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
143869 if( rc!=SQLITE_OK ){
143870 goto splitnode_out;
143873 /* Ensure both child nodes have node numbers assigned to them by calling
143874 ** nodeWrite(). Node pRight always needs a node number, as it was created
143875 ** by nodeNew() above. But node pLeft sometimes already has a node number.
143876 ** In this case avoid the all to nodeWrite().
143878 if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
143879 || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
143881 goto splitnode_out;
143884 rightbbox.iRowid = pRight->iNode;
143885 leftbbox.iRowid = pLeft->iNode;
143887 if( pNode->iNode==1 ){
143888 rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
143889 if( rc!=SQLITE_OK ){
143890 goto splitnode_out;
143892 }else{
143893 RtreeNode *pParent = pLeft->pParent;
143894 int iCell;
143895 rc = nodeParentIndex(pRtree, pLeft, &iCell);
143896 if( rc==SQLITE_OK ){
143897 nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
143898 rc = AdjustTree(pRtree, pParent, &leftbbox);
143900 if( rc!=SQLITE_OK ){
143901 goto splitnode_out;
143904 if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
143905 goto splitnode_out;
143908 for(i=0; i<NCELL(pRight); i++){
143909 i64 iRowid = nodeGetRowid(pRtree, pRight, i);
143910 rc = updateMapping(pRtree, iRowid, pRight, iHeight);
143911 if( iRowid==pCell->iRowid ){
143912 newCellIsRight = 1;
143914 if( rc!=SQLITE_OK ){
143915 goto splitnode_out;
143918 if( pNode->iNode==1 ){
143919 for(i=0; i<NCELL(pLeft); i++){
143920 i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
143921 rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
143922 if( rc!=SQLITE_OK ){
143923 goto splitnode_out;
143926 }else if( newCellIsRight==0 ){
143927 rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
143930 if( rc==SQLITE_OK ){
143931 rc = nodeRelease(pRtree, pRight);
143932 pRight = 0;
143934 if( rc==SQLITE_OK ){
143935 rc = nodeRelease(pRtree, pLeft);
143936 pLeft = 0;
143939 splitnode_out:
143940 nodeRelease(pRtree, pRight);
143941 nodeRelease(pRtree, pLeft);
143942 sqlite3_free(aCell);
143943 return rc;
143947 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
143948 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
143949 ** the pLeaf->pParent chain all the way up to the root node.
143951 ** This operation is required when a row is deleted (or updated - an update
143952 ** is implemented as a delete followed by an insert). SQLite provides the
143953 ** rowid of the row to delete, which can be used to find the leaf on which
143954 ** the entry resides (argument pLeaf). Once the leaf is located, this
143955 ** function is called to determine its ancestry.
143957 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
143958 int rc = SQLITE_OK;
143959 RtreeNode *pChild = pLeaf;
143960 while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
143961 int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
143962 sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
143963 rc = sqlite3_step(pRtree->pReadParent);
143964 if( rc==SQLITE_ROW ){
143965 RtreeNode *pTest; /* Used to test for reference loops */
143966 i64 iNode; /* Node number of parent node */
143968 /* Before setting pChild->pParent, test that we are not creating a
143969 ** loop of references (as we would if, say, pChild==pParent). We don't
143970 ** want to do this as it leads to a memory leak when trying to delete
143971 ** the referenced counted node structures.
143973 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
143974 for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
143975 if( !pTest ){
143976 rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
143979 rc = sqlite3_reset(pRtree->pReadParent);
143980 if( rc==SQLITE_OK ) rc = rc2;
143981 if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
143982 pChild = pChild->pParent;
143984 return rc;
143987 static int deleteCell(Rtree *, RtreeNode *, int, int);
143989 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
143990 int rc;
143991 int rc2;
143992 RtreeNode *pParent = 0;
143993 int iCell;
143995 assert( pNode->nRef==1 );
143997 /* Remove the entry in the parent cell. */
143998 rc = nodeParentIndex(pRtree, pNode, &iCell);
143999 if( rc==SQLITE_OK ){
144000 pParent = pNode->pParent;
144001 pNode->pParent = 0;
144002 rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
144004 rc2 = nodeRelease(pRtree, pParent);
144005 if( rc==SQLITE_OK ){
144006 rc = rc2;
144008 if( rc!=SQLITE_OK ){
144009 return rc;
144012 /* Remove the xxx_node entry. */
144013 sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
144014 sqlite3_step(pRtree->pDeleteNode);
144015 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
144016 return rc;
144019 /* Remove the xxx_parent entry. */
144020 sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
144021 sqlite3_step(pRtree->pDeleteParent);
144022 if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
144023 return rc;
144026 /* Remove the node from the in-memory hash table and link it into
144027 ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
144029 nodeHashDelete(pRtree, pNode);
144030 pNode->iNode = iHeight;
144031 pNode->pNext = pRtree->pDeleted;
144032 pNode->nRef++;
144033 pRtree->pDeleted = pNode;
144035 return SQLITE_OK;
144038 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
144039 RtreeNode *pParent = pNode->pParent;
144040 int rc = SQLITE_OK;
144041 if( pParent ){
144042 int ii;
144043 int nCell = NCELL(pNode);
144044 RtreeCell box; /* Bounding box for pNode */
144045 nodeGetCell(pRtree, pNode, 0, &box);
144046 for(ii=1; ii<nCell; ii++){
144047 RtreeCell cell;
144048 nodeGetCell(pRtree, pNode, ii, &cell);
144049 cellUnion(pRtree, &box, &cell);
144051 box.iRowid = pNode->iNode;
144052 rc = nodeParentIndex(pRtree, pNode, &ii);
144053 if( rc==SQLITE_OK ){
144054 nodeOverwriteCell(pRtree, pParent, &box, ii);
144055 rc = fixBoundingBox(pRtree, pParent);
144058 return rc;
144062 ** Delete the cell at index iCell of node pNode. After removing the
144063 ** cell, adjust the r-tree data structure if required.
144065 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
144066 RtreeNode *pParent;
144067 int rc;
144069 if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
144070 return rc;
144073 /* Remove the cell from the node. This call just moves bytes around
144074 ** the in-memory node image, so it cannot fail.
144076 nodeDeleteCell(pRtree, pNode, iCell);
144078 /* If the node is not the tree root and now has less than the minimum
144079 ** number of cells, remove it from the tree. Otherwise, update the
144080 ** cell in the parent node so that it tightly contains the updated
144081 ** node.
144083 pParent = pNode->pParent;
144084 assert( pParent || pNode->iNode==1 );
144085 if( pParent ){
144086 if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
144087 rc = removeNode(pRtree, pNode, iHeight);
144088 }else{
144089 rc = fixBoundingBox(pRtree, pNode);
144093 return rc;
144096 static int Reinsert(
144097 Rtree *pRtree,
144098 RtreeNode *pNode,
144099 RtreeCell *pCell,
144100 int iHeight
144102 int *aOrder;
144103 int *aSpare;
144104 RtreeCell *aCell;
144105 RtreeDValue *aDistance;
144106 int nCell;
144107 RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
144108 int iDim;
144109 int ii;
144110 int rc = SQLITE_OK;
144111 int n;
144113 memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
144115 nCell = NCELL(pNode)+1;
144116 n = (nCell+1)&(~1);
144118 /* Allocate the buffers used by this operation. The allocation is
144119 ** relinquished before this function returns.
144121 aCell = (RtreeCell *)sqlite3_malloc(n * (
144122 sizeof(RtreeCell) + /* aCell array */
144123 sizeof(int) + /* aOrder array */
144124 sizeof(int) + /* aSpare array */
144125 sizeof(RtreeDValue) /* aDistance array */
144127 if( !aCell ){
144128 return SQLITE_NOMEM;
144130 aOrder = (int *)&aCell[n];
144131 aSpare = (int *)&aOrder[n];
144132 aDistance = (RtreeDValue *)&aSpare[n];
144134 for(ii=0; ii<nCell; ii++){
144135 if( ii==(nCell-1) ){
144136 memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
144137 }else{
144138 nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
144140 aOrder[ii] = ii;
144141 for(iDim=0; iDim<pRtree->nDim; iDim++){
144142 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
144143 aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
144146 for(iDim=0; iDim<pRtree->nDim; iDim++){
144147 aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
144150 for(ii=0; ii<nCell; ii++){
144151 aDistance[ii] = 0.0;
144152 for(iDim=0; iDim<pRtree->nDim; iDim++){
144153 RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
144154 DCOORD(aCell[ii].aCoord[iDim*2]));
144155 aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
144159 SortByDistance(aOrder, nCell, aDistance, aSpare);
144160 nodeZero(pRtree, pNode);
144162 for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
144163 RtreeCell *p = &aCell[aOrder[ii]];
144164 nodeInsertCell(pRtree, pNode, p);
144165 if( p->iRowid==pCell->iRowid ){
144166 if( iHeight==0 ){
144167 rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
144168 }else{
144169 rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
144173 if( rc==SQLITE_OK ){
144174 rc = fixBoundingBox(pRtree, pNode);
144176 for(; rc==SQLITE_OK && ii<nCell; ii++){
144177 /* Find a node to store this cell in. pNode->iNode currently contains
144178 ** the height of the sub-tree headed by the cell.
144180 RtreeNode *pInsert;
144181 RtreeCell *p = &aCell[aOrder[ii]];
144182 rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
144183 if( rc==SQLITE_OK ){
144184 int rc2;
144185 rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
144186 rc2 = nodeRelease(pRtree, pInsert);
144187 if( rc==SQLITE_OK ){
144188 rc = rc2;
144193 sqlite3_free(aCell);
144194 return rc;
144198 ** Insert cell pCell into node pNode. Node pNode is the head of a
144199 ** subtree iHeight high (leaf nodes have iHeight==0).
144201 static int rtreeInsertCell(
144202 Rtree *pRtree,
144203 RtreeNode *pNode,
144204 RtreeCell *pCell,
144205 int iHeight
144207 int rc = SQLITE_OK;
144208 if( iHeight>0 ){
144209 RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
144210 if( pChild ){
144211 nodeRelease(pRtree, pChild->pParent);
144212 nodeReference(pNode);
144213 pChild->pParent = pNode;
144216 if( nodeInsertCell(pRtree, pNode, pCell) ){
144217 #if VARIANT_RSTARTREE_REINSERT
144218 if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
144219 rc = SplitNode(pRtree, pNode, pCell, iHeight);
144220 }else{
144221 pRtree->iReinsertHeight = iHeight;
144222 rc = Reinsert(pRtree, pNode, pCell, iHeight);
144224 #else
144225 rc = SplitNode(pRtree, pNode, pCell, iHeight);
144226 #endif
144227 }else{
144228 rc = AdjustTree(pRtree, pNode, pCell);
144229 if( rc==SQLITE_OK ){
144230 if( iHeight==0 ){
144231 rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
144232 }else{
144233 rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
144237 return rc;
144240 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
144241 int ii;
144242 int rc = SQLITE_OK;
144243 int nCell = NCELL(pNode);
144245 for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
144246 RtreeNode *pInsert;
144247 RtreeCell cell;
144248 nodeGetCell(pRtree, pNode, ii, &cell);
144250 /* Find a node to store this cell in. pNode->iNode currently contains
144251 ** the height of the sub-tree headed by the cell.
144253 rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
144254 if( rc==SQLITE_OK ){
144255 int rc2;
144256 rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
144257 rc2 = nodeRelease(pRtree, pInsert);
144258 if( rc==SQLITE_OK ){
144259 rc = rc2;
144263 return rc;
144267 ** Select a currently unused rowid for a new r-tree record.
144269 static int newRowid(Rtree *pRtree, i64 *piRowid){
144270 int rc;
144271 sqlite3_bind_null(pRtree->pWriteRowid, 1);
144272 sqlite3_bind_null(pRtree->pWriteRowid, 2);
144273 sqlite3_step(pRtree->pWriteRowid);
144274 rc = sqlite3_reset(pRtree->pWriteRowid);
144275 *piRowid = sqlite3_last_insert_rowid(pRtree->db);
144276 return rc;
144280 ** Remove the entry with rowid=iDelete from the r-tree structure.
144282 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
144283 int rc; /* Return code */
144284 RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
144285 int iCell; /* Index of iDelete cell in pLeaf */
144286 RtreeNode *pRoot; /* Root node of rtree structure */
144289 /* Obtain a reference to the root node to initialize Rtree.iDepth */
144290 rc = nodeAcquire(pRtree, 1, 0, &pRoot);
144292 /* Obtain a reference to the leaf node that contains the entry
144293 ** about to be deleted.
144295 if( rc==SQLITE_OK ){
144296 rc = findLeafNode(pRtree, iDelete, &pLeaf);
144299 /* Delete the cell in question from the leaf node. */
144300 if( rc==SQLITE_OK ){
144301 int rc2;
144302 rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
144303 if( rc==SQLITE_OK ){
144304 rc = deleteCell(pRtree, pLeaf, iCell, 0);
144306 rc2 = nodeRelease(pRtree, pLeaf);
144307 if( rc==SQLITE_OK ){
144308 rc = rc2;
144312 /* Delete the corresponding entry in the <rtree>_rowid table. */
144313 if( rc==SQLITE_OK ){
144314 sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
144315 sqlite3_step(pRtree->pDeleteRowid);
144316 rc = sqlite3_reset(pRtree->pDeleteRowid);
144319 /* Check if the root node now has exactly one child. If so, remove
144320 ** it, schedule the contents of the child for reinsertion and
144321 ** reduce the tree height by one.
144323 ** This is equivalent to copying the contents of the child into
144324 ** the root node (the operation that Gutman's paper says to perform
144325 ** in this scenario).
144327 if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
144328 int rc2;
144329 RtreeNode *pChild;
144330 i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
144331 rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
144332 if( rc==SQLITE_OK ){
144333 rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
144335 rc2 = nodeRelease(pRtree, pChild);
144336 if( rc==SQLITE_OK ) rc = rc2;
144337 if( rc==SQLITE_OK ){
144338 pRtree->iDepth--;
144339 writeInt16(pRoot->zData, pRtree->iDepth);
144340 pRoot->isDirty = 1;
144344 /* Re-insert the contents of any underfull nodes removed from the tree. */
144345 for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
144346 if( rc==SQLITE_OK ){
144347 rc = reinsertNodeContent(pRtree, pLeaf);
144349 pRtree->pDeleted = pLeaf->pNext;
144350 sqlite3_free(pLeaf);
144353 /* Release the reference to the root node. */
144354 if( rc==SQLITE_OK ){
144355 rc = nodeRelease(pRtree, pRoot);
144356 }else{
144357 nodeRelease(pRtree, pRoot);
144360 return rc;
144364 ** Rounding constants for float->double conversion.
144366 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
144367 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
144369 #if !defined(SQLITE_RTREE_INT_ONLY)
144371 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
144372 ** while taking care to round toward negative or positive, respectively.
144374 static RtreeValue rtreeValueDown(sqlite3_value *v){
144375 double d = sqlite3_value_double(v);
144376 float f = (float)d;
144377 if( f>d ){
144378 f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
144380 return f;
144382 static RtreeValue rtreeValueUp(sqlite3_value *v){
144383 double d = sqlite3_value_double(v);
144384 float f = (float)d;
144385 if( f<d ){
144386 f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
144388 return f;
144390 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
144394 ** The xUpdate method for rtree module virtual tables.
144396 static int rtreeUpdate(
144397 sqlite3_vtab *pVtab,
144398 int nData,
144399 sqlite3_value **azData,
144400 sqlite_int64 *pRowid
144402 Rtree *pRtree = (Rtree *)pVtab;
144403 int rc = SQLITE_OK;
144404 RtreeCell cell; /* New cell to insert if nData>1 */
144405 int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
144407 rtreeReference(pRtree);
144408 assert(nData>=1);
144410 /* Constraint handling. A write operation on an r-tree table may return
144411 ** SQLITE_CONSTRAINT for two reasons:
144413 ** 1. A duplicate rowid value, or
144414 ** 2. The supplied data violates the "x2>=x1" constraint.
144416 ** In the first case, if the conflict-handling mode is REPLACE, then
144417 ** the conflicting row can be removed before proceeding. In the second
144418 ** case, SQLITE_CONSTRAINT must be returned regardless of the
144419 ** conflict-handling mode specified by the user.
144421 if( nData>1 ){
144422 int ii;
144424 /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
144425 assert( nData==(pRtree->nDim*2 + 3) );
144426 #ifndef SQLITE_RTREE_INT_ONLY
144427 if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
144428 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
144429 cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
144430 cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
144431 if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
144432 rc = SQLITE_CONSTRAINT;
144433 goto constraint;
144436 }else
144437 #endif
144439 for(ii=0; ii<(pRtree->nDim*2); ii+=2){
144440 cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
144441 cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
144442 if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
144443 rc = SQLITE_CONSTRAINT;
144444 goto constraint;
144449 /* If a rowid value was supplied, check if it is already present in
144450 ** the table. If so, the constraint has failed. */
144451 if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
144452 cell.iRowid = sqlite3_value_int64(azData[2]);
144453 if( sqlite3_value_type(azData[0])==SQLITE_NULL
144454 || sqlite3_value_int64(azData[0])!=cell.iRowid
144456 int steprc;
144457 sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
144458 steprc = sqlite3_step(pRtree->pReadRowid);
144459 rc = sqlite3_reset(pRtree->pReadRowid);
144460 if( SQLITE_ROW==steprc ){
144461 if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
144462 rc = rtreeDeleteRowid(pRtree, cell.iRowid);
144463 }else{
144464 rc = SQLITE_CONSTRAINT;
144465 goto constraint;
144469 bHaveRowid = 1;
144473 /* If azData[0] is not an SQL NULL value, it is the rowid of a
144474 ** record to delete from the r-tree table. The following block does
144475 ** just that.
144477 if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
144478 rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
144481 /* If the azData[] array contains more than one element, elements
144482 ** (azData[2]..azData[argc-1]) contain a new record to insert into
144483 ** the r-tree structure.
144485 if( rc==SQLITE_OK && nData>1 ){
144486 /* Insert the new record into the r-tree */
144487 RtreeNode *pLeaf = 0;
144489 /* Figure out the rowid of the new row. */
144490 if( bHaveRowid==0 ){
144491 rc = newRowid(pRtree, &cell.iRowid);
144493 *pRowid = cell.iRowid;
144495 if( rc==SQLITE_OK ){
144496 rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
144498 if( rc==SQLITE_OK ){
144499 int rc2;
144500 pRtree->iReinsertHeight = -1;
144501 rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
144502 rc2 = nodeRelease(pRtree, pLeaf);
144503 if( rc==SQLITE_OK ){
144504 rc = rc2;
144509 constraint:
144510 rtreeRelease(pRtree);
144511 return rc;
144515 ** The xRename method for rtree module virtual tables.
144517 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
144518 Rtree *pRtree = (Rtree *)pVtab;
144519 int rc = SQLITE_NOMEM;
144520 char *zSql = sqlite3_mprintf(
144521 "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
144522 "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
144523 "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
144524 , pRtree->zDb, pRtree->zName, zNewName
144525 , pRtree->zDb, pRtree->zName, zNewName
144526 , pRtree->zDb, pRtree->zName, zNewName
144528 if( zSql ){
144529 rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
144530 sqlite3_free(zSql);
144532 return rc;
144536 ** This function populates the pRtree->nRowEst variable with an estimate
144537 ** of the number of rows in the virtual table. If possible, this is based
144538 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
144540 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
144541 const char *zSql = "SELECT stat FROM sqlite_stat1 WHERE tbl= ? || '_rowid'";
144542 sqlite3_stmt *p;
144543 int rc;
144544 i64 nRow = 0;
144546 rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
144547 if( rc==SQLITE_OK ){
144548 sqlite3_bind_text(p, 1, pRtree->zName, -1, SQLITE_STATIC);
144549 if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
144550 rc = sqlite3_finalize(p);
144551 }else if( rc!=SQLITE_NOMEM ){
144552 rc = SQLITE_OK;
144555 if( rc==SQLITE_OK ){
144556 if( nRow==0 ){
144557 pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
144558 }else{
144559 pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
144563 return rc;
144566 static sqlite3_module rtreeModule = {
144567 0, /* iVersion */
144568 rtreeCreate, /* xCreate - create a table */
144569 rtreeConnect, /* xConnect - connect to an existing table */
144570 rtreeBestIndex, /* xBestIndex - Determine search strategy */
144571 rtreeDisconnect, /* xDisconnect - Disconnect from a table */
144572 rtreeDestroy, /* xDestroy - Drop a table */
144573 rtreeOpen, /* xOpen - open a cursor */
144574 rtreeClose, /* xClose - close a cursor */
144575 rtreeFilter, /* xFilter - configure scan constraints */
144576 rtreeNext, /* xNext - advance a cursor */
144577 rtreeEof, /* xEof */
144578 rtreeColumn, /* xColumn - read data */
144579 rtreeRowid, /* xRowid - read data */
144580 rtreeUpdate, /* xUpdate - write data */
144581 0, /* xBegin - begin transaction */
144582 0, /* xSync - sync transaction */
144583 0, /* xCommit - commit transaction */
144584 0, /* xRollback - rollback transaction */
144585 0, /* xFindFunction - function overloading */
144586 rtreeRename, /* xRename - rename the table */
144587 0, /* xSavepoint */
144588 0, /* xRelease */
144589 0 /* xRollbackTo */
144592 static int rtreeSqlInit(
144593 Rtree *pRtree,
144594 sqlite3 *db,
144595 const char *zDb,
144596 const char *zPrefix,
144597 int isCreate
144599 int rc = SQLITE_OK;
144601 #define N_STATEMENT 9
144602 static const char *azSql[N_STATEMENT] = {
144603 /* Read and write the xxx_node table */
144604 "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
144605 "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
144606 "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
144608 /* Read and write the xxx_rowid table */
144609 "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
144610 "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
144611 "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
144613 /* Read and write the xxx_parent table */
144614 "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
144615 "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
144616 "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
144618 sqlite3_stmt **appStmt[N_STATEMENT];
144619 int i;
144621 pRtree->db = db;
144623 if( isCreate ){
144624 char *zCreate = sqlite3_mprintf(
144625 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
144626 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
144627 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
144628 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
144629 zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
144631 if( !zCreate ){
144632 return SQLITE_NOMEM;
144634 rc = sqlite3_exec(db, zCreate, 0, 0, 0);
144635 sqlite3_free(zCreate);
144636 if( rc!=SQLITE_OK ){
144637 return rc;
144641 appStmt[0] = &pRtree->pReadNode;
144642 appStmt[1] = &pRtree->pWriteNode;
144643 appStmt[2] = &pRtree->pDeleteNode;
144644 appStmt[3] = &pRtree->pReadRowid;
144645 appStmt[4] = &pRtree->pWriteRowid;
144646 appStmt[5] = &pRtree->pDeleteRowid;
144647 appStmt[6] = &pRtree->pReadParent;
144648 appStmt[7] = &pRtree->pWriteParent;
144649 appStmt[8] = &pRtree->pDeleteParent;
144651 rc = rtreeQueryStat1(db, pRtree);
144652 for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
144653 char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
144654 if( zSql ){
144655 rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
144656 }else{
144657 rc = SQLITE_NOMEM;
144659 sqlite3_free(zSql);
144662 return rc;
144666 ** The second argument to this function contains the text of an SQL statement
144667 ** that returns a single integer value. The statement is compiled and executed
144668 ** using database connection db. If successful, the integer value returned
144669 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
144670 ** code is returned and the value of *piVal after returning is not defined.
144672 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
144673 int rc = SQLITE_NOMEM;
144674 if( zSql ){
144675 sqlite3_stmt *pStmt = 0;
144676 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
144677 if( rc==SQLITE_OK ){
144678 if( SQLITE_ROW==sqlite3_step(pStmt) ){
144679 *piVal = sqlite3_column_int(pStmt, 0);
144681 rc = sqlite3_finalize(pStmt);
144684 return rc;
144688 ** This function is called from within the xConnect() or xCreate() method to
144689 ** determine the node-size used by the rtree table being created or connected
144690 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
144691 ** Otherwise, an SQLite error code is returned.
144693 ** If this function is being called as part of an xConnect(), then the rtree
144694 ** table already exists. In this case the node-size is determined by inspecting
144695 ** the root node of the tree.
144697 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
144698 ** This ensures that each node is stored on a single database page. If the
144699 ** database page-size is so large that more than RTREE_MAXCELLS entries
144700 ** would fit in a single node, use a smaller node-size.
144702 static int getNodeSize(
144703 sqlite3 *db, /* Database handle */
144704 Rtree *pRtree, /* Rtree handle */
144705 int isCreate, /* True for xCreate, false for xConnect */
144706 char **pzErr /* OUT: Error message, if any */
144708 int rc;
144709 char *zSql;
144710 if( isCreate ){
144711 int iPageSize = 0;
144712 zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
144713 rc = getIntFromStmt(db, zSql, &iPageSize);
144714 if( rc==SQLITE_OK ){
144715 pRtree->iNodeSize = iPageSize-64;
144716 if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
144717 pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
144719 }else{
144720 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
144722 }else{
144723 zSql = sqlite3_mprintf(
144724 "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
144725 pRtree->zDb, pRtree->zName
144727 rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
144728 if( rc!=SQLITE_OK ){
144729 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
144733 sqlite3_free(zSql);
144734 return rc;
144738 ** This function is the implementation of both the xConnect and xCreate
144739 ** methods of the r-tree virtual table.
144741 ** argv[0] -> module name
144742 ** argv[1] -> database name
144743 ** argv[2] -> table name
144744 ** argv[...] -> column names...
144746 static int rtreeInit(
144747 sqlite3 *db, /* Database connection */
144748 void *pAux, /* One of the RTREE_COORD_* constants */
144749 int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
144750 sqlite3_vtab **ppVtab, /* OUT: New virtual table */
144751 char **pzErr, /* OUT: Error message, if any */
144752 int isCreate /* True for xCreate, false for xConnect */
144754 int rc = SQLITE_OK;
144755 Rtree *pRtree;
144756 int nDb; /* Length of string argv[1] */
144757 int nName; /* Length of string argv[2] */
144758 int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
144760 const char *aErrMsg[] = {
144761 0, /* 0 */
144762 "Wrong number of columns for an rtree table", /* 1 */
144763 "Too few columns for an rtree table", /* 2 */
144764 "Too many columns for an rtree table" /* 3 */
144767 int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
144768 if( aErrMsg[iErr] ){
144769 *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
144770 return SQLITE_ERROR;
144773 sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
144775 /* Allocate the sqlite3_vtab structure */
144776 nDb = (int)strlen(argv[1]);
144777 nName = (int)strlen(argv[2]);
144778 pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
144779 if( !pRtree ){
144780 return SQLITE_NOMEM;
144782 memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
144783 pRtree->nBusy = 1;
144784 pRtree->base.pModule = &rtreeModule;
144785 pRtree->zDb = (char *)&pRtree[1];
144786 pRtree->zName = &pRtree->zDb[nDb+1];
144787 pRtree->nDim = (argc-4)/2;
144788 pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
144789 pRtree->eCoordType = eCoordType;
144790 memcpy(pRtree->zDb, argv[1], nDb);
144791 memcpy(pRtree->zName, argv[2], nName);
144793 /* Figure out the node size to use. */
144794 rc = getNodeSize(db, pRtree, isCreate, pzErr);
144796 /* Create/Connect to the underlying relational database schema. If
144797 ** that is successful, call sqlite3_declare_vtab() to configure
144798 ** the r-tree table schema.
144800 if( rc==SQLITE_OK ){
144801 if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
144802 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
144803 }else{
144804 char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
144805 char *zTmp;
144806 int ii;
144807 for(ii=4; zSql && ii<argc; ii++){
144808 zTmp = zSql;
144809 zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
144810 sqlite3_free(zTmp);
144812 if( zSql ){
144813 zTmp = zSql;
144814 zSql = sqlite3_mprintf("%s);", zTmp);
144815 sqlite3_free(zTmp);
144817 if( !zSql ){
144818 rc = SQLITE_NOMEM;
144819 }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
144820 *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
144822 sqlite3_free(zSql);
144826 if( rc==SQLITE_OK ){
144827 *ppVtab = (sqlite3_vtab *)pRtree;
144828 }else{
144829 rtreeRelease(pRtree);
144831 return rc;
144836 ** Implementation of a scalar function that decodes r-tree nodes to
144837 ** human readable strings. This can be used for debugging and analysis.
144839 ** The scalar function takes two arguments, a blob of data containing
144840 ** an r-tree node, and the number of dimensions the r-tree indexes.
144841 ** For a two-dimensional r-tree structure called "rt", to deserialize
144842 ** all nodes, a statement like:
144844 ** SELECT rtreenode(2, data) FROM rt_node;
144846 ** The human readable string takes the form of a Tcl list with one
144847 ** entry for each cell in the r-tree node. Each entry is itself a
144848 ** list, containing the 8-byte rowid/pageno followed by the
144849 ** <num-dimension>*2 coordinates.
144851 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
144852 char *zText = 0;
144853 RtreeNode node;
144854 Rtree tree;
144855 int ii;
144857 UNUSED_PARAMETER(nArg);
144858 memset(&node, 0, sizeof(RtreeNode));
144859 memset(&tree, 0, sizeof(Rtree));
144860 tree.nDim = sqlite3_value_int(apArg[0]);
144861 tree.nBytesPerCell = 8 + 8 * tree.nDim;
144862 node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
144864 for(ii=0; ii<NCELL(&node); ii++){
144865 char zCell[512];
144866 int nCell = 0;
144867 RtreeCell cell;
144868 int jj;
144870 nodeGetCell(&tree, &node, ii, &cell);
144871 sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
144872 nCell = (int)strlen(zCell);
144873 for(jj=0; jj<tree.nDim*2; jj++){
144874 #ifndef SQLITE_RTREE_INT_ONLY
144875 sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
144876 (double)cell.aCoord[jj].f);
144877 #else
144878 sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
144879 cell.aCoord[jj].i);
144880 #endif
144881 nCell = (int)strlen(zCell);
144884 if( zText ){
144885 char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
144886 sqlite3_free(zText);
144887 zText = zTextNew;
144888 }else{
144889 zText = sqlite3_mprintf("{%s}", zCell);
144893 sqlite3_result_text(ctx, zText, -1, sqlite3_free);
144896 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
144897 UNUSED_PARAMETER(nArg);
144898 if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
144899 || sqlite3_value_bytes(apArg[0])<2
144901 sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
144902 }else{
144903 u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
144904 sqlite3_result_int(ctx, readInt16(zBlob));
144909 ** Register the r-tree module with database handle db. This creates the
144910 ** virtual table module "rtree" and the debugging/analysis scalar
144911 ** function "rtreenode".
144913 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
144914 const int utf8 = SQLITE_UTF8;
144915 int rc;
144917 rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
144918 if( rc==SQLITE_OK ){
144919 rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
144921 if( rc==SQLITE_OK ){
144922 #ifdef SQLITE_RTREE_INT_ONLY
144923 void *c = (void *)RTREE_COORD_INT32;
144924 #else
144925 void *c = (void *)RTREE_COORD_REAL32;
144926 #endif
144927 rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
144929 if( rc==SQLITE_OK ){
144930 void *c = (void *)RTREE_COORD_INT32;
144931 rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
144934 return rc;
144938 ** A version of sqlite3_free() that can be used as a callback. This is used
144939 ** in two places - as the destructor for the blob value returned by the
144940 ** invocation of a geometry function, and as the destructor for the geometry
144941 ** functions themselves.
144943 static void doSqlite3Free(void *p){
144944 sqlite3_free(p);
144948 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
144949 ** scalar user function. This C function is the callback used for all such
144950 ** registered SQL functions.
144952 ** The scalar user functions return a blob that is interpreted by r-tree
144953 ** table MATCH operators.
144955 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
144956 RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
144957 RtreeMatchArg *pBlob;
144958 int nBlob;
144960 nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
144961 pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
144962 if( !pBlob ){
144963 sqlite3_result_error_nomem(ctx);
144964 }else{
144965 int i;
144966 pBlob->magic = RTREE_GEOMETRY_MAGIC;
144967 pBlob->xGeom = pGeomCtx->xGeom;
144968 pBlob->pContext = pGeomCtx->pContext;
144969 pBlob->nParam = nArg;
144970 for(i=0; i<nArg; i++){
144971 #ifdef SQLITE_RTREE_INT_ONLY
144972 pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
144973 #else
144974 pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
144975 #endif
144977 sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
144982 ** Register a new geometry function for use with the r-tree MATCH operator.
144984 SQLITE_API int sqlite3_rtree_geometry_callback(
144985 sqlite3 *db,
144986 const char *zGeom,
144987 int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
144988 void *pContext
144990 RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
144992 /* Allocate and populate the context object. */
144993 pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
144994 if( !pGeomCtx ) return SQLITE_NOMEM;
144995 pGeomCtx->xGeom = xGeom;
144996 pGeomCtx->pContext = pContext;
144998 /* Create the new user-function. Register a destructor function to delete
144999 ** the context object when it is no longer required. */
145000 return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
145001 (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
145005 #if !SQLITE_CORE
145006 #ifdef _WIN32
145007 __declspec(dllexport)
145008 #endif
145009 SQLITE_API int sqlite3_rtree_init(
145010 sqlite3 *db,
145011 char **pzErrMsg,
145012 const sqlite3_api_routines *pApi
145014 SQLITE_EXTENSION_INIT2(pApi)
145015 return sqlite3RtreeInit(db);
145017 #endif
145019 #endif
145021 /************** End of rtree.c ***********************************************/
145022 /************** Begin file icu.c *********************************************/
145024 ** 2007 May 6
145026 ** The author disclaims copyright to this source code. In place of
145027 ** a legal notice, here is a blessing:
145029 ** May you do good and not evil.
145030 ** May you find forgiveness for yourself and forgive others.
145031 ** May you share freely, never taking more than you give.
145033 *************************************************************************
145034 ** Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp
145036 ** This file implements an integration between the ICU library
145037 ** ("International Components for Unicode", an open-source library
145038 ** for handling unicode data) and SQLite. The integration uses
145039 ** ICU to provide the following to SQLite:
145041 ** * An implementation of the SQL regexp() function (and hence REGEXP
145042 ** operator) using the ICU uregex_XX() APIs.
145044 ** * Implementations of the SQL scalar upper() and lower() functions
145045 ** for case mapping.
145047 ** * Integration of ICU and SQLite collation sequences.
145049 ** * An implementation of the LIKE operator that uses ICU to
145050 ** provide case-independent matching.
145053 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
145055 /* Include ICU headers */
145056 #include <unicode/utypes.h>
145057 #include <unicode/uregex.h>
145058 #include <unicode/ustring.h>
145059 #include <unicode/ucol.h>
145061 /* #include <assert.h> */
145063 #ifndef SQLITE_CORE
145064 SQLITE_EXTENSION_INIT1
145065 #else
145066 #endif
145069 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
145070 ** operator.
145072 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
145073 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
145074 #endif
145077 ** Version of sqlite3_free() that is always a function, never a macro.
145079 static void xFree(void *p){
145080 sqlite3_free(p);
145084 ** Compare two UTF-8 strings for equality where the first string is
145085 ** a "LIKE" expression. Return true (1) if they are the same and
145086 ** false (0) if they are different.
145088 static int icuLikeCompare(
145089 const uint8_t *zPattern, /* LIKE pattern */
145090 const uint8_t *zString, /* The UTF-8 string to compare against */
145091 const UChar32 uEsc /* The escape character */
145093 static const int MATCH_ONE = (UChar32)'_';
145094 static const int MATCH_ALL = (UChar32)'%';
145096 int iPattern = 0; /* Current byte index in zPattern */
145097 int iString = 0; /* Current byte index in zString */
145099 int prevEscape = 0; /* True if the previous character was uEsc */
145101 while( zPattern[iPattern]!=0 ){
145103 /* Read (and consume) the next character from the input pattern. */
145104 UChar32 uPattern;
145105 U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
145106 assert(uPattern!=0);
145108 /* There are now 4 possibilities:
145110 ** 1. uPattern is an unescaped match-all character "%",
145111 ** 2. uPattern is an unescaped match-one character "_",
145112 ** 3. uPattern is an unescaped escape character, or
145113 ** 4. uPattern is to be handled as an ordinary character
145115 if( !prevEscape && uPattern==MATCH_ALL ){
145116 /* Case 1. */
145117 uint8_t c;
145119 /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
145120 ** MATCH_ALL. For each MATCH_ONE, skip one character in the
145121 ** test string.
145123 while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
145124 if( c==MATCH_ONE ){
145125 if( zString[iString]==0 ) return 0;
145126 U8_FWD_1_UNSAFE(zString, iString);
145128 iPattern++;
145131 if( zPattern[iPattern]==0 ) return 1;
145133 while( zString[iString] ){
145134 if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
145135 return 1;
145137 U8_FWD_1_UNSAFE(zString, iString);
145139 return 0;
145141 }else if( !prevEscape && uPattern==MATCH_ONE ){
145142 /* Case 2. */
145143 if( zString[iString]==0 ) return 0;
145144 U8_FWD_1_UNSAFE(zString, iString);
145146 }else if( !prevEscape && uPattern==uEsc){
145147 /* Case 3. */
145148 prevEscape = 1;
145150 }else{
145151 /* Case 4. */
145152 UChar32 uString;
145153 U8_NEXT_UNSAFE(zString, iString, uString);
145154 uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
145155 uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
145156 if( uString!=uPattern ){
145157 return 0;
145159 prevEscape = 0;
145163 return zString[iString]==0;
145167 ** Implementation of the like() SQL function. This function implements
145168 ** the build-in LIKE operator. The first argument to the function is the
145169 ** pattern and the second argument is the string. So, the SQL statements:
145171 ** A LIKE B
145173 ** is implemented as like(B, A). If there is an escape character E,
145175 ** A LIKE B ESCAPE E
145177 ** is mapped to like(B, A, E).
145179 static void icuLikeFunc(
145180 sqlite3_context *context,
145181 int argc,
145182 sqlite3_value **argv
145184 const unsigned char *zA = sqlite3_value_text(argv[0]);
145185 const unsigned char *zB = sqlite3_value_text(argv[1]);
145186 UChar32 uEsc = 0;
145188 /* Limit the length of the LIKE or GLOB pattern to avoid problems
145189 ** of deep recursion and N*N behavior in patternCompare().
145191 if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
145192 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
145193 return;
145197 if( argc==3 ){
145198 /* The escape character string must consist of a single UTF-8 character.
145199 ** Otherwise, return an error.
145201 int nE= sqlite3_value_bytes(argv[2]);
145202 const unsigned char *zE = sqlite3_value_text(argv[2]);
145203 int i = 0;
145204 if( zE==0 ) return;
145205 U8_NEXT(zE, i, nE, uEsc);
145206 if( i!=nE){
145207 sqlite3_result_error(context,
145208 "ESCAPE expression must be a single character", -1);
145209 return;
145213 if( zA && zB ){
145214 sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
145219 ** This function is called when an ICU function called from within
145220 ** the implementation of an SQL scalar function returns an error.
145222 ** The scalar function context passed as the first argument is
145223 ** loaded with an error message based on the following two args.
145225 static void icuFunctionError(
145226 sqlite3_context *pCtx, /* SQLite scalar function context */
145227 const char *zName, /* Name of ICU function that failed */
145228 UErrorCode e /* Error code returned by ICU function */
145230 char zBuf[128];
145231 sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
145232 zBuf[127] = '\0';
145233 sqlite3_result_error(pCtx, zBuf, -1);
145237 ** Function to delete compiled regexp objects. Registered as
145238 ** a destructor function with sqlite3_set_auxdata().
145240 static void icuRegexpDelete(void *p){
145241 URegularExpression *pExpr = (URegularExpression *)p;
145242 uregex_close(pExpr);
145246 ** Implementation of SQLite REGEXP operator. This scalar function takes
145247 ** two arguments. The first is a regular expression pattern to compile
145248 ** the second is a string to match against that pattern. If either
145249 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
145250 ** is 1 if the string matches the pattern, or 0 otherwise.
145252 ** SQLite maps the regexp() function to the regexp() operator such
145253 ** that the following two are equivalent:
145255 ** zString REGEXP zPattern
145256 ** regexp(zPattern, zString)
145258 ** Uses the following ICU regexp APIs:
145260 ** uregex_open()
145261 ** uregex_matches()
145262 ** uregex_close()
145264 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
145265 UErrorCode status = U_ZERO_ERROR;
145266 URegularExpression *pExpr;
145267 UBool res;
145268 const UChar *zString = sqlite3_value_text16(apArg[1]);
145270 (void)nArg; /* Unused parameter */
145272 /* If the left hand side of the regexp operator is NULL,
145273 ** then the result is also NULL.
145275 if( !zString ){
145276 return;
145279 pExpr = sqlite3_get_auxdata(p, 0);
145280 if( !pExpr ){
145281 const UChar *zPattern = sqlite3_value_text16(apArg[0]);
145282 if( !zPattern ){
145283 return;
145285 pExpr = uregex_open(zPattern, -1, 0, 0, &status);
145287 if( U_SUCCESS(status) ){
145288 sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
145289 }else{
145290 assert(!pExpr);
145291 icuFunctionError(p, "uregex_open", status);
145292 return;
145296 /* Configure the text that the regular expression operates on. */
145297 uregex_setText(pExpr, zString, -1, &status);
145298 if( !U_SUCCESS(status) ){
145299 icuFunctionError(p, "uregex_setText", status);
145300 return;
145303 /* Attempt the match */
145304 res = uregex_matches(pExpr, 0, &status);
145305 if( !U_SUCCESS(status) ){
145306 icuFunctionError(p, "uregex_matches", status);
145307 return;
145310 /* Set the text that the regular expression operates on to a NULL
145311 ** pointer. This is not really necessary, but it is tidier than
145312 ** leaving the regular expression object configured with an invalid
145313 ** pointer after this function returns.
145315 uregex_setText(pExpr, 0, 0, &status);
145317 /* Return 1 or 0. */
145318 sqlite3_result_int(p, res ? 1 : 0);
145322 ** Implementations of scalar functions for case mapping - upper() and
145323 ** lower(). Function upper() converts its input to upper-case (ABC).
145324 ** Function lower() converts to lower-case (abc).
145326 ** ICU provides two types of case mapping, "general" case mapping and
145327 ** "language specific". Refer to ICU documentation for the differences
145328 ** between the two.
145330 ** To utilise "general" case mapping, the upper() or lower() scalar
145331 ** functions are invoked with one argument:
145333 ** upper('ABC') -> 'abc'
145334 ** lower('abc') -> 'ABC'
145336 ** To access ICU "language specific" case mapping, upper() or lower()
145337 ** should be invoked with two arguments. The second argument is the name
145338 ** of the locale to use. Passing an empty string ("") or SQL NULL value
145339 ** as the second argument is the same as invoking the 1 argument version
145340 ** of upper() or lower().
145342 ** lower('I', 'en_us') -> 'i'
145343 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
145345 ** http://www.icu-project.org/userguide/posix.html#case_mappings
145347 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
145348 const UChar *zInput;
145349 UChar *zOutput;
145350 int nInput;
145351 int nOutput;
145353 UErrorCode status = U_ZERO_ERROR;
145354 const char *zLocale = 0;
145356 assert(nArg==1 || nArg==2);
145357 if( nArg==2 ){
145358 zLocale = (const char *)sqlite3_value_text(apArg[1]);
145361 zInput = sqlite3_value_text16(apArg[0]);
145362 if( !zInput ){
145363 return;
145365 nInput = sqlite3_value_bytes16(apArg[0]);
145367 nOutput = nInput * 2 + 2;
145368 zOutput = sqlite3_malloc(nOutput);
145369 if( !zOutput ){
145370 return;
145373 if( sqlite3_user_data(p) ){
145374 u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
145375 }else{
145376 u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
145379 if( !U_SUCCESS(status) ){
145380 icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
145381 return;
145384 sqlite3_result_text16(p, zOutput, -1, xFree);
145388 ** Collation sequence destructor function. The pCtx argument points to
145389 ** a UCollator structure previously allocated using ucol_open().
145391 static void icuCollationDel(void *pCtx){
145392 UCollator *p = (UCollator *)pCtx;
145393 ucol_close(p);
145397 ** Collation sequence comparison function. The pCtx argument points to
145398 ** a UCollator structure previously allocated using ucol_open().
145400 static int icuCollationColl(
145401 void *pCtx,
145402 int nLeft,
145403 const void *zLeft,
145404 int nRight,
145405 const void *zRight
145407 UCollationResult res;
145408 UCollator *p = (UCollator *)pCtx;
145409 res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
145410 switch( res ){
145411 case UCOL_LESS: return -1;
145412 case UCOL_GREATER: return +1;
145413 case UCOL_EQUAL: return 0;
145415 assert(!"Unexpected return value from ucol_strcoll()");
145416 return 0;
145420 ** Implementation of the scalar function icu_load_collation().
145422 ** This scalar function is used to add ICU collation based collation
145423 ** types to an SQLite database connection. It is intended to be called
145424 ** as follows:
145426 ** SELECT icu_load_collation(<locale>, <collation-name>);
145428 ** Where <locale> is a string containing an ICU locale identifier (i.e.
145429 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
145430 ** collation sequence to create.
145432 static void icuLoadCollation(
145433 sqlite3_context *p,
145434 int nArg,
145435 sqlite3_value **apArg
145437 sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
145438 UErrorCode status = U_ZERO_ERROR;
145439 const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
145440 const char *zName; /* SQL Collation sequence name (eg. "japanese") */
145441 UCollator *pUCollator; /* ICU library collation object */
145442 int rc; /* Return code from sqlite3_create_collation_x() */
145444 assert(nArg==2);
145445 zLocale = (const char *)sqlite3_value_text(apArg[0]);
145446 zName = (const char *)sqlite3_value_text(apArg[1]);
145448 if( !zLocale || !zName ){
145449 return;
145452 pUCollator = ucol_open(zLocale, &status);
145453 if( !U_SUCCESS(status) ){
145454 icuFunctionError(p, "ucol_open", status);
145455 return;
145457 assert(p);
145459 rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
145460 icuCollationColl, icuCollationDel
145462 if( rc!=SQLITE_OK ){
145463 ucol_close(pUCollator);
145464 sqlite3_result_error(p, "Error registering collation function", -1);
145469 ** Register the ICU extension functions with database db.
145471 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
145472 struct IcuScalar {
145473 const char *zName; /* Function name */
145474 int nArg; /* Number of arguments */
145475 int enc; /* Optimal text encoding */
145476 void *pContext; /* sqlite3_user_data() context */
145477 void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
145478 } scalars[] = {
145479 {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
145481 {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
145482 {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
145483 {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
145484 {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
145486 {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
145487 {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
145488 {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
145489 {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
145491 {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
145492 {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
145494 {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
145497 int rc = SQLITE_OK;
145498 int i;
145500 for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
145501 struct IcuScalar *p = &scalars[i];
145502 rc = sqlite3_create_function(
145503 db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
145507 return rc;
145510 #if !SQLITE_CORE
145511 #ifdef _WIN32
145512 __declspec(dllexport)
145513 #endif
145514 SQLITE_API int sqlite3_icu_init(
145515 sqlite3 *db,
145516 char **pzErrMsg,
145517 const sqlite3_api_routines *pApi
145519 SQLITE_EXTENSION_INIT2(pApi)
145520 return sqlite3IcuInit(db);
145522 #endif
145524 #endif
145526 /************** End of icu.c *************************************************/
145527 /************** Begin file fts3_icu.c ****************************************/
145529 ** 2007 June 22
145531 ** The author disclaims copyright to this source code. In place of
145532 ** a legal notice, here is a blessing:
145534 ** May you do good and not evil.
145535 ** May you find forgiveness for yourself and forgive others.
145536 ** May you share freely, never taking more than you give.
145538 *************************************************************************
145539 ** This file implements a tokenizer for fts3 based on the ICU library.
145541 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
145542 #ifdef SQLITE_ENABLE_ICU
145544 /* #include <assert.h> */
145545 /* #include <string.h> */
145547 #include <unicode/ubrk.h>
145548 /* #include <unicode/ucol.h> */
145549 /* #include <unicode/ustring.h> */
145550 #include <unicode/utf16.h>
145552 typedef struct IcuTokenizer IcuTokenizer;
145553 typedef struct IcuCursor IcuCursor;
145555 struct IcuTokenizer {
145556 sqlite3_tokenizer base;
145557 char *zLocale;
145560 struct IcuCursor {
145561 sqlite3_tokenizer_cursor base;
145563 UBreakIterator *pIter; /* ICU break-iterator object */
145564 int nChar; /* Number of UChar elements in pInput */
145565 UChar *aChar; /* Copy of input using utf-16 encoding */
145566 int *aOffset; /* Offsets of each character in utf-8 input */
145568 int nBuffer;
145569 char *zBuffer;
145571 int iToken;
145575 ** Create a new tokenizer instance.
145577 static int icuCreate(
145578 int argc, /* Number of entries in argv[] */
145579 const char * const *argv, /* Tokenizer creation arguments */
145580 sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
145582 IcuTokenizer *p;
145583 int n = 0;
145585 if( argc>0 ){
145586 n = strlen(argv[0])+1;
145588 p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
145589 if( !p ){
145590 return SQLITE_NOMEM;
145592 memset(p, 0, sizeof(IcuTokenizer));
145594 if( n ){
145595 p->zLocale = (char *)&p[1];
145596 memcpy(p->zLocale, argv[0], n);
145599 *ppTokenizer = (sqlite3_tokenizer *)p;
145601 return SQLITE_OK;
145605 ** Destroy a tokenizer
145607 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
145608 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
145609 sqlite3_free(p);
145610 return SQLITE_OK;
145614 ** Prepare to begin tokenizing a particular string. The input
145615 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
145616 ** used to incrementally tokenize this string is returned in
145617 ** *ppCursor.
145619 static int icuOpen(
145620 sqlite3_tokenizer *pTokenizer, /* The tokenizer */
145621 const char *zInput, /* Input string */
145622 int nInput, /* Length of zInput in bytes */
145623 sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
145625 IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
145626 IcuCursor *pCsr;
145628 const int32_t opt = U_FOLD_CASE_DEFAULT;
145629 UErrorCode status = U_ZERO_ERROR;
145630 int nChar;
145632 UChar32 c;
145633 int iInput = 0;
145634 int iOut = 0;
145636 *ppCursor = 0;
145638 if( zInput==0 ){
145639 nInput = 0;
145640 zInput = "";
145641 }else if( nInput<0 ){
145642 nInput = strlen(zInput);
145644 nChar = nInput+1;
145645 pCsr = (IcuCursor *)sqlite3_malloc(
145646 sizeof(IcuCursor) + /* IcuCursor */
145647 ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
145648 (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
145650 if( !pCsr ){
145651 return SQLITE_NOMEM;
145653 memset(pCsr, 0, sizeof(IcuCursor));
145654 pCsr->aChar = (UChar *)&pCsr[1];
145655 pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
145657 pCsr->aOffset[iOut] = iInput;
145658 U8_NEXT(zInput, iInput, nInput, c);
145659 while( c>0 ){
145660 int isError = 0;
145661 c = u_foldCase(c, opt);
145662 U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
145663 if( isError ){
145664 sqlite3_free(pCsr);
145665 return SQLITE_ERROR;
145667 pCsr->aOffset[iOut] = iInput;
145669 if( iInput<nInput ){
145670 U8_NEXT(zInput, iInput, nInput, c);
145671 }else{
145672 c = 0;
145676 pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
145677 if( !U_SUCCESS(status) ){
145678 sqlite3_free(pCsr);
145679 return SQLITE_ERROR;
145681 pCsr->nChar = iOut;
145683 ubrk_first(pCsr->pIter);
145684 *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
145685 return SQLITE_OK;
145689 ** Close a tokenization cursor previously opened by a call to icuOpen().
145691 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
145692 IcuCursor *pCsr = (IcuCursor *)pCursor;
145693 ubrk_close(pCsr->pIter);
145694 sqlite3_free(pCsr->zBuffer);
145695 sqlite3_free(pCsr);
145696 return SQLITE_OK;
145700 ** Extract the next token from a tokenization cursor.
145702 static int icuNext(
145703 sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
145704 const char **ppToken, /* OUT: *ppToken is the token text */
145705 int *pnBytes, /* OUT: Number of bytes in token */
145706 int *piStartOffset, /* OUT: Starting offset of token */
145707 int *piEndOffset, /* OUT: Ending offset of token */
145708 int *piPosition /* OUT: Position integer of token */
145710 IcuCursor *pCsr = (IcuCursor *)pCursor;
145712 int iStart = 0;
145713 int iEnd = 0;
145714 int nByte = 0;
145716 while( iStart==iEnd ){
145717 UChar32 c;
145719 iStart = ubrk_current(pCsr->pIter);
145720 iEnd = ubrk_next(pCsr->pIter);
145721 if( iEnd==UBRK_DONE ){
145722 return SQLITE_DONE;
145725 while( iStart<iEnd ){
145726 int iWhite = iStart;
145727 U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
145728 if( u_isspace(c) ){
145729 iStart = iWhite;
145730 }else{
145731 break;
145734 assert(iStart<=iEnd);
145738 UErrorCode status = U_ZERO_ERROR;
145739 if( nByte ){
145740 char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
145741 if( !zNew ){
145742 return SQLITE_NOMEM;
145744 pCsr->zBuffer = zNew;
145745 pCsr->nBuffer = nByte;
145748 u_strToUTF8(
145749 pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
145750 &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
145751 &status /* Output success/failure */
145753 } while( nByte>pCsr->nBuffer );
145755 *ppToken = pCsr->zBuffer;
145756 *pnBytes = nByte;
145757 *piStartOffset = pCsr->aOffset[iStart];
145758 *piEndOffset = pCsr->aOffset[iEnd];
145759 *piPosition = pCsr->iToken++;
145761 return SQLITE_OK;
145765 ** The set of routines that implement the simple tokenizer
145767 static const sqlite3_tokenizer_module icuTokenizerModule = {
145768 0, /* iVersion */
145769 icuCreate, /* xCreate */
145770 icuDestroy, /* xCreate */
145771 icuOpen, /* xOpen */
145772 icuClose, /* xClose */
145773 icuNext, /* xNext */
145777 ** Set *ppModule to point at the implementation of the ICU tokenizer.
145779 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
145780 sqlite3_tokenizer_module const**ppModule
145782 *ppModule = &icuTokenizerModule;
145785 #endif /* defined(SQLITE_ENABLE_ICU) */
145786 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
145788 /************** End of fts3_icu.c ********************************************/